code
stringlengths
3
1.18M
language
stringclasses
1 value
package com.ch_linghu.fanfoudroid.util; import java.io.File; import java.io.IOException; import android.os.Environment; /** * 对SD卡文件的管理 * @author ch.linghu * */ public class FileHelper { private static final String TAG = "FileHelper"; private static final String BASE_PATH="fanfoudroid"; public static File getBasePath() throws IOException{ File basePath = new File(Environment.getExternalStorageDirectory(), BASE_PATH); if (!basePath.exists()){ if (!basePath.mkdirs()){ throw new IOException(String.format("%s cannot be created!", basePath.toString())); } } if (!basePath.isDirectory()){ throw new IOException(String.format("%s is not a directory!", basePath.toString())); } return basePath; } }
Java
package com.ch_linghu.fanfoudroid.util; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import android.util.Log; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; public class DateTimeHelper { private static final String TAG = "DateTimeHelper"; // Wed Dec 15 02:53:36 +0000 2010 public static final DateFormat TWITTER_DATE_FORMATTER = new SimpleDateFormat( "E MMM d HH:mm:ss Z yyyy", Locale.US); public static final DateFormat TWITTER_SEARCH_API_DATE_FORMATTER = new SimpleDateFormat( "E, d MMM yyyy HH:mm:ss Z", Locale.US); // TODO: Z -> z ? public static final Date parseDateTime(String dateString) { try { Log.v(TAG, String.format("in parseDateTime, dateString=%s", dateString)); return TWITTER_DATE_FORMATTER.parse(dateString); } catch (ParseException e) { Log.w(TAG, "Could not parse Twitter date string: " + dateString); return null; } } // Handle "yyyy-MM-dd'T'HH:mm:ss.SSS" from sqlite public static final Date parseDateTimeFromSqlite(String dateString) { try { Log.v(TAG, String.format("in parseDateTime, dateString=%s", dateString)); return TwitterDatabase.DB_DATE_FORMATTER.parse(dateString); } catch (ParseException e) { Log.w(TAG, "Could not parse Twitter date string: " + dateString); return null; } } public static final Date parseSearchApiDateTime(String dateString) { try { return TWITTER_SEARCH_API_DATE_FORMATTER.parse(dateString); } catch (ParseException e) { Log.w(TAG, "Could not parse Twitter search date string: " + dateString); return null; } } public static final DateFormat AGO_FULL_DATE_FORMATTER = new SimpleDateFormat( "yyyy-MM-dd HH:mm"); public static String getRelativeDate(Date date) { Date now = new Date(); String prefix = TwitterApplication.mContext .getString(R.string.tweet_created_at_beautify_prefix); String sec = TwitterApplication.mContext .getString(R.string.tweet_created_at_beautify_sec); String min = TwitterApplication.mContext .getString(R.string.tweet_created_at_beautify_min); String hour = TwitterApplication.mContext .getString(R.string.tweet_created_at_beautify_hour); String day = TwitterApplication.mContext .getString(R.string.tweet_created_at_beautify_day); String suffix = TwitterApplication.mContext .getString(R.string.tweet_created_at_beautify_suffix); // Seconds. long diff = (now.getTime() - date.getTime()) / 1000; if (diff < 0) { diff = 0; } if (diff < 60) { return diff + sec + suffix; } // Minutes. diff /= 60; if (diff < 60) { return prefix + diff + min + suffix; } // Hours. diff /= 60; if (diff < 24) { return prefix + diff + hour + suffix; } return AGO_FULL_DATE_FORMATTER.format(date); } public static long getNowTime() { return Calendar.getInstance().getTime().getTime(); } }
Java
/*** Copyright (c) 2008-2009 CommonsWare, LLC Portions (c) 2009 Google, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.commonsware.cwac.sacklist; import java.util.ArrayList; import java.util.List; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; /** * Adapter that simply returns row views from a list. * * If you supply a size, you must implement newView(), to * create a required view. The adapter will then cache these * views. * * If you supply a list of views in the constructor, that * list will be used directly. If any elements in the list * are null, then newView() will be called just for those * slots. * * Subclasses may also wish to override areAllItemsEnabled() * (default: false) and isEnabled() (default: false), if some * of their rows should be selectable. * * It is assumed each view is unique, and therefore will not * get recycled. * * Note that this adapter is not designed for long lists. It * is more for screens that should behave like a list. This * is particularly useful if you combine this with other * adapters (e.g., SectionedAdapter) that might have an * arbitrary number of rows, so it all appears seamless. */ public class SackOfViewsAdapter extends BaseAdapter { private List<View> views=null; /** * Constructor creating an empty list of views, but with * a specified count. Subclasses must override newView(). */ public SackOfViewsAdapter(int count) { super(); views=new ArrayList<View>(count); for (int i=0;i<count;i++) { views.add(null); } } /** * Constructor wrapping a supplied list of views. * Subclasses must override newView() if any of the elements * in the list are null. */ public SackOfViewsAdapter(List<View> views) { super(); this.views=views; } /** * Get the data item associated with the specified * position in the data set. * @param position Position of the item whose data we want */ @Override public Object getItem(int position) { return(views.get(position)); } /** * How many items are in the data set represented by this * Adapter. */ @Override public int getCount() { return(views.size()); } /** * Returns the number of types of Views that will be * created by getView(). */ @Override public int getViewTypeCount() { return(getCount()); } /** * Get the type of View that will be created by getView() * for the specified item. * @param position Position of the item whose data we want */ @Override public int getItemViewType(int position) { return(position); } /** * Are all items in this ListAdapter enabled? If yes it * means all items are selectable and clickable. */ @Override public boolean areAllItemsEnabled() { return(false); } /** * Returns true if the item at the specified position is * not a separator. * @param position Position of the item whose data we want */ @Override public boolean isEnabled(int position) { return(false); } /** * Get a View that displays the data at the specified * position in the data set. * @param position Position of the item whose data we want * @param convertView View to recycle, if not null * @param parent ViewGroup containing the returned View */ @Override public View getView(int position, View convertView, ViewGroup parent) { View result=views.get(position); if (result==null) { result=newView(position, parent); views.set(position, result); } return(result); } /** * Get the row id associated with the specified position * in the list. * @param position Position of the item whose data we want */ @Override public long getItemId(int position) { return(position); } /** * Create a new View to go into the list at the specified * position. * @param position Position of the item whose data we want * @param parent ViewGroup containing the returned View */ protected View newView(int position, ViewGroup parent) { throw new RuntimeException("You must override newView()!"); } }
Java
/*** Copyright (c) 2008-2009 CommonsWare, LLC Portions (c) 2009 Google, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.commonsware.cwac.merge; import java.util.ArrayList; import java.util.List; import android.database.DataSetObserver; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.SectionIndexer; import com.commonsware.cwac.sacklist.SackOfViewsAdapter; /** * Adapter that merges multiple child adapters and views * into a single contiguous whole. * * Adapters used as pieces within MergeAdapter must * have view type IDs monotonically increasing from 0. Ideally, * adapters also have distinct ranges for their row ids, as * returned by getItemId(). * */ public class MergeAdapter extends BaseAdapter implements SectionIndexer { private ArrayList<ListAdapter> pieces=new ArrayList<ListAdapter>(); /** * Stock constructor, simply chaining to the superclass. */ public MergeAdapter() { super(); } /** * Adds a new adapter to the roster of things to appear * in the aggregate list. * @param adapter Source for row views for this section */ public void addAdapter(ListAdapter adapter) { pieces.add(adapter); adapter.registerDataSetObserver(new CascadeDataSetObserver()); } /** * Adds a new View to the roster of things to appear * in the aggregate list. * @param view Single view to add */ public void addView(View view) { addView(view, false); } /** * Adds a new View to the roster of things to appear * in the aggregate list. * @param view Single view to add * @param enabled false if views are disabled, true if enabled */ public void addView(View view, boolean enabled) { ArrayList<View> list=new ArrayList<View>(1); list.add(view); addViews(list, enabled); } /** * Adds a list of views to the roster of things to appear * in the aggregate list. * @param views List of views to add */ public void addViews(List<View> views) { addViews(views, false); } /** * Adds a list of views to the roster of things to appear * in the aggregate list. * @param views List of views to add * @param enabled false if views are disabled, true if enabled */ public void addViews(List<View> views, boolean enabled) { if (enabled) { addAdapter(new EnabledSackAdapter(views)); } else { addAdapter(new SackOfViewsAdapter(views)); } } /** * Get the data item associated with the specified * position in the data set. * @param position Position of the item whose data we want */ @Override public Object getItem(int position) { for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { return(piece.getItem(position)); } position-=size; } return(null); } /** * Get the adapter associated with the specified * position in the data set. * @param position Position of the item whose adapter we want */ public ListAdapter getAdapter(int position) { for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { return(piece); } position-=size; } return(null); } /** * How many items are in the data set represented by this * Adapter. */ @Override public int getCount() { int total=0; for (ListAdapter piece : pieces) { total+=piece.getCount(); } return(total); } /** * Returns the number of types of Views that will be * created by getView(). */ @Override public int getViewTypeCount() { int total=0; for (ListAdapter piece : pieces) { total+=piece.getViewTypeCount(); } return(Math.max(total, 1)); // needed for setListAdapter() before content add' } /** * Get the type of View that will be created by getView() * for the specified item. * @param position Position of the item whose data we want */ @Override public int getItemViewType(int position) { int typeOffset=0; int result=-1; for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { result=typeOffset+piece.getItemViewType(position); break; } position-=size; typeOffset+=piece.getViewTypeCount(); } return(result); } /** * Are all items in this ListAdapter enabled? If yes it * means all items are selectable and clickable. */ @Override public boolean areAllItemsEnabled() { return(false); } /** * Returns true if the item at the specified position is * not a separator. * @param position Position of the item whose data we want */ @Override public boolean isEnabled(int position) { for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { return(piece.isEnabled(position)); } position-=size; } return(false); } /** * Get a View that displays the data at the specified * position in the data set. * @param position Position of the item whose data we want * @param convertView View to recycle, if not null * @param parent ViewGroup containing the returned View */ @Override public View getView(int position, View convertView, ViewGroup parent) { for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { return(piece.getView(position, convertView, parent)); } position-=size; } return(null); } /** * Get the row id associated with the specified position * in the list. * @param position Position of the item whose data we want */ @Override public long getItemId(int position) { for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { return(piece.getItemId(position)); } position-=size; } return(-1); } @Override public int getPositionForSection(int section) { int position=0; for (ListAdapter piece : pieces) { if (piece instanceof SectionIndexer) { Object[] sections=((SectionIndexer)piece).getSections(); int numSections=0; if (sections!=null) { numSections=sections.length; } if (section<numSections) { return(position+((SectionIndexer)piece).getPositionForSection(section)); } else if (sections!=null) { section-=numSections; } } position+=piece.getCount(); } return(0); } @Override public int getSectionForPosition(int position) { int section=0; for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { if (piece instanceof SectionIndexer) { return(section+((SectionIndexer)piece).getSectionForPosition(position)); } return(0); } else { if (piece instanceof SectionIndexer) { Object[] sections=((SectionIndexer)piece).getSections(); if (sections!=null) { section+=sections.length; } } } position-=size; } return(0); } @Override public Object[] getSections() { ArrayList<Object> sections=new ArrayList<Object>(); for (ListAdapter piece : pieces) { if (piece instanceof SectionIndexer) { Object[] curSections=((SectionIndexer)piece).getSections(); if (curSections!=null) { for (Object section : curSections) { sections.add(section); } } } } if (sections.size()==0) { return(null); } return(sections.toArray(new Object[0])); } private static class EnabledSackAdapter extends SackOfViewsAdapter { public EnabledSackAdapter(List<View> views) { super(views); } @Override public boolean areAllItemsEnabled() { return(true); } @Override public boolean isEnabled(int position) { return(true); } } private class CascadeDataSetObserver extends DataSetObserver { @Override public void onChanged() { notifyDataSetChanged(); } @Override public void onInvalidated() { notifyDataSetInvalidated(); } } }
Java
package com.hlidskialf.android.hardware; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; public class ShakeListener implements SensorEventListener { private static final int FORCE_THRESHOLD = 350; private static final int TIME_THRESHOLD = 100; private static final int SHAKE_TIMEOUT = 500; private static final int SHAKE_DURATION = 1000; private static final int SHAKE_COUNT = 3; private SensorManager mSensorMgr; private Sensor mSensor; private float mLastX = -1.0f, mLastY = -1.0f, mLastZ = -1.0f; private long mLastTime; private OnShakeListener mShakeListener; private Context mContext; private int mShakeCount = 0; private long mLastShake; private long mLastForce; public interface OnShakeListener { public void onShake(); } public ShakeListener(Context context) { mContext = context; resume(); } public void setOnShakeListener(OnShakeListener listener) { mShakeListener = listener; } public void resume() { mSensorMgr = (SensorManager) mContext .getSystemService(Context.SENSOR_SERVICE); mSensor = mSensorMgr .getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER); if (mSensorMgr == null) { throw new UnsupportedOperationException("Sensors not supported"); } boolean supported = mSensorMgr.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_GAME); if (!supported) { mSensorMgr.unregisterListener(this, mSensor); throw new UnsupportedOperationException( "Accelerometer not supported"); } } public void pause() { if (mSensorMgr != null) { mSensorMgr.unregisterListener(this, mSensor); mSensorMgr = null; } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } @Override public void onSensorChanged(SensorEvent event) { Sensor sensor = event.sensor; float[] values = event.values; if (sensor.getType() != SensorManager.SENSOR_ACCELEROMETER) return; long now = System.currentTimeMillis(); if ((now - mLastForce) > SHAKE_TIMEOUT) { mShakeCount = 0; } if ((now - mLastTime) > TIME_THRESHOLD) { long diff = now - mLastTime; float speed = Math.abs(values[SensorManager.DATA_X] + values[SensorManager.DATA_Y] + values[SensorManager.DATA_Z] - mLastX - mLastY - mLastZ) / diff * 10000; if (speed > FORCE_THRESHOLD) { if ((++mShakeCount >= SHAKE_COUNT) && (now - mLastShake > SHAKE_DURATION)) { mLastShake = now; mShakeCount = 0; if (mShakeListener != null) { mShakeListener.onShake(); } } mLastForce = now; } mLastTime = now; mLastX = values[SensorManager.DATA_X]; mLastY = values[SensorManager.DATA_Y]; mLastZ = values[SensorManager.DATA_Z]; } } }
Java
package polymorphism.services.user.co; public class User { private String id; private String name; private String email; private String gender; private String birth; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getBirth() { return birth; } public void setBirth(String birth) { this.birth = birth; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", email=" + email + ", gender=" + gender + ", birth=" + birth + "]"; } }
Java
package polymorphism.services.group.co; import java.sql.Timestamp; public class Group { private String id; private String name; private Timestamp begin; private Timestamp end; private String topic; private Integer maxMem; private Integer curMem; private String region; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Timestamp getBegin() { return begin; } public void setBegin(Timestamp begin) { this.begin = begin; } public Timestamp getEnd() { return end; } public void setEnd(Timestamp end) { this.end = end; } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public Integer getMaxMem() { return maxMem; } public void setMaxMem(Integer maxMem) { this.maxMem = maxMem; } public Integer getCurMem() { return curMem; } public void setCurMem(Integer curMem) { this.curMem = curMem; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } @Override public String toString() { return "Group [id=" + id + ", name=" + name + ", begin=" + begin + ", end=" + end + ", topic=" + topic + ", maxMem=" + maxMem + ", curMem=" + curMem + ", region=" + region + "]"; } }
Java
package org.poly2tri.triangulation.point.ardor3d; import java.util.ArrayList; import java.util.List; import org.poly2tri.geometry.polygon.PolygonPoint; import org.poly2tri.triangulation.TriangulationPoint; import com.ardor3d.math.Vector3; public class ArdorVector3PolygonPoint extends PolygonPoint { private final Vector3 _p; public ArdorVector3PolygonPoint( Vector3 point ) { super( point.getX(), point.getY() ); _p = point; } public final double getX() { return _p.getX(); } public final double getY() { return _p.getY(); } public final double getZ() { return _p.getZ(); } public final float getXf() { return _p.getXf(); } public final float getYf() { return _p.getYf(); } public final float getZf() { return _p.getZf(); } public static List<PolygonPoint> toPoints( Vector3[] vpoints ) { ArrayList<PolygonPoint> points = new ArrayList<PolygonPoint>(vpoints.length); for( int i=0; i<vpoints.length; i++ ) { points.add( new ArdorVector3PolygonPoint(vpoints[i]) ); } return points; } public static List<PolygonPoint> toPoints( ArrayList<Vector3> vpoints ) { int i=0; ArrayList<PolygonPoint> points = new ArrayList<PolygonPoint>(vpoints.size()); for( Vector3 point : vpoints ) { points.add( new ArdorVector3PolygonPoint(point) ); } return points; } }
Java
package org.poly2tri.triangulation.point.ardor3d; import java.util.ArrayList; import java.util.List; import org.poly2tri.triangulation.TriangulationPoint; import com.ardor3d.math.Vector3; public class ArdorVector3Point extends TriangulationPoint { private final Vector3 _p; public ArdorVector3Point( Vector3 point ) { _p = point; } public final double getX() { return _p.getX(); } public final double getY() { return _p.getY(); } public final double getZ() { return _p.getZ(); } public final float getXf() { return _p.getXf(); } public final float getYf() { return _p.getYf(); } public final float getZf() { return _p.getZf(); } @Override public void set( double x, double y, double z ) { _p.set( x, y, z ); } public static List<TriangulationPoint> toPoints( Vector3[] vpoints ) { ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(vpoints.length); for( int i=0; i<vpoints.length; i++ ) { points.add( new ArdorVector3Point(vpoints[i]) ); } return points; } public static List<TriangulationPoint> toPoints( ArrayList<Vector3> vpoints ) { int i=0; ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(vpoints.size()); for( Vector3 point : vpoints ) { points.add( new ArdorVector3Point(point) ); } return points; } public static List<TriangulationPoint> toPolygonPoints( Vector3[] vpoints ) { ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(vpoints.length); for( int i=0; i<vpoints.length; i++ ) { points.add( new ArdorVector3PolygonPoint(vpoints[i]) ); } return points; } public static List<TriangulationPoint> toPolygonPoints( ArrayList<Vector3> vpoints ) { int i=0; ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(vpoints.size()); for( Vector3 point : vpoints ) { points.add( new ArdorVector3PolygonPoint(point) ); } return points; } }
Java
package org.poly2tri.triangulation.tools.ardor3d; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.HashMap; import java.util.List; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.geometry.primitives.Point; import org.poly2tri.transform.coordinate.CoordinateTransform; import org.poly2tri.transform.coordinate.NoTransform; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.delaunay.DelaunayTriangle; import org.poly2tri.triangulation.point.TPoint; import org.poly2tri.triangulation.sets.PointSet; import com.ardor3d.math.Vector3; import com.ardor3d.renderer.IndexMode; import com.ardor3d.scenegraph.Mesh; import com.ardor3d.util.geom.BufferUtils; public class ArdorMeshMapper { private static final CoordinateTransform _ct = new NoTransform(); public static void updateTriangleMesh( Mesh mesh, List<DelaunayTriangle> triangles ) { updateTriangleMesh( mesh, triangles, _ct ); } public static void updateTriangleMesh( Mesh mesh, List<DelaunayTriangle> triangles, CoordinateTransform pc ) { FloatBuffer vertBuf; TPoint point; mesh.getMeshData().setIndexMode( IndexMode.Triangles ); if( triangles == null || triangles.size() == 0 ) { return; } point = new TPoint(0,0,0); int size = 3*3*triangles.size(); prepareVertexBuffer( mesh, size ); vertBuf = mesh.getMeshData().getVertexBuffer(); vertBuf.rewind(); for( DelaunayTriangle t : triangles ) { for( int i=0; i<3; i++ ) { pc.transform( t.points[i], point ); vertBuf.put(point.getXf()); vertBuf.put(point.getYf()); vertBuf.put(point.getZf()); } } } public static void updateFaceNormals( Mesh mesh, List<DelaunayTriangle> triangles ) { updateFaceNormals( mesh, triangles, _ct ); } public static void updateFaceNormals( Mesh mesh, List<DelaunayTriangle> triangles, CoordinateTransform pc ) { FloatBuffer nBuf; Vector3 fNormal; HashMap<DelaunayTriangle,Vector3> fnMap; int size = 3*3*triangles.size(); fnMap = calculateFaceNormals( triangles, pc ); prepareNormalBuffer( mesh, size ); nBuf = mesh.getMeshData().getNormalBuffer(); nBuf.rewind(); for( DelaunayTriangle t : triangles ) { fNormal = fnMap.get( t ); for( int i=0; i<3; i++ ) { nBuf.put(fNormal.getXf()); nBuf.put(fNormal.getYf()); nBuf.put(fNormal.getZf()); } } } public static void updateVertexNormals( Mesh mesh, List<DelaunayTriangle> triangles ) { updateVertexNormals( mesh, triangles, _ct ); } public static void updateVertexNormals( Mesh mesh, List<DelaunayTriangle> triangles, CoordinateTransform pc ) { FloatBuffer nBuf; TriangulationPoint vertex; Vector3 vNormal, fNormal; HashMap<DelaunayTriangle,Vector3> fnMap; HashMap<TriangulationPoint,Vector3> vnMap = new HashMap<TriangulationPoint,Vector3>(3*triangles.size()); int size = 3*3*triangles.size(); fnMap = calculateFaceNormals( triangles, pc ); // Calculate a vertex normal for each vertex for( DelaunayTriangle t : triangles ) { fNormal = fnMap.get( t ); for( int i=0; i<3; i++ ) { vertex = t.points[i]; vNormal = vnMap.get( vertex ); if( vNormal == null ) { vNormal = new Vector3( fNormal.getX(), fNormal.getY(), fNormal.getZ() ); vnMap.put( vertex, vNormal ); } else { vNormal.addLocal( fNormal ); } } } // Normalize all normals for( Vector3 normal : vnMap.values() ) { normal.normalizeLocal(); } prepareNormalBuffer( mesh, size ); nBuf = mesh.getMeshData().getNormalBuffer(); nBuf.rewind(); for( DelaunayTriangle t : triangles ) { for( int i=0; i<3; i++ ) { vertex = t.points[i]; vNormal = vnMap.get( vertex ); nBuf.put(vNormal.getXf()); nBuf.put(vNormal.getYf()); nBuf.put(vNormal.getZf()); } } } private static HashMap<DelaunayTriangle,Vector3> calculateFaceNormals( List<DelaunayTriangle> triangles, CoordinateTransform pc ) { HashMap<DelaunayTriangle,Vector3> normals = new HashMap<DelaunayTriangle,Vector3>(triangles.size()); TPoint point = new TPoint(0,0,0); // calculate the Face Normals for all triangles float x1,x2,x3,y1,y2,y3,z1,z2,z3,nx,ny,nz,ux,uy,uz,vx,vy,vz; double norm; for( DelaunayTriangle t : triangles ) { pc.transform( t.points[0], point ); x1 = point.getXf(); y1 = point.getYf(); z1 = point.getZf(); pc.transform( t.points[1], point ); x2 = point.getXf(); y2 = point.getYf(); z2 = point.getZf(); pc.transform( t.points[2], point ); x3 = point.getXf(); y3 = point.getYf(); z3 = point.getZf(); ux = x2 - x1; uy = y2 - y1; uz = z2 - z1; vx = x3 - x1; vy = y3 - y1; vz = z3 - z1; nx = uy*vz - uz*vy; ny = uz*vx - ux*vz; nz = ux*vy - uy*vx; norm = 1/Math.sqrt( nx*nx + ny*ny + nz*nz ); nx *= norm; ny *= norm; nz *= norm; normals.put( t, new Vector3(nx,ny,nz) ); } return normals; } /** * For now very primitive! * * Assumes a single texture and that the triangles form a xy-monotone surface * <p> * A continuous surface S in R3 is called xy-monotone, if every line parallel * to the z-axis intersects it at a single point at most. * * @param mesh * @param scale */ public static void updateTextureCoordinates( Mesh mesh, List<DelaunayTriangle> triangles, double scale, double angle ) { TriangulationPoint vertex; FloatBuffer tcBuf; float width,maxX,minX,maxY,minY,x,y,xn,yn; maxX = Float.NEGATIVE_INFINITY; minX = Float.POSITIVE_INFINITY; maxY = Float.NEGATIVE_INFINITY; minY = Float.POSITIVE_INFINITY; for( DelaunayTriangle t : triangles ) { for( int i=0; i<3; i++ ) { vertex = t.points[i]; x = vertex.getXf(); y = vertex.getYf(); maxX = x > maxX ? x : maxX; minX = x < minX ? x : minX; maxY = y > maxY ? y : maxY; minY = y < minY ? x : minY; } } width = maxX-minX > maxY-minY ? maxX-minX : maxY-minY; width *= scale; tcBuf = prepareTextureCoordinateBuffer(mesh,0,2*3*triangles.size()); tcBuf.rewind(); for( DelaunayTriangle t : triangles ) { for( int i=0; i<3; i++ ) { vertex = t.points[i]; x = vertex.getXf()-(maxX-minX)/2; y = vertex.getYf()-(maxY-minY)/2; xn = (float)(x*Math.cos(angle)-y*Math.sin(angle)); yn = (float)(y*Math.cos(angle)+x*Math.sin(angle)); tcBuf.put( xn/width ); tcBuf.put( yn/width ); } } } /** * Assuming: * 1. That given U anv V aren't collinear. * 2. That O,U and V can be projected in the XY plane * * @param mesh * @param triangles * @param o * @param u * @param v */ public static void updateTextureCoordinates( Mesh mesh, List<DelaunayTriangle> triangles, double scale, Point o, Point u, Point v ) { FloatBuffer tcBuf; float x,y,a,b; final float ox = (float)scale*o.getXf(); final float oy = (float)scale*o.getYf(); final float ux = (float)scale*u.getXf(); final float uy = (float)scale*u.getYf(); final float vx = (float)scale*v.getXf(); final float vy = (float)scale*v.getYf(); final float vCu = (vx*uy-vy*ux); final boolean doX = Math.abs( ux ) > Math.abs( uy ); tcBuf = prepareTextureCoordinateBuffer(mesh,0,2*3*triangles.size()); tcBuf.rewind(); for( DelaunayTriangle t : triangles ) { for( int i=0; i<3; i++ ) { x = t.points[i].getXf()-ox; y = t.points[i].getYf()-oy; // Calculate the texture coordinate in the UV plane a = (uy*x - ux*y)/vCu; if( doX ) { b = (x - a*vx)/ux; } else { b = (y - a*vy)/uy; } tcBuf.put( a ); tcBuf.put( b ); } } } // FloatBuffer vBuf,tcBuf; // float width,maxX,minX,maxY,minY,x,y,xn,yn; // // maxX = Float.NEGATIVE_INFINITY; // minX = Float.POSITIVE_INFINITY; // maxY = Float.NEGATIVE_INFINITY; // minY = Float.POSITIVE_INFINITY; // // vBuf = mesh.getMeshData().getVertexBuffer(); // for( int i=0; i < vBuf.limit()-1; i+=3 ) // { // x = vBuf.get(i); // y = vBuf.get(i+1); // // maxX = x > maxX ? x : maxX; // minX = x < minX ? x : minX; // maxY = y > maxY ? y : maxY; // minY = y < minY ? x : minY; // } // // width = maxX-minX > maxY-minY ? maxX-minX : maxY-minY; // width *= scale; // // vBuf = mesh.getMeshData().getVertexBuffer(); // tcBuf = prepareTextureCoordinateBuffer(mesh,0,2*vBuf.limit()/3); // tcBuf.rewind(); // // for( int i=0; i < vBuf.limit()-1; i+=3 ) // { // x = vBuf.get(i)-(maxX-minX)/2; // y = vBuf.get(i+1)-(maxY-minY)/2; // xn = (float)(x*Math.cos(angle)-y*Math.sin(angle)); // yn = (float)(y*Math.cos(angle)+x*Math.sin(angle)); // tcBuf.put( xn/width ); // tcBuf.put( yn/width ); // } public static void updateTriangleMesh( Mesh mesh, PointSet ps, CoordinateTransform pc ) { updateTriangleMesh( mesh, ps.getTriangles(), pc ); } /** * Will populate a given Mesh's vertex,index buffer and set IndexMode.Triangles<br> * Will also increase buffer sizes if needed by creating new buffers. * * @param mesh * @param ps */ public static void updateTriangleMesh( Mesh mesh, PointSet ps ) { updateTriangleMesh( mesh, ps.getTriangles() ); } public static void updateTriangleMesh( Mesh mesh, Polygon p ) { updateTriangleMesh( mesh, p.getTriangles() ); } public static void updateTriangleMesh( Mesh mesh, Polygon p, CoordinateTransform pc ) { updateTriangleMesh( mesh, p.getTriangles(), pc ); } public static void updateVertexBuffer( Mesh mesh, List<? extends Point> list ) { FloatBuffer vertBuf; int size = 3*list.size(); prepareVertexBuffer( mesh, size ); if( size == 0 ) { return; } vertBuf = mesh.getMeshData().getVertexBuffer(); vertBuf.rewind(); for( Point p : list ) { vertBuf.put(p.getXf()).put(p.getYf()).put(p.getZf()); } } public static void updateIndexBuffer( Mesh mesh, int[] index ) { IntBuffer indexBuf; if( index == null || index.length == 0 ) { return; } int size = index.length; prepareIndexBuffer( mesh, size ); indexBuf = mesh.getMeshData().getIndexBuffer(); indexBuf.rewind(); for( int i=0; i<size; i+=2 ) { indexBuf.put(index[i]).put( index[i+1] ); } } private static void prepareVertexBuffer( Mesh mesh, int size ) { FloatBuffer vertBuf; vertBuf = mesh.getMeshData().getVertexBuffer(); if( vertBuf == null || vertBuf.capacity() < size ) { vertBuf = BufferUtils.createFloatBuffer( size ); mesh.getMeshData().setVertexBuffer( vertBuf ); } else { vertBuf.limit( size ); mesh.getMeshData().updateVertexCount(); } } private static void prepareNormalBuffer( Mesh mesh, int size ) { FloatBuffer nBuf; nBuf = mesh.getMeshData().getNormalBuffer(); if( nBuf == null || nBuf.capacity() < size ) { nBuf = BufferUtils.createFloatBuffer( size ); mesh.getMeshData().setNormalBuffer( nBuf ); } else { nBuf.limit( size ); } } private static void prepareIndexBuffer( Mesh mesh, int size) { IntBuffer indexBuf = mesh.getMeshData().getIndexBuffer(); if( indexBuf == null || indexBuf.capacity() < size ) { indexBuf = BufferUtils.createIntBuffer( size ); mesh.getMeshData().setIndexBuffer( indexBuf ); } else { indexBuf.limit( size ); } } private static FloatBuffer prepareTextureCoordinateBuffer( Mesh mesh, int index, int size ) { FloatBuffer tcBuf; tcBuf = mesh.getMeshData().getTextureBuffer( index ); if( tcBuf == null || tcBuf.capacity() < size ) { tcBuf = BufferUtils.createFloatBuffer( size ); mesh.getMeshData().setTextureBuffer( tcBuf, index ); } else { tcBuf.limit( size ); } return tcBuf; } }
Java
package org.poly2tri.polygon.ardor3d; import java.util.ArrayList; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.triangulation.point.ardor3d.ArdorVector3Point; import org.poly2tri.triangulation.point.ardor3d.ArdorVector3PolygonPoint; import com.ardor3d.math.Vector3; public class ArdorPolygon extends Polygon { public ArdorPolygon( Vector3[] points ) { super( ArdorVector3PolygonPoint.toPoints( points ) ); } public ArdorPolygon( ArrayList<Vector3> points ) { super( ArdorVector3PolygonPoint.toPoints( points ) ); } }
Java
package org.poly2tri.examples.ardor3d; import java.util.ArrayList; import org.poly2tri.Poly2Tri; import org.poly2tri.examples.ardor3d.base.P2TSimpleExampleBase; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.geometry.polygon.PolygonPoint; import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper; import com.ardor3d.framework.FrameHandler; import com.ardor3d.input.logical.LogicalLayer; import com.ardor3d.math.ColorRGBA; import com.ardor3d.renderer.state.WireframeState; import com.ardor3d.scenegraph.Mesh; import com.ardor3d.scenegraph.Node; import com.google.inject.Inject; public class CDTHoleExample extends P2TSimpleExampleBase { public static void main(final String[] args) { start(CDTHoleExample.class); } @Inject public CDTHoleExample( LogicalLayer logicalLayer, FrameHandler frameHandler ) { super( logicalLayer, frameHandler ); } @Override protected void initExample() { super.initExample(); Node node = new Node(); node.setRenderState( new WireframeState() ); _node.attachChild( node ); Polygon circle; Polygon hole; circle = createCirclePolygon( 64, 25, 1 ); hole = createCirclePolygon( 32, 25, 0.25, -0.5, -0.5 ); circle.addHole( hole ); hole = createCirclePolygon( 64, 25, 0.5, 0.25, 0.25 ); circle.addHole( hole ); Mesh mesh = new Mesh(); mesh.setDefaultColor( ColorRGBA.RED ); mesh.setTranslation( 0, 0, 0.01 ); node.attachChild( mesh ); Mesh mesh2 = new Mesh(); mesh2.setDefaultColor( ColorRGBA.BLUE ); _node.attachChild( mesh2 ); Poly2Tri.triangulate( circle ); ArdorMeshMapper.updateTriangleMesh( mesh, circle ); ArdorMeshMapper.updateTriangleMesh( mesh2, circle ); } private Polygon createCirclePolygon( int n, double scale, double radius ) { return createCirclePolygon( n, scale, radius, 0, 0 ); } private Polygon createCirclePolygon( int n, double scale, double radius, double x, double y ) { if( n < 3 ) n=3; PolygonPoint[] points = new PolygonPoint[n]; for( int i=0; i<n; i++ ) { points[i] = new PolygonPoint( scale*(x + radius*Math.cos( (2.0*Math.PI*i)/n )), scale*(y + radius*Math.sin( (2.0*Math.PI*i)/n ) )); } return new Polygon( points ); } }
Java
package org.poly2tri.examples.ardor3d.base; import java.net.URISyntaxException; import org.lwjgl.opengl.Display; import com.ardor3d.example.ExampleBase; import com.ardor3d.framework.FrameHandler; import com.ardor3d.image.Texture; import com.ardor3d.image.Image.Format; import com.ardor3d.input.logical.LogicalLayer; import com.ardor3d.renderer.queue.RenderBucketType; import com.ardor3d.renderer.state.BlendState; import com.ardor3d.renderer.state.TextureState; import com.ardor3d.renderer.state.WireframeState; import com.ardor3d.scenegraph.Node; import com.ardor3d.scenegraph.hint.LightCombineMode; import com.ardor3d.scenegraph.shape.Quad; import com.ardor3d.util.TextureManager; import com.ardor3d.util.resource.ResourceLocatorTool; import com.ardor3d.util.resource.SimpleResourceLocator; import com.google.inject.Inject; public abstract class P2TSimpleExampleBase extends ExampleBase { protected Node _node; protected Quad _logotype; protected int _width,_height; @Inject public P2TSimpleExampleBase( LogicalLayer logicalLayer, FrameHandler frameHandler ) { super( logicalLayer, frameHandler ); } @Override protected void initExample() { _canvas.setVSyncEnabled( true ); _canvas.getCanvasRenderer().getCamera().setLocation(0, 0, 65); _width = Display.getDisplayMode().getWidth(); _height = Display.getDisplayMode().getHeight(); _root.getSceneHints().setLightCombineMode( LightCombineMode.Off ); _node = new Node(); _node.getSceneHints().setLightCombineMode( LightCombineMode.Off ); // _node.setRenderState( new WireframeState() ); _root.attachChild( _node ); try { SimpleResourceLocator srl = new SimpleResourceLocator(ExampleBase.class.getClassLoader().getResource("org/poly2tri/examples/data/")); ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_MODEL, srl); SimpleResourceLocator sr2 = new SimpleResourceLocator(ExampleBase.class.getClassLoader().getResource("org/poly2tri/examples/textures/")); ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, sr2); } catch (final URISyntaxException ex) { ex.printStackTrace(); } _logotype = new Quad("box", 128, 128 ); _logotype.setTranslation( 74, _height - 74, 0 ); _logotype.getSceneHints().setRenderBucketType( RenderBucketType.Ortho ); BlendState bs = new BlendState(); bs.setBlendEnabled( true ); bs.setEnabled( true ); bs.setSourceFunction(BlendState.SourceFunction.SourceAlpha); bs.setDestinationFunction(BlendState.DestinationFunction.OneMinusSourceAlpha); _logotype.setRenderState( bs ); TextureState ts = new TextureState(); ts.setEnabled(true); ts.setTexture(TextureManager.load("poly2tri_logotype_256x256.png", Texture.MinificationFilter.Trilinear, Format.GuessNoCompression, true)); _logotype.setRenderState(ts); _root.attachChild( _logotype ); } }
Java
package org.poly2tri.examples.ardor3d.base; import java.nio.FloatBuffer; import java.util.List; import org.poly2tri.geometry.polygon.PolygonSet; import org.poly2tri.triangulation.TriangulationAlgorithm; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.TriangulationProcess; import org.poly2tri.triangulation.delaunay.DelaunayTriangle; import org.poly2tri.triangulation.delaunay.sweep.DTSweepContext; import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper; import com.ardor3d.framework.Canvas; import com.ardor3d.framework.FrameHandler; import com.ardor3d.input.Key; import com.ardor3d.input.logical.InputTrigger; import com.ardor3d.input.logical.KeyPressedCondition; import com.ardor3d.input.logical.LogicalLayer; import com.ardor3d.input.logical.TriggerAction; import com.ardor3d.input.logical.TwoInputStates; import com.ardor3d.math.ColorRGBA; import com.ardor3d.math.Vector3; import com.ardor3d.renderer.IndexMode; import com.ardor3d.renderer.queue.RenderBucketType; import com.ardor3d.renderer.state.WireframeState; import com.ardor3d.scenegraph.Mesh; import com.ardor3d.scenegraph.MeshData; import com.ardor3d.scenegraph.Node; import com.ardor3d.scenegraph.Point; import com.ardor3d.scenegraph.hint.LightCombineMode; import com.ardor3d.ui.text.BasicText; import com.ardor3d.util.ReadOnlyTimer; import com.ardor3d.util.geom.BufferUtils; public abstract class P2TExampleBase extends P2TSimpleExampleBase { protected TriangulationProcess _process; protected CDTSweepMesh _cdtSweepMesh; protected CDTSweepPoints _cdtSweepPoints; protected PolygonSet _polygonSet; private long _processTimestamp; /** Text fields used to present info about the example. */ protected final BasicText _exampleInfo[] = new BasicText[7]; public P2TExampleBase( LogicalLayer logicalLayer, FrameHandler frameHandler ) { super( logicalLayer, frameHandler ); } @Override protected void initExample() { super.initExample(); // Warmup the triangulation code for better performance // when we need triangulation during runtime // Poly2Tri.warmup(); _process = new TriangulationProcess(TriangulationAlgorithm.DTSweep); _cdtSweepPoints = new CDTSweepPoints(); _cdtSweepMesh = new CDTSweepMesh(); _node.attachChild( _cdtSweepPoints.getSceneNode() ); _node.attachChild( _cdtSweepMesh.getSceneNode() ); final Node textNodes = new Node("Text"); textNodes.getSceneHints().setRenderBucketType(RenderBucketType.Ortho); textNodes.getSceneHints().setLightCombineMode(LightCombineMode.Off); _root.attachChild( textNodes ); for (int i = 0; i < _exampleInfo.length; i++) { _exampleInfo[i] = BasicText.createDefaultTextLabel("Text", "", 16); _exampleInfo[i].setTranslation(new Vector3(10, (_exampleInfo.length-i-1) * 20 + 10, 0)); textNodes.attachChild(_exampleInfo[i]); } updateText(); } protected DTSweepContext getContext() { return (DTSweepContext)_process.getContext(); } /** * Update text information. */ protected void updateText() { _exampleInfo[0].setText(""); _exampleInfo[1].setText("[Home] Toggle wireframe"); _exampleInfo[2].setText("[End] Toggle vertex points"); } @Override protected void updateExample(final ReadOnlyTimer timer) { if( _process.isDone() && _processTimestamp != _process.getTimestamp() ) { _processTimestamp = _process.getTimestamp(); updateMesh(); _exampleInfo[0].setText("[" + _process.getTriangulationTime() + "ms] " + _process.getPointCount() + " points" ); } } public void exit() { super.exit(); _process.shutdown(); } protected void triangulate() { _process.triangulate( _polygonSet ); } protected void updateMesh() { if( _process.getContext().getTriangulatable() != null ) { if( _process.getContext().isDebugEnabled() ) { if( _process.isDone() ) { _cdtSweepMesh.update( _process.getContext().getTriangulatable().getTriangles() ); _cdtSweepPoints.update( _process.getContext().getTriangulatable().getPoints() ); } else { _cdtSweepMesh.update( _process.getContext().getTriangles() ); _cdtSweepPoints.update( _process.getContext().getPoints() ); } } else { _cdtSweepMesh.update( _polygonSet.getPolygons().get(0).getTriangles() ); _cdtSweepPoints.update( _polygonSet.getPolygons().get(0).getPoints() ); } } } @Override public void registerInputTriggers() { super.registerInputTriggers(); _controlHandle.setMoveSpeed( 10 ); // HOME - toogleWireframe _logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.HOME ), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { _cdtSweepMesh.toogleWireframe(); } } ) ); // END - tooglePoints _logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.END ), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { _cdtSweepPoints.toogleVisibile(); } } ) ); } protected abstract class SceneElement<A> { protected Node _node; public SceneElement(String name) { _node = new Node(name); _node.getSceneHints().setAllPickingHints( false ); } public abstract void update( A element ); public Node getSceneNode() { return _node; } } protected class CDTSweepPoints extends SceneElement<List<TriangulationPoint>> { private Point m_point = new Point(); private boolean _pointsVisible = true; public CDTSweepPoints() { super("Mesh"); m_point.setDefaultColor( ColorRGBA.RED ); m_point.setPointSize( 1 ); m_point.setTranslation( 0, 0, 0.01 ); _node.attachChild( m_point ); MeshData md = m_point.getMeshData(); int size = 1000; FloatBuffer vertBuf = BufferUtils.createFloatBuffer( (int)size*3 ); md.setVertexBuffer( vertBuf ); } public void toogleVisibile() { if( _pointsVisible ) { m_point.removeFromParent(); _pointsVisible = false; } else { _node.attachChild( m_point ); _pointsVisible = true; } } @Override public void update( List<TriangulationPoint> list ) { ArdorMeshMapper.updateVertexBuffer( m_point, list ); } } protected class CDTSweepMesh extends SceneElement<List<DelaunayTriangle>> { private Mesh m_mesh = new Mesh(); private WireframeState _ws = new WireframeState(); public CDTSweepMesh() { super("Mesh"); MeshData md; m_mesh.setDefaultColor( ColorRGBA.BLUE ); m_mesh.setRenderState( _ws ); _node.attachChild( m_mesh ); md = m_mesh.getMeshData(); int size = 1000; FloatBuffer vertBuf = BufferUtils.createFloatBuffer( (int)size*3*3 ); md.setVertexBuffer( vertBuf ); md.setIndexMode( IndexMode.Triangles ); } public void toogleWireframe() { if( _ws.isEnabled() ) { _ws.setEnabled( false ); } else { _ws.setEnabled( true ); } } @Override public void update( List<DelaunayTriangle> triangles ) { ArdorMeshMapper.updateTriangleMesh( m_mesh, triangles ); } } }
Java
package org.poly2tri.examples.ardor3d.misc; public enum ExampleModels { Test ("test.dat",1,0,0,true), Two ("2.dat",1,0,0,true), Debug ("debug.dat",1,0,0,false), Debug2 ("debug2.dat",1,0,0,false), Bird ("bird.dat",1,0,0,false), Custom ("funny.dat",1,0,0,false), Diamond ("diamond.dat",1,0,0,false), Dude ("dude.dat",1,-0.1,0,true), Nazca_heron ("nazca_heron.dat",1.3,0,0.35,false), Nazca_monkey ("nazca_monkey.dat",1,0,0,false), Star ("star.dat",1,0,0,false), Strange ("strange.dat",1,0,0,true), Tank ("tank.dat",1.3,0,0,true); private final static String m_basePath = "org/poly2tri/examples/data/"; private String m_filename; private double m_scale; private double m_x; private double m_y; private boolean _invertedYAxis; ExampleModels( String filename, double scale, double x, double y, boolean invertedY ) { m_filename = filename; m_scale = scale; m_x = x; m_y = y; _invertedYAxis = invertedY; } public String getFilename() { return m_basePath + m_filename; } public double getScale() { return m_scale; } public double getX() { return m_x; } public double getY() { return m_y; } public boolean invertedYAxis() { return _invertedYAxis; } }
Java
/** * Copyright (c) 2008-2009 Ardor Labs, Inc. * * This file is part of Ardor3D. * * Ardor3D is free software: you can redistribute it and/or modify it * under the terms of its license which may be found in the accompanying * LICENSE file or at <http://www.ardor3d.com/LICENSE>. */ package org.poly2tri.examples.ardor3d.misc; import java.nio.FloatBuffer; import com.ardor3d.math.Vector3; import com.ardor3d.math.type.ReadOnlyVector3; import com.ardor3d.scenegraph.Mesh; import com.ardor3d.util.geom.BufferUtils; public class Triangle extends Mesh { private static final long serialVersionUID = 1L; public Triangle() { this( "Triangle" ); } public Triangle(final String name ) { this( name, new Vector3( Math.cos( Math.toRadians( 90 ) ), Math.sin( Math.toRadians( 90 ) ), 0 ), new Vector3( Math.cos( Math.toRadians( 210 ) ), Math.sin( Math.toRadians( 210 ) ), 0 ), new Vector3( Math.cos( Math.toRadians( 330 ) ), Math.sin( Math.toRadians( 330 ) ), 0 )); } public Triangle(final String name, ReadOnlyVector3 a, ReadOnlyVector3 b, ReadOnlyVector3 c ) { super(name); initialize(a,b,c); } /** * <code>resize</code> changes the width and height of the given quad by altering its vertices. * * @param width * the new width of the <code>Quad</code>. * @param height * the new height of the <code>Quad</code>. */ // public void resize( double radius ) // { // _meshData.getVertexBuffer().clear(); // _meshData.getVertexBuffer().put((float) (-width / 2)).put((float) (height / 2)).put(0); // _meshData.getVertexBuffer().put((float) (-width / 2)).put((float) (-height / 2)).put(0); // _meshData.getVertexBuffer().put((float) (width / 2)).put((float) (-height / 2)).put(0); // _meshData.getVertexBuffer().put((float) (width / 2)).put((float) (height / 2)).put(0); // } /** * <code>initialize</code> builds the data for the <code>Quad</code> object. * * @param width * the width of the <code>Quad</code>. * @param height * the height of the <code>Quad</code>. */ private void initialize(ReadOnlyVector3 a, ReadOnlyVector3 b, ReadOnlyVector3 c ) { final int verts = 3; _meshData.setVertexBuffer(BufferUtils.createVector3Buffer(3)); _meshData.setNormalBuffer(BufferUtils.createVector3Buffer(3)); final FloatBuffer tbuf = BufferUtils.createVector2Buffer(3); _meshData.setTextureBuffer(tbuf, 0); _meshData.setIndexBuffer(BufferUtils.createIntBuffer(3)); Vector3 ba = Vector3.fetchTempInstance(); Vector3 ca = Vector3.fetchTempInstance(); ba.set( b ).subtractLocal( a ); ca.set( c ).subtractLocal( a ); ba.crossLocal( ca ).normalizeLocal(); _meshData.getNormalBuffer().put(ba.getXf()).put(ba.getYf()).put(ba.getZf()); _meshData.getNormalBuffer().put(ba.getXf()).put(ba.getYf()).put(ba.getZf()); _meshData.getNormalBuffer().put(ba.getXf()).put(ba.getYf()).put(ba.getZf()); Vector3.releaseTempInstance( ba ); Vector3.releaseTempInstance( ca ); tbuf.put(0).put(1); tbuf.put(0).put(0); tbuf.put(1).put(0); _meshData.getIndexBuffer().put(0); _meshData.getIndexBuffer().put(1); _meshData.getIndexBuffer().put(2); _meshData.getVertexBuffer().put(a.getXf()).put(a.getYf()).put(a.getZf()); _meshData.getVertexBuffer().put(b.getXf()).put(b.getYf()).put(b.getZf()); _meshData.getVertexBuffer().put(c.getXf()).put(c.getYf()).put(c.getZf()); } }
Java
package org.poly2tri.examples.ardor3d.misc; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.polygon.ardor3d.ArdorPolygon; import org.poly2tri.triangulation.TriangulationPoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ardor3d.math.Vector3; public class PolygonLoader { private final static Logger logger = LoggerFactory.getLogger( PolygonLoader.class ); public static Polygon loadModel( ExampleModels model, double scale ) throws FileNotFoundException, IOException { String line; ArrayList<Vector3> points = new ArrayList<Vector3>(); InputStream istream = PolygonLoader.class.getClassLoader().getResourceAsStream( model.getFilename() ); if( istream == null ) { throw new FileNotFoundException( "Couldn't find " + model ); } InputStreamReader ir = new InputStreamReader( istream ); BufferedReader reader = new BufferedReader( ir ); while( ( line = reader.readLine() ) != null ) { StringTokenizer tokens = new StringTokenizer( line, " ," ); points.add( new Vector3( Float.valueOf( tokens.nextToken() ).floatValue(), Float.valueOf( tokens.nextToken() ).floatValue(), 0f )); } if( points.isEmpty() ) { throw new IOException( "no data in file " + model ); } // Rescale models so they are centered at 0,0 and don't fall outside the // unit square double maxX, maxY, minX, minY; maxX = minX = points.get( 0 ).getX(); if( model.invertedYAxis() ) { maxY = minY = -points.get( 0 ).getY(); } else { maxY = minY = points.get( 0 ).getY(); } for( Vector3 p : points ) { if( model.invertedYAxis() ) { p.setY( -p.getY() ); } maxX = p.getX() > maxX ? p.getX() : maxX; maxY = p.getY() > maxY ? p.getY() : maxY; minX = p.getX() < minX ? p.getX() : minX; minY = p.getY() < minY ? p.getY() : minY; } double width, height, xScale, yScale; width = maxX - minX; height = maxY - minY; xScale = scale * 1f / width; yScale = scale * 1f / height; // System.out.println("scale/height=" + SCALE + "/" + height ); // System.out.println("scale=" + yScale); for( Vector3 p : points ) { if( model.invertedYAxis() ) { p.subtractLocal( maxX - width / 2, maxY - height / 2, 0 ); } else { p.subtractLocal( maxX - width / 2, maxY - height / 2, 0 ); } p.multiplyLocal( xScale < yScale ? xScale : yScale ); } return new ArdorPolygon( points); } public static void saveModel( String path, TriangulationPoint[] points ) { FileWriter writer = null; BufferedWriter w = null; String file = path+System.currentTimeMillis()+".dat"; try { writer = new FileWriter(file); w = new BufferedWriter(writer); for( TriangulationPoint p : points ) { w.write( Float.toString( p.getXf() ) +" "+ Float.toString( p.getYf() )); w.newLine(); } logger.info( "Saved polygon\n" + file ); } catch( IOException e ) { logger.error( "Failed to save model" ); } finally { if( w != null ) { try { w.close(); } catch( IOException e2 ) { } } } } /** * This is a very unoptimal dump of the triangles as absolute lines. * For manual importation to an SVG<br> * * @param path * @param ps */ // public static void saveTriLine( String path, PolygonSet ps ) // { // FileWriter writer = null; // BufferedWriter w = null; // String file = path+System.currentTimeMillis()+".tri"; // // if( ps.getTriangles() == null || ps.getTriangles().isEmpty() ) // { // return; // } // // try // { // // writer = new FileWriter(file); // w = new BufferedWriter(writer); // for( DelaunayTriangle t : ps.getTriangles() ) // { // for( int i=0; i<3; i++ ) // { // w.write( Float.toString( t.points[i].getXf() ) +","+ Float.toString( t.points[i].getYf() )+" "); // } //// w.newLine(); // } // logger.info( "Saved triangle lines\n" + file ); // } // catch( IOException e ) // { // logger.error( "Failed to save triangle lines" + e.getMessage() ); // } // finally // { // if( w != null ) // { // try // { // w.close(); // } // catch( IOException e2 ) // { // } // } // } // } }
Java
package org.poly2tri.examples.ardor3d.misc; public enum ExampleSets { Example1 ("example1.dat",1,0,0,true), Example2 ("example2.dat",1,0,0,true), Example3 ("example3.dat",1,0,0,false), Example4 ("example4.dat",1,0,0,false); private final static String m_basePath = "org/poly2tri/examples/data/pointsets/"; private String m_filename; private double m_scale; private double m_x; private double m_y; private boolean _invertedYAxis; ExampleSets( String filename, double scale, double x, double y, boolean invertedY ) { m_filename = filename; m_scale = scale; m_x = x; m_y = y; _invertedYAxis = invertedY; } public String getFilename() { return m_basePath + m_filename; } public double getScale() { return m_scale; } public double getX() { return m_x; } public double getY() { return m_y; } public boolean invertedYAxis() { return _invertedYAxis; } }
Java
package org.poly2tri.examples.ardor3d.misc; import org.poly2tri.triangulation.point.TPoint; public class MyPoint extends TPoint { int index; public MyPoint( double x, double y ) { super( x, y ); } public void setIndex(int i) { index = i; } public int getIndex() { return index; } public boolean equals(Object other) { if (!(other instanceof MyPoint)) return false; MyPoint p = (MyPoint)other; return getX() == p.getX() && getY() == p.getY(); } public int hashCode() { return (int)getX() + (int)getY(); } }
Java
package org.poly2tri.examples.ardor3d.misc; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.geometry.polygon.PolygonSet; import org.poly2tri.polygon.ardor3d.ArdorPolygon; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.delaunay.DelaunayTriangle; import org.poly2tri.triangulation.point.TPoint; import org.poly2tri.triangulation.sets.PointSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ardor3d.math.Vector3; public class DataLoader { private final static Logger logger = LoggerFactory.getLogger( DataLoader.class ); public static Polygon loadModel( ExampleModels model, double scale ) throws FileNotFoundException, IOException { String line; ArrayList<Vector3> points = new ArrayList<Vector3>(); InputStream istream = DataLoader.class.getClassLoader().getResourceAsStream( model.getFilename() ); if( istream == null ) { throw new FileNotFoundException( "Couldn't find " + model ); } InputStreamReader ir = new InputStreamReader( istream ); BufferedReader reader = new BufferedReader( ir ); while( ( line = reader.readLine() ) != null ) { StringTokenizer tokens = new StringTokenizer( line, " ," ); points.add( new Vector3( Double.valueOf( tokens.nextToken() ).doubleValue(), Double.valueOf( tokens.nextToken() ).doubleValue(), 0f )); } if( points.isEmpty() ) { throw new IOException( "no data in file " + model ); } // Rescale models so they are centered at 0,0 and don't fall outside the // unit square double maxX, maxY, minX, minY; maxX = minX = points.get( 0 ).getX(); if( model.invertedYAxis() ) { maxY = minY = -points.get( 0 ).getY(); } else { maxY = minY = points.get( 0 ).getY(); } for( Vector3 p : points ) { if( model.invertedYAxis() ) { p.setY( -p.getY() ); } maxX = p.getX() > maxX ? p.getX() : maxX; maxY = p.getY() > maxY ? p.getY() : maxY; minX = p.getX() < minX ? p.getX() : minX; minY = p.getY() < minY ? p.getY() : minY; } double width, height, xScale, yScale; width = maxX - minX; height = maxY - minY; xScale = scale * 1f / width; yScale = scale * 1f / height; // System.out.println("scale/height=" + SCALE + "/" + height ); // System.out.println("scale=" + yScale); for( Vector3 p : points ) { if( model.invertedYAxis() ) { p.subtractLocal( maxX - width / 2, maxY - height / 2, 0 ); } else { p.subtractLocal( maxX - width / 2, maxY - height / 2, 0 ); } p.multiplyLocal( xScale < yScale ? xScale : yScale ); } return new ArdorPolygon( points); } public static PointSet loadPointSet( ExampleSets set, double scale ) throws FileNotFoundException, IOException { String line; ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(); InputStream istream = DataLoader.class.getClassLoader().getResourceAsStream( set.getFilename() ); if( istream == null ) { throw new FileNotFoundException( "Couldn't find " + set ); } InputStreamReader ir = new InputStreamReader( istream ); BufferedReader reader = new BufferedReader( ir ); while( ( line = reader.readLine() ) != null ) { StringTokenizer tokens = new StringTokenizer( line, " ," ); points.add( new TPoint( scale*Float.valueOf( tokens.nextToken() ).floatValue(), scale*Float.valueOf( tokens.nextToken() ).floatValue() )); } if( points.isEmpty() ) { throw new IOException( "no data in file " + set ); } // Rescale models so they are centered at 0,0 and don't fall outside the // unit square // double maxX, maxY, minX, minY; // maxX = minX = points.get( 0 ).getX(); // if( set.invertedYAxis() ) // { // maxY = minY = -points.get( 0 ).getY(); // } // else // { // maxY = minY = points.get( 0 ).getY(); // } // for( TPoint p : points ) // { // if( set.invertedYAxis() ) // { // p.setY( -p.getY() ); // } // maxX = p.getX() > maxX ? p.getX() : maxX; // maxY = p.getY() > maxY ? p.getY() : maxY; // minX = p.getX() < minX ? p.getX() : minX; // minY = p.getY() < minY ? p.getY() : minY; // } // // double width, height, xScale, yScale; // width = maxX - minX; // height = maxY - minY; // xScale = scale * 1f / width; // yScale = scale * 1f / height; // // // System.out.println("scale/height=" + SCALE + "/" + height ); // // System.out.println("scale=" + yScale); // // for( TPoint p : points ) // { // if( set.invertedYAxis() ) // { // p.subtractLocal( maxX - width / 2, maxY - height / 2, 0 ); // } // else // { // p.subtractLocal( maxX - width / 2, maxY - height / 2, 0 ); // } // p.multiplyLocal( xScale < yScale ? xScale : yScale ); // } return new PointSet( points ); } public static void saveModel( String path, TriangulationPoint[] points ) { FileWriter writer = null; BufferedWriter w = null; String file = path+System.currentTimeMillis()+".dat"; try { writer = new FileWriter(file); w = new BufferedWriter(writer); for( TriangulationPoint p : points ) { w.write( Float.toString( p.getXf() ) +" "+ Float.toString( p.getYf() )); w.newLine(); } logger.info( "Saved polygon\n" + file ); } catch( IOException e ) { logger.error( "Failed to save model" ); } finally { if( w != null ) { try { w.close(); } catch( IOException e2 ) { } } } } /** * This is a very unoptimal dump of the triangles as absolute lines. * For manual importation to an SVG<br> * * @param path * @param ps */ public static void saveTriLine( String path, PolygonSet ps ) { FileWriter writer = null; BufferedWriter w = null; String file = path+System.currentTimeMillis()+".tri"; if( ps.getPolygons() == null || ps.getPolygons().isEmpty() ) { return; } try { writer = new FileWriter(file); w = new BufferedWriter(writer); for( DelaunayTriangle t : ps.getPolygons().get(0).getTriangles() ) { for( int i=0; i<3; i++ ) { w.write( Float.toString( t.points[i].getXf() ) +","+ Float.toString( t.points[i].getYf() )+" "); } // w.newLine(); } logger.info( "Saved triangle lines\n" + file ); } catch( IOException e ) { logger.error( "Failed to save triangle lines" + e.getMessage() ); } finally { if( w != null ) { try { w.close(); } catch( IOException e2 ) { } } } } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.examples.ardor3d; import java.io.IOException; import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.List; import org.poly2tri.examples.ardor3d.base.P2TExampleBase; import org.poly2tri.examples.ardor3d.misc.DataLoader; import org.poly2tri.examples.ardor3d.misc.ExampleModels; import org.poly2tri.examples.ardor3d.misc.Triangle; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.geometry.polygon.PolygonSet; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.delaunay.DelaunayTriangle; import org.poly2tri.triangulation.delaunay.sweep.AdvancingFront; import org.poly2tri.triangulation.delaunay.sweep.AdvancingFrontNode; import org.poly2tri.triangulation.delaunay.sweep.DTSweepConstraint; import org.poly2tri.triangulation.delaunay.sweep.DTSweepContext; import org.poly2tri.triangulation.point.TPoint; import org.poly2tri.triangulation.sets.ConstrainedPointSet; import org.poly2tri.triangulation.sets.PointSet; import org.poly2tri.triangulation.util.PolygonGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ardor3d.framework.Canvas; import com.ardor3d.framework.FrameHandler; import com.ardor3d.input.Key; import com.ardor3d.input.logical.InputTrigger; import com.ardor3d.input.logical.KeyPressedCondition; import com.ardor3d.input.logical.LogicalLayer; import com.ardor3d.input.logical.TriggerAction; import com.ardor3d.input.logical.TwoInputStates; import com.ardor3d.math.ColorRGBA; import com.ardor3d.renderer.IndexMode; import com.ardor3d.renderer.state.WireframeState; import com.ardor3d.scenegraph.Line; import com.ardor3d.scenegraph.Point; import com.ardor3d.util.ReadOnlyTimer; import com.ardor3d.util.geom.BufferUtils; import com.google.inject.Inject; /** * Toggle Model with PageUp and PageDown<br> * Toggle Wireframe with Home<br> * Toggle Vertex points with End<br> * Use 1 and 2 to generate random polygons<br> * * @author Thomas * */ public class CDTModelExample extends P2TExampleBase { private final static Logger logger = LoggerFactory.getLogger( CDTModelExample.class ); private ExampleModels m_currentModel = ExampleModels.Two; private static double SCALE = 50; private Line m_line; // Build parameters private int m_vertexCount = 10000; // Scene components private CDTSweepAdvancingFront _cdtSweepAdvancingFront; private CDTSweepActiveNode _cdtSweepActiveNode; private CDTSweepActiveTriangles _cdtSweepActiveTriangle; private CDTSweepActiveEdge _cdtSweepActiveEdge; // private GUICircumCircle m_circumCircle; private int m_stepCount = 0; private boolean m_autoStep = true; private final String m_dataPath = "src/main/resources/org/poly2tri/examples/data/"; public static void main(final String[] args) { start(CDTModelExample.class); } @Inject public CDTModelExample( LogicalLayer logicalLayer, FrameHandler frameHandler ) { super( logicalLayer, frameHandler ); } protected void updateExample(final ReadOnlyTimer timer) { super.updateExample( timer ); if( getContext().isDebugEnabled() ) { int count = _process.getStepCount(); if( m_stepCount < count ) { _process.requestRead(); if( _process.isReadable() ) { updateMesh(); m_stepCount = count; if( m_autoStep ) { _process.resume(); } } } } } @Override protected void initExample() { super.initExample(); // getContext().isDebugEnabled( true ); if( getContext().isDebugEnabled() ) { _cdtSweepAdvancingFront = new CDTSweepAdvancingFront(); _node.attachChild( _cdtSweepAdvancingFront.getSceneNode() ); _cdtSweepActiveNode = new CDTSweepActiveNode(); _node.attachChild( _cdtSweepActiveNode.getSceneNode() ); _cdtSweepActiveTriangle = new CDTSweepActiveTriangles(); _node.attachChild( _cdtSweepActiveTriangle.getSceneNode() ); _cdtSweepActiveEdge = new CDTSweepActiveEdge(); _node.attachChild( _cdtSweepActiveEdge.getSceneNode() ); // m_circumCircle = new GUICircumCircle(); // m_node.attachChild( m_circumCircle.getSceneNode() ); } buildModel(m_currentModel); triangulate(); } /** * Update text information. */ protected void updateText() { super.updateText(); _exampleInfo[3].setText("[PageUp] Next model"); _exampleInfo[4].setText("[PageDown] Previous model"); _exampleInfo[5].setText("[1] Generate polygon type A "); _exampleInfo[6].setText("[2] Generate polygon type B "); } private void buildModel( ExampleModels model ) { Polygon poly; if( model != null ) { try { poly = DataLoader.loadModel( model, SCALE ); _polygonSet = new PolygonSet( poly ); } catch( IOException e ) { logger.info( "Failed to load model {}", e.getMessage() ); model = null; } } if( model == null ) { _polygonSet = new PolygonSet( PolygonGenerator.RandomCircleSweep( SCALE, m_vertexCount ) ); } } private ConstrainedPointSet buildCustom() { ArrayList<TriangulationPoint> list = new ArrayList<TriangulationPoint>(20); int[] index; list.add( new TPoint(2.2715518,-4.5233157) ); list.add( new TPoint(3.4446202,-3.5232647) ); list.add( new TPoint(4.7215156,-4.5233157) ); list.add( new TPoint(6.0311967,-3.5232647) ); list.add( new TPoint(3.4446202,-7.2578132) ); list.add( new TPoint(.81390847,-3.5232647) ); index = new int[]{3,5}; return new ConstrainedPointSet( list, index ); } protected void triangulate() { super.triangulate(); m_stepCount = 0; } protected void updateMesh() { super.updateMesh(); DTSweepContext tcx = getContext(); if( tcx.isDebugEnabled() ) { _cdtSweepActiveTriangle.update( tcx ); _cdtSweepActiveEdge.update( tcx ); _cdtSweepActiveNode.update( tcx ); _cdtSweepAdvancingFront.update( tcx ); // m_circumCircle.update( tcx.getCircumCircle() ); } } @Override public void registerInputTriggers() { super.registerInputTriggers(); // SPACE - toggle models _logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.PAGEUP_PRIOR ), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { int index; index = (m_currentModel.ordinal()+1)%ExampleModels.values().length; m_currentModel = ExampleModels.values()[index]; buildModel(m_currentModel); _node.setScale( m_currentModel.getScale() ); triangulate(); } } ) ); // SPACE - toggle models backwards _logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.PAGEDOWN_NEXT ), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { int index; index = ((m_currentModel.ordinal()-1)%ExampleModels.values().length + ExampleModels.values().length)%ExampleModels.values().length; m_currentModel = ExampleModels.values()[index]; buildModel(m_currentModel); _node.setScale( m_currentModel.getScale() ); triangulate(); } } ) ); _logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.ONE ), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { _polygonSet = new PolygonSet( PolygonGenerator.RandomCircleSweep( SCALE, m_vertexCount ) ); triangulate(); } } ) ); _logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.TWO ), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { _polygonSet = new PolygonSet( PolygonGenerator.RandomCircleSweep2( SCALE, 200 ) ); triangulate(); } } ) ); // X -start _logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.X ), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { // Lets create a TriangulationProcess that allows you to step thru the TriangulationAlgorithm // _process.getContext().isDebugEnabled( true ); // _process.triangulate(); // m_stepCount = 0; } } ) ); // C - step _logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.C ), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { // updateMesh(); _process.resume(); } } ) ); // Z - toggle autostep _logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.Z ), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { m_autoStep = m_autoStep ? false : true; } } ) ); // space - save triangle lines _logicalLayer.registerTrigger( new InputTrigger( new KeyPressedCondition( Key.SPACE ), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { // PolygonLoader.saveTriLine( m_dataPath, _polygonSet ); m_stepCount = 0; _process.triangulate( buildCustom() ); } } ) ); } class CDTSweepAdvancingFront extends SceneElement<DTSweepContext> { protected Line m_nodeLines; protected Point m_frontPoints; protected Line m_frontLine; public CDTSweepAdvancingFront() { super("AdvancingFront"); m_frontLine = new Line(); m_frontLine.getMeshData().setIndexMode( IndexMode.LineStrip ); m_frontLine.getMeshData().setVertexBuffer( BufferUtils.createVector3Buffer( 800 ) ); m_frontLine.setDefaultColor( ColorRGBA.ORANGE ); m_frontLine.setTranslation( 0, 0.05, 0 ); _node.attachChild( m_frontLine ); m_frontPoints = new Point(); m_frontPoints.getMeshData().setVertexBuffer( m_frontLine.getMeshData().getVertexBuffer() ); m_frontPoints.setPointSize( 6 ); m_frontPoints.setDefaultColor( ColorRGBA.ORANGE ); m_frontPoints.setTranslation( 0, 0.05, 0 ); _node.attachChild( m_frontPoints ); m_nodeLines = new Line(); m_nodeLines.getMeshData().setIndexMode( IndexMode.Lines ); m_nodeLines.getMeshData().setVertexBuffer( BufferUtils.createVector3Buffer( 2*800 ) ); m_nodeLines.setDefaultColor( ColorRGBA.YELLOW ); m_nodeLines.setTranslation( 0, 0.05, 0 ); _node.attachChild( m_nodeLines ); } @Override public void update( DTSweepContext tcx ) { AdvancingFront front = ((DTSweepContext)tcx).getAdvancingFront(); AdvancingFrontNode node; DelaunayTriangle tri; if( front == null ) return; FloatBuffer fb = m_frontLine.getMeshData().getVertexBuffer(); FloatBuffer nodeVert = m_nodeLines.getMeshData().getVertexBuffer(); fb.limit( fb.capacity() ); nodeVert.limit( fb.capacity() ); fb.rewind(); nodeVert.rewind(); int count=0; node = front.head; TriangulationPoint point; do { point = node.getPoint(); fb.put( point.getXf() ).put( point.getYf() ).put( point.getZf() ); tri = node.getTriangle(); if( tri != null ) { nodeVert.put( point.getXf() ).put( point.getYf() ).put( point.getZf() ); nodeVert.put( ( tri.points[0].getXf() + tri.points[1].getXf() + tri.points[2].getXf() )/3 ); nodeVert.put( ( tri.points[0].getYf() + tri.points[1].getYf() + tri.points[2].getYf() )/3 ); nodeVert.put( ( tri.points[0].getZf() + tri.points[1].getZf() + tri.points[2].getZf() )/3 ); } count++; } while( (node = node.getNext()) != null ); fb.limit( 3*count ); nodeVert.limit( 2*count*3 ); } } // class GUICircumCircle extends SceneElement<Tuple2<TriangulationPoint,Double>> // { // private int VCNT = 64; // private Line m_circle = new Line(); // // public GUICircumCircle() // { // super("CircumCircle"); // m_circle.getMeshData().setIndexMode( IndexMode.LineLoop ); // m_circle.getMeshData().setVertexBuffer( BufferUtils.createVector3Buffer( VCNT ) ); // m_circle.setDefaultColor( ColorRGBA.WHITE ); // m_circle.setLineWidth( 1 ); // m_node.attachChild( m_circle ); // } // // @Override // public void update( Tuple2<TriangulationPoint,Double> circle ) // { // float x,y; // if( circle.a != null ) // { // FloatBuffer fb = m_circle.getMeshData().getVertexBuffer(); // fb.rewind(); // for( int i=0; i < VCNT; i++ ) // { // x = (float)circle.a.getX() + (float)(circle.b*Math.cos( 2*Math.PI*((double)i%VCNT)/VCNT )); // y = (float)circle.a.getY() + (float)(circle.b*Math.sin( 2*Math.PI*((double)i%VCNT)/VCNT )); // fb.put( x ).put( y ).put( 0 ); // } // } // else // { // m_node.detachAllChildren(); // } // } // } class CDTSweepMeshExtended extends CDTSweepMesh { // private Line m_conLine = new Line(); public CDTSweepMeshExtended() { super(); // Line that show the connection between triangles // m_conLine.setDefaultColor( ColorRGBA.RED ); // m_conLine.getMeshData().setIndexMode( IndexMode.Lines ); // m_node.attachChild( m_conLine ); // // vertBuf = BufferUtils.createFloatBuffer( size*3*3*3 ); // m_conLine.getMeshData().setVertexBuffer( vertBuf ); } @Override public void update( List<DelaunayTriangle> triangles ) { super.update( triangles ); // MeshData md; // Vector3 v1 = Vector3.fetchTempInstance(); // Vector3 v2 = Vector3.fetchTempInstance(); // FloatBuffer v2Buf; // // // md = m_mesh.getMeshData(); // v2Buf = m_conLine.getMeshData().getVertexBuffer(); // //// logger.info( "Triangle count [{}]", tcx.getMap().size() ); // // int size = 2*3*3*ps.getTriangles().size(); // if( v2Buf.capacity() < size ) // { // v2Buf = BufferUtils.createFloatBuffer( size ); // m_conLine.getMeshData().setVertexBuffer( v2Buf ); // } // else // { // v2Buf.limit( 2*size ); // } // // v2Buf.rewind(); // int lineCount=0; // ArdorVector3Point p; // for( DelaunayTriangle t : ps.getTriangles() ) // { // v1.set( t.points[0] ).addLocal( t.points[1] ).addLocal( t.points[2] ).multiplyLocal( 1.0d/3 ); // if( t.neighbors[0] != null ) // { // v2.set( t.points[2] ).subtractLocal( t.points[1] ).multiplyLocal( 0.5 ).addLocal( t.points[1] ); // v2Buf.put( v1.getXf() ).put( v1.getYf() ).put( v1.getZf() ); // v2Buf.put( v2.getXf() ).put( v2.getYf() ).put( v2.getZf() ); // lineCount++; // } // if( t.neighbors[1] != null ) // { // v2.set( t.points[0] ).subtractLocal( t.points[2] ).multiplyLocal( 0.5 ).addLocal( t.points[2] ); // v2Buf.put( v1.getXf() ).put( v1.getYf() ).put( v1.getZf() ); // v2Buf.put( v2.getXf() ).put( v2.getYf() ).put( v2.getZf() ); // lineCount++; // } // if( t.neighbors[2] != null ) // { // v2.set( t.points[1] ).subtractLocal( t.points[0] ).multiplyLocal( 0.5 ).addLocal( t.points[0] ); // v2Buf.put( v1.getXf() ).put( v1.getYf() ).put( v1.getZf() ); // v2Buf.put( v2.getXf() ).put( v2.getYf() ).put( v2.getZf() ); // lineCount++; // } // } // v2Buf.limit( 2*3*lineCount ); // Vector3.releaseTempInstance( v1 ); // Vector3.releaseTempInstance( v2 ); } } class CDTSweepActiveEdge extends SceneElement<DTSweepContext> { private Line m_edgeLine = new Line(); public CDTSweepActiveEdge() { super("ActiveEdge"); m_edgeLine.getMeshData().setIndexMode( IndexMode.Lines ); m_edgeLine.getMeshData().setVertexBuffer( BufferUtils.createVector3Buffer( 2 ) ); m_edgeLine.setDefaultColor( ColorRGBA.YELLOW ); m_edgeLine.setLineWidth( 3 ); } @Override public void update( DTSweepContext tcx ) { DTSweepConstraint edge = tcx.getDebugContext().getActiveConstraint(); if( edge != null ) { FloatBuffer fb = m_edgeLine.getMeshData().getVertexBuffer(); fb.rewind(); fb.put( edge.getP().getXf() ).put( edge.getP().getYf() ).put( 0 ); fb.put( edge.getQ().getXf() ).put( edge.getQ().getYf() ).put( 0 ); _node.attachChild( m_edgeLine ); } else { _node.detachAllChildren(); } } } class CDTSweepActiveTriangles extends SceneElement<DTSweepContext> { private Triangle m_a = new Triangle(); private Triangle m_b = new Triangle(); public CDTSweepActiveTriangles() { super("ActiveTriangles"); _node.getSceneHints().setAllPickingHints( false ); m_a.setDefaultColor( new ColorRGBA( 0.8f,0.8f,0.8f,1.0f ) ); m_b.setDefaultColor( new ColorRGBA( 0.5f,0.5f,0.5f,1.0f ) ); } public void setScale( double scale ) { m_a.setScale( scale ); m_b.setScale( scale ); } @Override public void update( DTSweepContext tcx ) { DelaunayTriangle t,t2; t = tcx.getDebugContext().getPrimaryTriangle(); t2 = tcx.getDebugContext().getSecondaryTriangle(); _node.detachAllChildren(); if( t != null ) { FloatBuffer fb = m_a.getMeshData().getVertexBuffer(); fb.rewind(); fb.put( t.points[0].getXf() ).put( t.points[0].getYf() ).put( t.points[0].getZf() ); fb.put( t.points[1].getXf() ).put( t.points[1].getYf() ).put( t.points[1].getZf() ); fb.put( t.points[2].getXf() ).put( t.points[2].getYf() ).put( t.points[2].getZf() ); _node.attachChild( m_a ); } if( t2 != null ) { FloatBuffer fb = m_b.getMeshData().getVertexBuffer(); fb.rewind(); fb.put( t2.points[0].getXf() ).put( t2.points[0].getYf() ).put( t2.points[0].getZf() ); fb.put( t2.points[1].getXf() ).put( t2.points[1].getYf() ).put( t2.points[1].getZf() ); fb.put( t2.points[2].getXf() ).put( t2.points[2].getYf() ).put( t2.points[2].getZf() ); _node.attachChild( m_b ); } } } class CDTSweepActiveNode extends SceneElement<DTSweepContext> { private Triangle m_a = new Triangle(); private Triangle m_b = new Triangle(); private Triangle m_c = new Triangle(); public CDTSweepActiveNode() { super("WorkingNode"); _node.setRenderState( new WireframeState() ); m_a.setDefaultColor( ColorRGBA.DARK_GRAY ); m_b.setDefaultColor( ColorRGBA.LIGHT_GRAY ); m_c.setDefaultColor( ColorRGBA.DARK_GRAY ); setScale( 0.5 ); } public void setScale( double scale ) { m_a.setScale( scale ); m_b.setScale( scale ); m_c.setScale( scale ); } @Override public void update( DTSweepContext tcx ) { AdvancingFrontNode node = tcx.getDebugContext().getActiveNode(); TriangulationPoint p; if( node != null ) { if( node.getPrevious() != null ) { p = node.getPrevious().getPoint(); m_a.setTranslation( p.getXf(), p.getYf(), p.getZf() ); } p = node.getPoint(); m_b.setTranslation( p.getXf(), p.getYf(), p.getZf() ); if( node.getNext() != null ) { p = node.getNext().getPoint(); m_c.setTranslation( p.getXf(), p.getYf(), p.getZf() ); } _node.attachChild( m_a ); _node.attachChild( m_b ); _node.attachChild( m_c ); } else { _node.detachAllChildren(); } } } }
Java
package org.poly2tri.examples.ardor3d; import java.io.IOException; import java.util.ArrayList; import org.poly2tri.Poly2Tri; import org.poly2tri.examples.ardor3d.base.P2TSimpleExampleBase; import org.poly2tri.examples.ardor3d.misc.DataLoader; import org.poly2tri.examples.ardor3d.misc.ExampleSets; import org.poly2tri.triangulation.TriangulationAlgorithm; import org.poly2tri.triangulation.TriangulationContext; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.point.TPoint; import org.poly2tri.triangulation.sets.PointSet; import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper; import org.poly2tri.triangulation.util.PointGenerator; import com.ardor3d.framework.FrameHandler; import com.ardor3d.input.logical.LogicalLayer; import com.ardor3d.math.ColorRGBA; import com.ardor3d.renderer.state.WireframeState; import com.ardor3d.scenegraph.Mesh; import com.google.inject.Inject; public class DTUniformDistributionExample extends P2TSimpleExampleBase { public static void main(final String[] args) { start(DTUniformDistributionExample.class); } @Inject public DTUniformDistributionExample( LogicalLayer logicalLayer, FrameHandler frameHandler ) { super( logicalLayer, frameHandler ); } @Override protected void initExample() { super.initExample(); PointSet ps; Mesh mesh; mesh = new Mesh(); mesh.setDefaultColor( ColorRGBA.BLUE ); mesh.setRenderState( new WireframeState() ); _node.attachChild( mesh ); try { ps = DataLoader.loadPointSet( ExampleSets.Example2, 0.1 ); ps = new PointSet( PointGenerator.uniformDistribution( 10000, 60 ) ); Poly2Tri.triangulate( ps ); ArdorMeshMapper.updateTriangleMesh( mesh, ps ); } catch( IOException e ) {} } }
Java
package org.poly2tri.examples.ardor3d; import java.util.List; import org.poly2tri.Poly2Tri; import org.poly2tri.examples.ardor3d.base.P2TSimpleExampleBase; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.point.TPoint; import org.poly2tri.triangulation.sets.ConstrainedPointSet; import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper; import org.poly2tri.triangulation.util.PointGenerator; import com.ardor3d.framework.FrameHandler; import com.ardor3d.input.logical.LogicalLayer; import com.ardor3d.math.ColorRGBA; import com.ardor3d.scenegraph.Mesh; import com.google.inject.Inject; public class CDTUniformDistributionExample extends P2TSimpleExampleBase { public static void main(final String[] args) { start(CDTUniformDistributionExample.class); } @Inject public CDTUniformDistributionExample( LogicalLayer logicalLayer, FrameHandler frameHandler ) { super( logicalLayer, frameHandler ); } @Override protected void initExample() { super.initExample(); Mesh mesh = new Mesh(); mesh.setDefaultColor( ColorRGBA.BLUE ); _node.attachChild( mesh ); double scale = 100; int size = 1000; int index = (int)(Math.random()*size); List<TriangulationPoint> points = PointGenerator.uniformDistribution( size, scale ); // Lets add a constraint that cuts the uniformDistribution in half points.add( new TPoint(0,scale/2) ); points.add( new TPoint(0,-scale/2) ); index = size; ConstrainedPointSet cps = new ConstrainedPointSet( points, new int[]{ index, index+1 } ); Poly2Tri.triangulate( cps ); ArdorMeshMapper.updateTriangleMesh( mesh, cps ); } }
Java
package org.poly2tri.examples.ardor3d; import java.util.ArrayList; import org.poly2tri.Poly2Tri; import org.poly2tri.examples.ardor3d.base.P2TSimpleExampleBase; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.geometry.polygon.PolygonPoint; import org.poly2tri.triangulation.point.TPoint; import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper; import org.poly2tri.triangulation.util.PolygonGenerator; import com.ardor3d.framework.FrameHandler; import com.ardor3d.input.logical.LogicalLayer; import com.ardor3d.math.ColorRGBA; import com.ardor3d.renderer.state.WireframeState; import com.ardor3d.scenegraph.Mesh; import com.ardor3d.scenegraph.Node; import com.google.inject.Inject; public class CDTSteinerPointExample extends P2TSimpleExampleBase { public static void main(final String[] args) { start(CDTSteinerPointExample.class); } @Inject public CDTSteinerPointExample( LogicalLayer logicalLayer, FrameHandler frameHandler ) { super( logicalLayer, frameHandler ); } @Override protected void initExample() { super.initExample(); Node node = new Node(); node.setRenderState( new WireframeState() ); _node.attachChild( node ); Polygon poly; poly = createCirclePolygon( 32, 1.5 ); // top left Mesh mesh = new Mesh(); mesh.setDefaultColor( ColorRGBA.BLUE ); mesh.setTranslation( -2, 2, 0 ); node.attachChild( mesh ); Poly2Tri.triangulate( poly ); ArdorMeshMapper.updateTriangleMesh( mesh, poly ); // bottom left mesh = new Mesh(); mesh.setDefaultColor( ColorRGBA.RED ); mesh.setTranslation( -2, -2, 0 ); node.attachChild( mesh ); poly.addSteinerPoint( new TPoint(0,0) ); Poly2Tri.triangulate( poly ); ArdorMeshMapper.updateTriangleMesh( mesh, poly ); poly = PolygonGenerator.RandomCircleSweep2( 4, 200 ); // top right mesh = new Mesh(); mesh.setDefaultColor( ColorRGBA.BLUE ); mesh.setTranslation( 2, 2, 0 ); node.attachChild( mesh ); Poly2Tri.triangulate( poly ); ArdorMeshMapper.updateTriangleMesh( mesh, poly ); // bottom right mesh = new Mesh(); mesh.setDefaultColor( ColorRGBA.RED ); mesh.setTranslation( 2, -2, 0 ); node.attachChild( mesh ); poly.addSteinerPoint( new TPoint(0,0) ); Poly2Tri.triangulate( poly ); ArdorMeshMapper.updateTriangleMesh( mesh, poly ); } private Polygon createCirclePolygon( int n, double radius ) { if( n < 3 ) n=3; PolygonPoint[] points = new PolygonPoint[n]; for( int i=0; i<n; i++ ) { points[i] = new PolygonPoint( radius*Math.cos( (2.0*Math.PI*i)/n ), radius*Math.sin( (2.0*Math.PI*i)/n ) ); } return new Polygon( points ); } }
Java
package org.poly2tri.examples; import org.poly2tri.Poly2Tri; import org.poly2tri.triangulation.sets.PointSet; import org.poly2tri.triangulation.util.PointGenerator; public class ProfilingExample { public static void main(final String[] args) throws Exception { PointSet ps = new PointSet( PointGenerator.uniformDistribution( 50, 500000 ) ); for( int i=0; i<1; i++ ) { Poly2Tri.triangulate( ps ); } Thread.sleep( 10000000 ); } public void startProfiling() throws Exception { } }
Java
package org.poly2tri.examples.geotools; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import org.geotools.data.FeatureSource; import org.geotools.data.shapefile.ShapefileDataStore; import org.geotools.feature.FeatureCollection; import org.geotools.feature.FeatureIterator; import org.opengis.feature.Feature; import org.opengis.feature.GeometryAttribute; import org.poly2tri.Poly2Tri; import org.poly2tri.examples.ardor3d.base.P2TSimpleExampleBase; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.geometry.polygon.PolygonPoint; import org.poly2tri.geometry.polygon.PolygonSet; import org.poly2tri.transform.coordinate.CoordinateTransform; import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ardor3d.example.ExampleBase; import com.ardor3d.framework.Canvas; import com.ardor3d.framework.FrameHandler; import com.ardor3d.image.Image; import com.ardor3d.image.Texture; import com.ardor3d.image.Texture.WrapMode; import com.ardor3d.input.MouseButton; import com.ardor3d.input.logical.InputTrigger; import com.ardor3d.input.logical.LogicalLayer; import com.ardor3d.input.logical.MouseButtonClickedCondition; import com.ardor3d.input.logical.TriggerAction; import com.ardor3d.input.logical.TwoInputStates; import com.ardor3d.math.ColorRGBA; import com.ardor3d.math.MathUtils; import com.ardor3d.math.Matrix3; import com.ardor3d.math.Vector3; import com.ardor3d.renderer.queue.RenderBucketType; import com.ardor3d.renderer.state.BlendState; import com.ardor3d.renderer.state.MaterialState; import com.ardor3d.renderer.state.WireframeState; import com.ardor3d.renderer.state.ZBufferState; import com.ardor3d.renderer.state.BlendState.BlendEquation; import com.ardor3d.scenegraph.FloatBufferData; import com.ardor3d.scenegraph.Mesh; import com.ardor3d.scenegraph.Node; import com.ardor3d.scenegraph.extension.Skybox; import com.ardor3d.scenegraph.extension.Skybox.Face; import com.ardor3d.scenegraph.hint.LightCombineMode; import com.ardor3d.scenegraph.shape.Sphere; import com.ardor3d.util.ReadOnlyTimer; import com.ardor3d.util.TextureManager; import com.ardor3d.util.resource.ResourceLocatorTool; import com.ardor3d.util.resource.SimpleResourceLocator; import com.google.inject.Inject; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.LinearRing; import com.vividsolutions.jts.geom.MultiLineString; import com.vividsolutions.jts.geom.MultiPolygon; /** * Hello world! * */ public class WorldExample extends P2TSimpleExampleBase { private final static Logger logger = LoggerFactory.getLogger( WorldExample.class ); private final static CoordinateTransform _wgs84 = new WGS84GeodeticTransform(100); private Node _worldNode; private Skybox _skybox; private final Matrix3 rotate = new Matrix3(); private double angle = 0; private boolean _doRotate = true; /** * We use one PolygonSet for each country since countries can have islands * and be composed of multiple polygons */ private ArrayList<PolygonSet> _countries = new ArrayList<PolygonSet>(); @Inject public WorldExample( LogicalLayer logicalLayer, FrameHandler frameHandler ) { super( logicalLayer, frameHandler ); } public static void main( String[] args ) throws Exception { try { start(WorldExample.class); } catch( RuntimeException e ) { logger.error( "WorldExample failed due to a runtime exception" ); } } @Override protected void updateExample( ReadOnlyTimer timer ) { if( _doRotate ) { angle += timer.getTimePerFrame() * 10; angle %= 360; rotate.fromAngleNormalAxis(angle * MathUtils.DEG_TO_RAD, Vector3.UNIT_Z); _worldNode.setRotation(rotate); } } @Override protected void initExample() { super.initExample(); try { importShape(100); } catch( IOException e ) { } _canvas.getCanvasRenderer().getCamera().setLocation(200, 200, 200); _canvas.getCanvasRenderer().getCamera().lookAt( 0, 0, 0, Vector3.UNIT_Z ); _worldNode = new Node("shape"); // _worldNode.setRenderState( new WireframeState() ); _node.attachChild( _worldNode ); buildSkyBox(); Sphere seas = new Sphere("seas", Vector3.ZERO, 64, 64, 100.2f); seas.setDefaultColor( new ColorRGBA(0,0,0.5f,0.25f) ); seas.getSceneHints().setRenderBucketType( RenderBucketType.Transparent ); BlendState bs = new BlendState(); bs.setBlendEnabled( true ); bs.setEnabled( true ); bs.setBlendEquationAlpha( BlendEquation.Max ); bs.setSourceFunction(BlendState.SourceFunction.SourceAlpha); bs.setDestinationFunction(BlendState.DestinationFunction.OneMinusSourceAlpha); seas.setRenderState( bs ); ZBufferState zb = new ZBufferState(); zb.setEnabled( true ); zb.setWritable( false ); seas.setRenderState( zb ); _worldNode.attachChild( seas ); Sphere core = new Sphere("seas", Vector3.ZERO, 16, 16, 10f); core.getSceneHints().setLightCombineMode( LightCombineMode.Replace ); MaterialState ms = new MaterialState(); ms.setEmissive( new ColorRGBA(0.8f,0.2f,0,0.9f) ); core.setRenderState( ms ); _worldNode.attachChild( core ); Mesh mesh; for( PolygonSet ps : _countries ) { Poly2Tri.triangulate( ps ); float value = 1-0.9f*(float)Math.random(); for( Polygon p : ps.getPolygons() ) { mesh = new Mesh(); mesh.setDefaultColor( new ColorRGBA( value, value, value, 1.0f ) ); _worldNode.attachChild( mesh ); ArdorMeshMapper.updateTriangleMesh( mesh, p, _wgs84 ); } } } protected void importShape( double rescale ) throws IOException { // URL url = WorldExample.class.getResource( "/z5UKI.shp" ); URL url = WorldExample.class.getResource( "/earth/countries.shp" ); url.getFile(); ShapefileDataStore ds = new ShapefileDataStore(url); FeatureSource featureSource = ds.getFeatureSource(); // for( int i=0; i < ds.getTypeNames().length; i++) // { // System.out.println("ShapefileDataStore.typename=" + ds.getTypeNames()[i] ); // } FeatureCollection fc = featureSource.getFeatures(); // System.out.println( "featureCollection.ID=" + fc.getID() ); // System.out.println( "featureCollection.schema=" + fc.getSchema() ); // System.out.println( "featureCollection.Bounds[minX,maxX,minY,maxY]=[" // + fc.getBounds().getMinX() + "," + // + fc.getBounds().getMaxX() + "," + // + fc.getBounds().getMinY() + "," + // + fc.getBounds().getMaxY() + "]" ); // double width, height, xScale, yScale, scale, dX, dY; // width = fc.getBounds().getMaxX() - fc.getBounds().getMinX(); // height = fc.getBounds().getMaxY() - fc.getBounds().getMinY(); // dX = fc.getBounds().getMinX() + width/2; // dY = fc.getBounds().getMinY() + height/2; // xScale = rescale * 1f / width; // yScale = rescale * 1f / height; // scale = xScale < yScale ? xScale : yScale; FeatureIterator fi; Feature f; GeometryAttribute geoAttrib; Polygon polygon; PolygonSet polygonSet; fi = fc.features(); while( fi.hasNext() ) { polygonSet = new PolygonSet(); f = fi.next(); geoAttrib = f.getDefaultGeometryProperty(); // System.out.println( "Feature.Identifier:" + f.getIdentifier() ); // System.out.println( "Feature.Name:" + f.getName() ); // System.out.println( "Feature.Type:" + f.getType() ); // System.out.println( "Feature.Descriptor:" + geoAttrib.getDescriptor() ); // System.out.println( "GeoAttrib.Identifier=" + geoAttrib.getIdentifier() ); // System.out.println( "GeoAttrib.Name=" + geoAttrib.getName() ); // System.out.println( "GeoAttrib.Type.Name=" + geoAttrib.getType().getName() ); // System.out.println( "GeoAttrib.Type.Binding=" + geoAttrib.getType().getBinding() ); // System.out.println( "GeoAttrib.Value=" + geoAttrib.getValue() ); if( geoAttrib.getType().getBinding() == MultiLineString.class ) { MultiLineString mls = (MultiLineString)geoAttrib.getValue(); Coordinate[] coords = mls.getCoordinates(); // System.out.println( "MultiLineString.coordinates=" + coords.length ); ArrayList<PolygonPoint> points = new ArrayList<PolygonPoint>(coords.length); for( int i=0; i<coords.length; i++) { points.add( new PolygonPoint(coords[i].x,coords[i].y) ); // System.out.println( "[x,y]=[" + coords[i].x + "," + coords[i].y + "]" ); } polygonSet.add( new Polygon(points) ); } else if( geoAttrib.getType().getBinding() == MultiPolygon.class ) { MultiPolygon mp = (MultiPolygon)geoAttrib.getValue(); // System.out.println( "MultiPolygon.NumGeometries=" + mp.getNumGeometries() ); for( int i=0; i<mp.getNumGeometries(); i++ ) { com.vividsolutions.jts.geom.Polygon jtsPolygon = (com.vividsolutions.jts.geom.Polygon)mp.getGeometryN(i); polygon = buildPolygon( jtsPolygon ); polygonSet.add( polygon ); } } _countries.add( polygonSet ); } } private static Polygon buildPolygon( com.vividsolutions.jts.geom.Polygon jtsPolygon ) { Polygon polygon; LinearRing shell; ArrayList<PolygonPoint> points; // Envelope envelope; // System.out.println( "MultiPolygon.points=" + jtsPolygon.getNumPoints() ); // System.out.println( "MultiPolygon.NumInteriorRing=" + jtsPolygon.getNumInteriorRing() ); // envelope = jtsPolygon.getEnvelopeInternal(); shell = (LinearRing)jtsPolygon.getExteriorRing(); Coordinate[] coords = shell.getCoordinates(); points = new ArrayList<PolygonPoint>(coords.length); // Skipping last coordinate since JTD defines a shell as a LineString that start with // same first and last coordinate for( int j=0; j<coords.length-1; j++) { points.add( new PolygonPoint(coords[j].x,coords[j].y) ); } polygon = new Polygon(points); return polygon; } // // private void refinePolygon() // { // // } /** * Builds the sky box. */ private void buildSkyBox() { _skybox = new Skybox("skybox", 300, 300, 300); try { SimpleResourceLocator sr2 = new SimpleResourceLocator(ExampleBase.class.getClassLoader().getResource("org/poly2tri/examples/geotools/textures/")); ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, sr2); } catch (final URISyntaxException ex) { ex.printStackTrace(); } final String dir = ""; final Texture stars = TextureManager.load(dir + "stars.gif", Texture.MinificationFilter.Trilinear, Image.Format.GuessNoCompression, true); _skybox.setTexture(Skybox.Face.North, stars); _skybox.setTexture(Skybox.Face.West, stars); _skybox.setTexture(Skybox.Face.South, stars); _skybox.setTexture(Skybox.Face.East, stars); _skybox.setTexture(Skybox.Face.Up, stars); _skybox.setTexture(Skybox.Face.Down, stars); _skybox.getTexture( Skybox.Face.North ).setWrap( WrapMode.Repeat ); for( Face f : Face.values() ) { FloatBufferData fbd = _skybox.getFace(f).getMeshData().getTextureCoords().get( 0 ); fbd.getBuffer().clear(); fbd.getBuffer().put( 0 ).put( 4 ); fbd.getBuffer().put( 0 ).put( 0 ); fbd.getBuffer().put( 4 ).put( 0 ); fbd.getBuffer().put( 4 ).put( 4 ); } _node.attachChild( _skybox ); } @Override public void registerInputTriggers() { super.registerInputTriggers(); // SPACE - toggle models _logicalLayer.registerTrigger( new InputTrigger( new MouseButtonClickedCondition(MouseButton.RIGHT), new TriggerAction() { public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf ) { _doRotate = _doRotate ? false : true; } } ) ); } /* * http://en.wikipedia.org/wiki/Longitude#Degree_length * http://www.colorado.edu/geography/gcraft/notes/datum/gif/llhxyz.gif * * x (in m) = Latitude * 60 * 1852 * y (in m) = (PI/180) * cos(Longitude) * (637813.7^2 / sqrt( (637813.7 * cos(Longitude))^2 + (635675.23 * sin(Longitude))^2 ) ) * z (in m) = Altitude * * The 'quick and dirty' method (assuming the Earth is a perfect sphere): * * x = longitude*60*1852*cos(latitude) * y = latitude*60*1852 * * Latitude and longitude must be in decimal degrees, x and y are in meters. * The origin of the xy-grid is the intersection of the 0-degree meridian * and the equator, where x is positive East and y is positive North. * * So, why the 1852? I'm using the (original) definition of a nautical mile * here: 1 nautical mile = the length of one arcminute on the equator (hence * the 60*1852; I'm converting the lat/lon degrees to lat/lon minutes). */ }
Java
package org.poly2tri.geometry.primitives; public abstract class Point { public abstract double getX(); public abstract double getY(); public abstract double getZ(); public abstract float getXf(); public abstract float getYf(); public abstract float getZf(); public abstract void set( double x, double y, double z ); protected static int calculateHashCode( double x, double y, double z) { int result = 17; final long a = Double.doubleToLongBits(x); result += 31 * result + (int) (a ^ (a >>> 32)); final long b = Double.doubleToLongBits(y); result += 31 * result + (int) (b ^ (b >>> 32)); final long c = Double.doubleToLongBits(z); result += 31 * result + (int) (c ^ (c >>> 32)); return result; } }
Java
package org.poly2tri.geometry.primitives; public abstract class Edge<A extends Point> { protected A p; protected A q; public A getP() { return p; } public A getQ() { return q; } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.geometry.polygon; import java.util.ArrayList; import java.util.List; public class PolygonSet { protected ArrayList<Polygon> _polygons = new ArrayList<Polygon>(); public PolygonSet() { } public PolygonSet( Polygon poly ) { _polygons.add( poly ); } public void add( Polygon p ) { _polygons.add( p ); } public List<Polygon> getPolygons() { return _polygons; } }
Java
package org.poly2tri.geometry.polygon; import org.poly2tri.triangulation.point.TPoint; public class PolygonPoint extends TPoint { protected PolygonPoint _next; protected PolygonPoint _previous; public PolygonPoint( double x, double y ) { super( x, y ); } public PolygonPoint( double x, double y, double z ) { super( x, y, z ); } public void setPrevious( PolygonPoint p ) { _previous = p; } public void setNext( PolygonPoint p ) { _next = p; } public PolygonPoint getNext() { return _next; } public PolygonPoint getPrevious() { return _previous; } }
Java
package org.poly2tri.geometry.polygon; public class PolygonUtil { /** * TODO * @param polygon */ public static void validate( Polygon polygon ) { // TODO: implement // 1. Check for duplicate points // 2. Check for intersecting sides } }
Java
package org.poly2tri.geometry.polygon; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.poly2tri.triangulation.Triangulatable; import org.poly2tri.triangulation.TriangulationContext; import org.poly2tri.triangulation.TriangulationMode; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.delaunay.DelaunayTriangle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Polygon implements Triangulatable { private final static Logger logger = LoggerFactory.getLogger( Polygon.class ); protected ArrayList<TriangulationPoint> _points = new ArrayList<TriangulationPoint>(); protected ArrayList<TriangulationPoint> _steinerPoints; protected ArrayList<Polygon> _holes; protected List<DelaunayTriangle> m_triangles; protected PolygonPoint _last; /** * To create a polygon we need atleast 3 separate points * * @param p1 * @param p2 * @param p3 */ public Polygon( PolygonPoint p1, PolygonPoint p2, PolygonPoint p3 ) { p1._next = p2; p2._next = p3; p3._next = p1; p1._previous = p3; p2._previous = p1; p3._previous = p2; _points.add( p1 ); _points.add( p2 ); _points.add( p3 ); } /** * Requires atleast 3 points * @param points - ordered list of points forming the polygon. * No duplicates are allowed */ public Polygon( List<PolygonPoint> points ) { // Lets do one sanity check that first and last point hasn't got same position // Its something that often happen when importing polygon data from other formats if( points.get(0).equals( points.get(points.size()-1) ) ) { logger.warn( "Removed duplicate point"); points.remove( points.size()-1 ); } _points.addAll( points ); } /** * Requires atleast 3 points * * @param points */ public Polygon( PolygonPoint[] points ) { this( Arrays.asList( points ) ); } public TriangulationMode getTriangulationMode() { return TriangulationMode.POLYGON; } public int pointCount() { int count = _points.size(); if( _steinerPoints != null ) { count += _steinerPoints.size(); } return count; } public void addSteinerPoint( TriangulationPoint point ) { if( _steinerPoints == null ) { _steinerPoints = new ArrayList<TriangulationPoint>(); } _steinerPoints.add( point ); } public void addSteinerPoints( List<TriangulationPoint> points ) { if( _steinerPoints == null ) { _steinerPoints = new ArrayList<TriangulationPoint>(); } _steinerPoints.addAll( points ); } public void clearSteinerPoints() { if( _steinerPoints != null ) { _steinerPoints.clear(); } } /** * Assumes: that given polygon is fully inside the current polygon * @param poly - a subtraction polygon */ public void addHole( Polygon poly ) { if( _holes == null ) { _holes = new ArrayList<Polygon>(); } _holes.add( poly ); // XXX: tests could be made here to be sure it is fully inside // addSubtraction( poly.getPoints() ); } /** * Will insert a point in the polygon after given point * * @param a * @param b * @param p */ public void insertPointAfter( PolygonPoint a, PolygonPoint newPoint ) { // Validate that int index = _points.indexOf( a ); if( index != -1 ) { newPoint.setNext( a.getNext() ); newPoint.setPrevious( a ); a.getNext().setPrevious( newPoint ); a.setNext( newPoint ); _points.add( index+1, newPoint ); } else { throw new RuntimeException( "Tried to insert a point into a Polygon after a point not belonging to the Polygon" ); } } public void addPoints( List<PolygonPoint> list ) { PolygonPoint first; for( PolygonPoint p : list ) { p.setPrevious( _last ); if( _last != null ) { p.setNext( _last.getNext() ); _last.setNext( p ); } _last = p; _points.add( p ); } first = (PolygonPoint)_points.get(0); _last.setNext( first ); first.setPrevious( _last ); } /** * Will add a point after the last point added * * @param p */ public void addPoint(PolygonPoint p ) { p.setPrevious( _last ); p.setNext( _last.getNext() ); _last.setNext( p ); _points.add( p ); } public void removePoint( PolygonPoint p ) { PolygonPoint next, prev; next = p.getNext(); prev = p.getPrevious(); prev.setNext( next ); next.setPrevious( prev ); _points.remove( p ); } public PolygonPoint getPoint() { return _last; } public List<TriangulationPoint> getPoints() { return _points; } public List<DelaunayTriangle> getTriangles() { return m_triangles; } public void addTriangle( DelaunayTriangle t ) { m_triangles.add( t ); } public void addTriangles( List<DelaunayTriangle> list ) { m_triangles.addAll( list ); } public void clearTriangulation() { if( m_triangles != null ) { m_triangles.clear(); } } /** * Creates constraints and populates the context with points */ public void prepareTriangulation( TriangulationContext<?> tcx ) { if( m_triangles == null ) { m_triangles = new ArrayList<DelaunayTriangle>( _points.size() ); } else { m_triangles.clear(); } // Outer constraints for( int i = 0; i < _points.size()-1 ; i++ ) { tcx.newConstraint( _points.get( i ), _points.get( i+1 ) ); } tcx.newConstraint( _points.get( 0 ), _points.get( _points.size()-1 ) ); tcx.addPoints( _points ); // Hole constraints if( _holes != null ) { for( Polygon p : _holes ) { for( int i = 0; i < p._points.size()-1 ; i++ ) { tcx.newConstraint( p._points.get( i ), p._points.get( i+1 ) ); } tcx.newConstraint( p._points.get( 0 ), p._points.get( p._points.size()-1 ) ); tcx.addPoints( p._points ); } } if( _steinerPoints != null ) { tcx.addPoints( _steinerPoints ); } } }
Java
package org.poly2tri.triangulation; public abstract class TriangulationDebugContext { protected TriangulationContext<?> _tcx; public TriangulationDebugContext( TriangulationContext<?> tcx ) { _tcx = tcx; } public abstract void clear(); }
Java
package org.poly2tri.triangulation; public enum TriangulationMode { UNCONSTRAINED,CONSTRAINED,POLYGON; }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation.point; import org.poly2tri.triangulation.TriangulationPoint; public class TPoint extends TriangulationPoint { private double _x; private double _y; private double _z; public TPoint( double x, double y ) { this( x, y, 0 ); } public TPoint( double x, double y, double z ) { _x = x; _y = y; _z = z; } public double getX() { return _x; } public double getY() { return _y; } public double getZ() { return _z; } public float getXf() { return (float)_x; } public float getYf() { return (float)_y; } public float getZf() { return (float)_z; } @Override public void set( double x, double y, double z ) { _x = x; _y = y; _z = z; } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation.point; import java.nio.FloatBuffer; import org.poly2tri.triangulation.TriangulationPoint; public class FloatBufferPoint extends TriangulationPoint { private final FloatBuffer _fb; private final int _ix,_iy,_iz; public FloatBufferPoint( FloatBuffer fb, int index ) { _fb = fb; _ix = index; _iy = index+1; _iz = index+2; } public final double getX() { return _fb.get( _ix ); } public final double getY() { return _fb.get( _iy ); } public final double getZ() { return _fb.get( _iz ); } public final float getXf() { return _fb.get( _ix ); } public final float getYf() { return _fb.get( _iy ); } public final float getZf() { return _fb.get( _iz ); } @Override public void set( double x, double y, double z ) { _fb.put( _ix, (float)x ); _fb.put( _iy, (float)y ); _fb.put( _iz, (float)z ); } public static TriangulationPoint[] toPoints( FloatBuffer fb ) { FloatBufferPoint[] points = new FloatBufferPoint[fb.limit()/3]; for( int i=0,j=0; i<points.length; i++, j+=3 ) { points[i] = new FloatBufferPoint(fb, j); } return points; } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation; import java.util.ArrayList; import java.util.List; import org.poly2tri.triangulation.delaunay.DelaunayTriangle; public abstract class TriangulationContext<A extends TriangulationDebugContext> { protected A _debug; protected boolean _debugEnabled = false; protected ArrayList<DelaunayTriangle> _triList = new ArrayList<DelaunayTriangle>(); protected ArrayList<TriangulationPoint> _points = new ArrayList<TriangulationPoint>(200); protected TriangulationMode _triangulationMode; protected Triangulatable _triUnit; private boolean _terminated = false; private boolean _waitUntilNotified; private int _stepTime = -1; private int _stepCount = 0; public int getStepCount() { return _stepCount; } public void done() { _stepCount++; } public abstract TriangulationAlgorithm algorithm(); public void prepareTriangulation( Triangulatable t ) { _triUnit = t; _triangulationMode = t.getTriangulationMode(); t.prepareTriangulation( this ); } public abstract TriangulationConstraint newConstraint( TriangulationPoint a, TriangulationPoint b ); public void addToList( DelaunayTriangle triangle ) { _triList.add( triangle ); } public List<DelaunayTriangle> getTriangles() { return _triList; } public Triangulatable getTriangulatable() { return _triUnit; } public List<TriangulationPoint> getPoints() { return _points; } public synchronized void update(String message) { if( _debugEnabled ) { try { synchronized( this ) { _stepCount++; if( _stepTime > 0 ) { wait( (int)_stepTime ); /** Can we resume execution or are we expected to wait? */ if( _waitUntilNotified ) { wait(); } } else { wait(); } // We have been notified _waitUntilNotified = false; } } catch( InterruptedException e ) { update("Triangulation was interrupted"); } } if( _terminated ) { throw new RuntimeException( "Triangulation process terminated before completion"); } } public void clear() { _points.clear(); _terminated = false; if( _debug != null ) { _debug.clear(); } _stepCount=0; } public TriangulationMode getTriangulationMode() { return _triangulationMode; } public synchronized void waitUntilNotified(boolean b) { _waitUntilNotified = b; } public void terminateTriangulation() { _terminated=true; } public boolean isDebugEnabled() { return _debugEnabled; } public abstract void isDebugEnabled( boolean b ); public A getDebugContext() { return _debug; } public void addPoints( List<TriangulationPoint> points ) { _points.addAll( points ); } }
Java
package org.poly2tri.triangulation; import java.util.List; import org.poly2tri.triangulation.delaunay.DelaunayTriangle; public interface Triangulatable { /** * Preparations needed before triangulation start should be handled here * @param tcx */ public void prepareTriangulation( TriangulationContext<?> tcx ); public List<DelaunayTriangle> getTriangles(); public List<TriangulationPoint> getPoints(); public void addTriangle( DelaunayTriangle t ); public void addTriangles( List<DelaunayTriangle> list ); public void clearTriangulation(); public TriangulationMode getTriangulationMode(); }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation; import java.util.ArrayList; import org.poly2tri.geometry.primitives.Point; import org.poly2tri.triangulation.delaunay.sweep.DTSweepConstraint; public abstract class TriangulationPoint extends Point { // List of edges this point constitutes an upper ending point (CDT) private ArrayList<DTSweepConstraint> edges; @Override public String toString() { return "[" + getX() + "," + getY() + "]"; } public abstract double getX(); public abstract double getY(); public abstract double getZ(); public abstract float getXf(); public abstract float getYf(); public abstract float getZf(); public abstract void set( double x, double y, double z ); public ArrayList<DTSweepConstraint> getEdges() { return edges; } public void addEdge( DTSweepConstraint e ) { if( edges == null ) { edges = new ArrayList<DTSweepConstraint>(); } edges.add( e ); } public boolean hasEdges() { return edges != null; } /** * @param p - edge destination point * @return the edge from this point to given point */ public DTSweepConstraint getEdge( TriangulationPoint p ) { for( DTSweepConstraint c : edges ) { if( c.p == p ) { return c; } } return null; } public boolean equals(Object obj) { if( obj instanceof TriangulationPoint ) { TriangulationPoint p = (TriangulationPoint)obj; return getX() == p.getX() && getY() == p.getY(); } return super.equals( obj ); } public int hashCode() { long bits = java.lang.Double.doubleToLongBits(getX()); bits ^= java.lang.Double.doubleToLongBits(getY()) * 31; return (((int) bits) ^ ((int) (bits >> 32))); } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation.delaunay; import java.util.ArrayList; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.delaunay.sweep.DTSweepConstraint; import org.poly2tri.triangulation.point.TPoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DelaunayTriangle { private final static Logger logger = LoggerFactory.getLogger( DelaunayTriangle.class ); /** Neighbor pointers */ public final DelaunayTriangle[] neighbors = new DelaunayTriangle[3]; /** Flags to determine if an edge is a Constrained edge */ public final boolean[] cEdge = new boolean[] { false, false, false }; /** Flags to determine if an edge is a Delauney edge */ public final boolean[] dEdge = new boolean[] { false, false, false }; /** Has this triangle been marked as an interior triangle? */ protected boolean interior = false; public final TriangulationPoint[] points = new TriangulationPoint[3]; public DelaunayTriangle( TriangulationPoint p1, TriangulationPoint p2, TriangulationPoint p3 ) { points[0] = p1; points[1] = p2; points[2] = p3; } public int index( TriangulationPoint p ) { if( p == points[0] ) { return 0; } else if( p == points[1] ) { return 1; } else if( p == points[2] ) { return 2; } throw new RuntimeException("Calling index with a point that doesn't exist in triangle"); } public int indexCW( TriangulationPoint p ) { int index = index(p); switch( index ) { case 0: return 2; case 1: return 0; default: return 1; } } public int indexCCW( TriangulationPoint p ) { int index = index(p); switch( index ) { case 0: return 1; case 1: return 2; default: return 0; } } public boolean contains( TriangulationPoint p ) { return ( p == points[0] || p == points[1] || p == points[2] ); } public boolean contains( DTSweepConstraint e ) { return ( contains( e.p ) && contains( e.q ) ); } public boolean contains( TriangulationPoint p, TriangulationPoint q ) { return ( contains( p ) && contains( q ) ); } // Update neighbor pointers private void markNeighbor( TriangulationPoint p1, TriangulationPoint p2, DelaunayTriangle t ) { if( ( p1 == points[2] && p2 == points[1] ) || ( p1 == points[1] && p2 == points[2] ) ) { neighbors[0] = t; } else if( ( p1 == points[0] && p2 == points[2] ) || ( p1 == points[2] && p2 == points[0] ) ) { neighbors[1] = t; } else if( ( p1 == points[0] && p2 == points[1] ) || ( p1 == points[1] && p2 == points[0] ) ) { neighbors[2] = t; } else { logger.error( "Neighbor error, please report!" ); // throw new Exception("Neighbor error, please report!"); } } /* Exhaustive search to update neighbor pointers */ public void markNeighbor( DelaunayTriangle t ) { if( t.contains( points[1], points[2] ) ) { neighbors[0] = t; t.markNeighbor( points[1], points[2], this ); } else if( t.contains( points[0], points[2] ) ) { neighbors[1] = t; t.markNeighbor( points[0], points[2], this ); } else if( t.contains( points[0], points[1] ) ) { neighbors[2] = t; t.markNeighbor( points[0], points[1], this ); } else { logger.error( "markNeighbor failed" ); } } public void clearNeighbors() { neighbors[0] = neighbors[1] = neighbors[2] = null; } public void clearNeighbor( DelaunayTriangle triangle ) { if( neighbors[0] == triangle ) { neighbors[0] = null; } else if( neighbors[1] == triangle ) { neighbors[1] = null; } else { neighbors[2] = null; } } /** * Clears all references to all other triangles and points */ public void clear() { DelaunayTriangle t; for( int i=0; i<3; i++ ) { t = neighbors[i]; if( t != null ) { t.clearNeighbor( this ); } } clearNeighbors(); points[0]=points[1]=points[2]=null; } /** * @param t - opposite triangle * @param p - the point in t that isn't shared between the triangles * @return */ public TriangulationPoint oppositePoint( DelaunayTriangle t, TriangulationPoint p ) { assert t != this : "self-pointer error"; return pointCW( t.pointCW(p) ); } // The neighbor clockwise to given point public DelaunayTriangle neighborCW( TriangulationPoint point ) { if( point == points[0] ) { return neighbors[1]; } else if( point == points[1] ) { return neighbors[2]; } return neighbors[0]; } // The neighbor counter-clockwise to given point public DelaunayTriangle neighborCCW( TriangulationPoint point ) { if( point == points[0] ) { return neighbors[2]; } else if( point == points[1] ) { return neighbors[0]; } return neighbors[1]; } // The neighbor across to given point public DelaunayTriangle neighborAcross( TriangulationPoint opoint ) { if( opoint == points[0] ) { return neighbors[0]; } else if( opoint == points[1] ) { return neighbors[1]; } return neighbors[2]; } // The point counter-clockwise to given point public TriangulationPoint pointCCW( TriangulationPoint point ) { if( point == points[0] ) { return points[1]; } else if( point == points[1] ) { return points[2]; } else if( point == points[2] ) { return points[0]; } logger.error( "point location error" ); throw new RuntimeException("[FIXME] point location error"); } // The point counter-clockwise to given point public TriangulationPoint pointCW( TriangulationPoint point ) { if( point == points[0] ) { return points[2]; } else if( point == points[1] ) { return points[0]; } else if( point == points[2] ) { return points[1]; } logger.error( "point location error" ); throw new RuntimeException("[FIXME] point location error"); } // Legalize triangle by rotating clockwise around oPoint public void legalize( TriangulationPoint oPoint, TriangulationPoint nPoint ) { if( oPoint == points[0] ) { points[1] = points[0]; points[0] = points[2]; points[2] = nPoint; } else if( oPoint == points[1] ) { points[2] = points[1]; points[1] = points[0]; points[0] = nPoint; } else if( oPoint == points[2] ) { points[0] = points[2]; points[2] = points[1]; points[1] = nPoint; } else { logger.error( "legalization error" ); throw new RuntimeException("legalization bug"); } } public void printDebug() { System.out.println( points[0] + "," + points[1] + "," + points[2] ); } // Finalize edge marking public void markNeighborEdges() { for( int i = 0; i < 3; i++ ) { if( cEdge[i] ) { switch( i ) { case 0: if( neighbors[0] != null ) neighbors[0].markConstrainedEdge( points[1], points[2] ); break; case 1: if( neighbors[1] != null ) neighbors[1].markConstrainedEdge( points[0], points[2] ); break; case 2: if( neighbors[2] != null ) neighbors[2].markConstrainedEdge( points[0], points[1] ); break; } } } } public void markEdge( DelaunayTriangle triangle ) { for( int i = 0; i < 3; i++ ) { if( cEdge[i] ) { switch( i ) { case 0: triangle.markConstrainedEdge( points[1], points[2] ); break; case 1: triangle.markConstrainedEdge( points[0], points[2] ); break; case 2: triangle.markConstrainedEdge( points[0], points[1] ); break; } } } } public void markEdge( ArrayList<DelaunayTriangle> tList ) { for( DelaunayTriangle t : tList ) { for( int i = 0; i < 3; i++ ) { if( t.cEdge[i] ) { switch( i ) { case 0: markConstrainedEdge( t.points[1], t.points[2] ); break; case 1: markConstrainedEdge( t.points[0], t.points[2] ); break; case 2: markConstrainedEdge( t.points[0], t.points[1] ); break; } } } } } public void markConstrainedEdge( int index ) { cEdge[index] = true; } public void markConstrainedEdge( DTSweepConstraint edge ) { markConstrainedEdge( edge.p, edge.q ); if( ( edge.q == points[0] && edge.p == points[1] ) || ( edge.q == points[1] && edge.p == points[0] ) ) { cEdge[2] = true; } else if( ( edge.q == points[0] && edge.p == points[2] ) || ( edge.q == points[2] && edge.p == points[0] ) ) { cEdge[1] = true; } else if( ( edge.q == points[1] && edge.p == points[2] ) || ( edge.q == points[2] && edge.p == points[1] ) ) { cEdge[0] = true; } } // Mark edge as constrained public void markConstrainedEdge( TriangulationPoint p, TriangulationPoint q ) { if( ( q == points[0] && p == points[1] ) || ( q == points[1] && p == points[0] ) ) { cEdge[2] = true; } else if( ( q == points[0] && p == points[2] ) || ( q == points[2] && p == points[0] ) ) { cEdge[1] = true; } else if( ( q == points[1] && p == points[2] ) || ( q == points[2] && p == points[1] ) ) { cEdge[0] = true; } } public double area() { double a = (points[0].getX() - points[2].getX())*(points[1].getY() - points[0].getY()); double b = (points[0].getX() - points[1].getX())*(points[2].getY() - points[0].getY()); return 0.5*Math.abs( a - b ); } public TPoint centroid() { double cx = ( points[0].getX() + points[1].getX() + points[2].getX() ) / 3d; double cy = ( points[0].getY() + points[1].getY() + points[2].getY() ) / 3d; return new TPoint( cx, cy ); } /** * Get the neighbor that share this edge * * @param constrainedEdge * @return index of the shared edge or -1 if edge isn't shared */ public int edgeIndex( TriangulationPoint p1, TriangulationPoint p2 ) { if( points[0] == p1 ) { if( points[1] == p2 ) { return 2; } else if( points[2] == p2 ) { return 1; } } else if( points[1] == p1 ) { if( points[2] == p2 ) { return 0; } else if( points[0] == p2 ) { return 2; } } else if( points[2] == p1 ) { if( points[0] == p2 ) { return 1; } else if( points[1] == p2 ) { return 0; } } return -1; } public boolean getConstrainedEdgeCCW( TriangulationPoint p ) { if( p == points[0] ) { return cEdge[2]; } else if( p == points[1] ) { return cEdge[0]; } return cEdge[1]; } public boolean getConstrainedEdgeCW( TriangulationPoint p ) { if( p == points[0] ) { return cEdge[1]; } else if( p == points[1] ) { return cEdge[2]; } return cEdge[0]; } public boolean getConstrainedEdgeAcross( TriangulationPoint p ) { if( p == points[0] ) { return cEdge[0]; } else if( p == points[1] ) { return cEdge[1]; } return cEdge[2]; } public void setConstrainedEdgeCCW( TriangulationPoint p, boolean ce ) { if( p == points[0] ) { cEdge[2] = ce; } else if( p == points[1] ) { cEdge[0] = ce; } else { cEdge[1] = ce; } } public void setConstrainedEdgeCW( TriangulationPoint p, boolean ce ) { if( p == points[0] ) { cEdge[1] = ce; } else if( p == points[1] ) { cEdge[2] = ce; } else { cEdge[0] = ce; } } public void setConstrainedEdgeAcross( TriangulationPoint p, boolean ce ) { if( p == points[0] ) { cEdge[0] = ce; } else if( p == points[1] ) { cEdge[1] = ce; } else { cEdge[2] = ce; } } public boolean getDelunayEdgeCCW( TriangulationPoint p ) { if( p == points[0] ) { return dEdge[2]; } else if( p == points[1] ) { return dEdge[0]; } return dEdge[1]; } public boolean getDelunayEdgeCW( TriangulationPoint p ) { if( p == points[0] ) { return dEdge[1]; } else if( p == points[1] ) { return dEdge[2]; } return dEdge[0]; } public boolean getDelunayEdgeAcross( TriangulationPoint p ) { if( p == points[0] ) { return dEdge[0]; } else if( p == points[1] ) { return dEdge[1]; } return dEdge[2]; } public void setDelunayEdgeCCW( TriangulationPoint p, boolean e ) { if( p == points[0] ) { dEdge[2] = e; } else if( p == points[1] ) { dEdge[0] = e; } else { dEdge[1] = e; } } public void setDelunayEdgeCW( TriangulationPoint p, boolean e ) { if( p == points[0] ) { dEdge[1] = e; } else if( p == points[1] ) { dEdge[2] = e; } else { dEdge[0] = e; } } public void setDelunayEdgeAcross( TriangulationPoint p, boolean e ) { if( p == points[0] ) { dEdge[0] = e; } else if( p == points[1] ) { dEdge[1] = e; } else { dEdge[2] = e; } } public void clearDelunayEdges() { dEdge[0] = false; dEdge[1] = false; dEdge[2] = false; } public boolean isInterior() { return interior; } public void isInterior( boolean b ) { interior = b; } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation.delaunay.sweep; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.delaunay.DelaunayTriangle; public class AdvancingFrontNode { protected AdvancingFrontNode next = null; protected AdvancingFrontNode prev = null; protected final Double key; // XXX: BST protected final double value; protected final TriangulationPoint point; protected DelaunayTriangle triangle; public AdvancingFrontNode( TriangulationPoint point ) { this.point = point; value = point.getX(); key = Double.valueOf( value ); // XXX: BST } public AdvancingFrontNode getNext() { return next; } public AdvancingFrontNode getPrevious() { return prev; } public TriangulationPoint getPoint() { return point; } public DelaunayTriangle getTriangle() { return triangle; } public boolean hasNext() { return next != null; } public boolean hasPrevious() { return prev != null; } }
Java
package org.poly2tri.triangulation.delaunay.sweep; import org.poly2tri.triangulation.TriangulationContext; import org.poly2tri.triangulation.TriangulationDebugContext; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.delaunay.DelaunayTriangle; public class DTSweepDebugContext extends TriangulationDebugContext { /* * Fields used for visual representation of current triangulation */ protected DelaunayTriangle _primaryTriangle; protected DelaunayTriangle _secondaryTriangle; protected TriangulationPoint _activePoint; protected AdvancingFrontNode _activeNode; protected DTSweepConstraint _activeConstraint; public DTSweepDebugContext( DTSweepContext tcx ) { super( tcx ); } public boolean isDebugContext() { return true; } // private Tuple2<TPoint,Double> m_circumCircle = new Tuple2<TPoint,Double>( new TPoint(), new Double(0) ); // public Tuple2<TPoint,Double> getCircumCircle() { return m_circumCircle; } public DelaunayTriangle getPrimaryTriangle() { return _primaryTriangle; } public DelaunayTriangle getSecondaryTriangle() { return _secondaryTriangle; } public AdvancingFrontNode getActiveNode() { return _activeNode; } public DTSweepConstraint getActiveConstraint() { return _activeConstraint; } public TriangulationPoint getActivePoint() { return _activePoint; } public void setPrimaryTriangle( DelaunayTriangle triangle ) { _primaryTriangle = triangle; _tcx.update("setPrimaryTriangle"); } public void setSecondaryTriangle( DelaunayTriangle triangle ) { _secondaryTriangle = triangle; _tcx.update("setSecondaryTriangle"); } public void setActivePoint( TriangulationPoint point ) { _activePoint = point; } public void setActiveConstraint( DTSweepConstraint e ) { _activeConstraint = e; _tcx.update("setWorkingSegment"); } public void setActiveNode( AdvancingFrontNode node ) { _activeNode = node; _tcx.update("setWorkingNode"); } @Override public void clear() { _primaryTriangle = null; _secondaryTriangle = null; _activePoint = null; _activeNode = null; _activeConstraint = null; } // public void setWorkingCircumCircle( TPoint point, TPoint point2, TPoint point3 ) // { // double dx,dy; // // CircleXY.circumCenter( point, point2, point3, m_circumCircle.a ); // dx = m_circumCircle.a.getX()-point.getX(); // dy = m_circumCircle.a.getY()-point.getY(); // m_circumCircle.b = Double.valueOf( Math.sqrt( dx*dx + dy*dy ) ); // // } }
Java
package org.poly2tri.triangulation.delaunay.sweep; import java.util.Comparator; import org.poly2tri.triangulation.TriangulationPoint; public class DTSweepPointComparator implements Comparator<TriangulationPoint> { public int compare( TriangulationPoint p1, TriangulationPoint p2 ) { if(p1.getY() < p2.getY() ) { return -1; } else if( p1.getY() > p2.getY()) { return 1; } else { if(p1.getX() < p2.getX()) { return -1; } else if( p1.getX() > p2.getX() ) { return 1; } else { return 0; } } } }
Java
package org.poly2tri.triangulation.delaunay.sweep; public class PointOnEdgeException extends RuntimeException { /** * */ private static final long serialVersionUID = 1L; public PointOnEdgeException( String msg ) { super(msg); } }
Java
package org.poly2tri.triangulation.delaunay.sweep; public class AdvancingFrontIndex<A> { double _min,_max; IndexNode<A> _root; public AdvancingFrontIndex( double min, double max, int depth ) { if( depth > 5 ) depth = 5; _root = createIndex( depth ); } private IndexNode<A> createIndex( int n ) { IndexNode<A> node = null; if( n > 0 ) { node = new IndexNode<A>(); node.bigger = createIndex( n-1 ); node.smaller = createIndex( n-1 ); } return node; } public A fetchAndRemoveIndex( A key ) { return null; } public A fetchAndInsertIndex( A key ) { return null; } class IndexNode<A> { A value; IndexNode<A> smaller; IndexNode<A> bigger; double range; } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation; public enum TriangulationAlgorithm { DTSweep }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation; public enum TriangulationProcessEvent { Started,Waiting,Failed,Aborted,Done }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation.sets; import java.util.ArrayList; import java.util.List; import org.poly2tri.triangulation.Triangulatable; import org.poly2tri.triangulation.TriangulationContext; import org.poly2tri.triangulation.TriangulationMode; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.delaunay.DelaunayTriangle; public class PointSet implements Triangulatable { List<TriangulationPoint> _points; List<DelaunayTriangle> _triangles; public PointSet( List<TriangulationPoint> points ) { _points = new ArrayList<TriangulationPoint>(); _points.addAll( points ); } public TriangulationMode getTriangulationMode() { return TriangulationMode.UNCONSTRAINED; } public List<TriangulationPoint> getPoints() { return _points; } public List<DelaunayTriangle> getTriangles() { return _triangles; } public void addTriangle( DelaunayTriangle t ) { _triangles.add( t ); } public void addTriangles( List<DelaunayTriangle> list ) { _triangles.addAll( list ); } public void clearTriangulation() { _triangles.clear(); } public void prepareTriangulation( TriangulationContext<?> tcx ) { if( _triangles == null ) { _triangles = new ArrayList<DelaunayTriangle>( _points.size() ); } else { _triangles.clear(); } tcx.addPoints( _points ); } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation.util; public class Tuple2<A,B> { public A a; public B b; public Tuple2(A a,B b) { this.a = a; this.b = b; } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation.util; public class Tuple3<A,B,C> { public A a; public B b; public C c; public Tuple3(A a,B b,C c) { this.a = a; this.b = b; this.c = c; } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation.util; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.geometry.polygon.PolygonPoint; public class PolygonGenerator { private static final double PI_2 = 2.0*Math.PI; public static Polygon RandomCircleSweep( double scale, int vertexCount ) { PolygonPoint point; PolygonPoint[] points; double radius = scale/4; points = new PolygonPoint[vertexCount]; for(int i=0; i<vertexCount; i++) { do { if( i%250 == 0 ) { radius += scale/2*(0.5 - Math.random()); } else if( i%50 == 0 ) { radius += scale/5*(0.5 - Math.random()); } else { radius += 25*scale/vertexCount*(0.5 - Math.random()); } radius = radius > scale/2 ? scale/2 : radius; radius = radius < scale/10 ? scale/10 : radius; } while( radius < scale/10 || radius > scale/2 ); point = new PolygonPoint( radius*Math.cos( (PI_2*i)/vertexCount ), radius*Math.sin( (PI_2*i)/vertexCount ) ); points[i] = point; } return new Polygon( points ); } public static Polygon RandomCircleSweep2( double scale, int vertexCount ) { PolygonPoint point; PolygonPoint[] points; double radius = scale/4; points = new PolygonPoint[vertexCount]; for(int i=0; i<vertexCount; i++) { do { radius += scale/5*(0.5 - Math.random()); radius = radius > scale/2 ? scale/2 : radius; radius = radius < scale/10 ? scale/10 : radius; } while( radius < scale/10 || radius > scale/2 ); point = new PolygonPoint( radius*Math.cos( (PI_2*i)/vertexCount ), radius*Math.sin( (PI_2*i)/vertexCount ) ); points[i] = point; } return new Polygon( points ); } }
Java
package org.poly2tri.triangulation.util; import java.util.ArrayList; import java.util.List; import org.poly2tri.triangulation.TriangulationPoint; import org.poly2tri.triangulation.point.TPoint; public class PointGenerator { public static List<TriangulationPoint> uniformDistribution( int n, double scale ) { ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(); for( int i=0; i<n; i++ ) { points.add( new TPoint( scale*(0.5 - Math.random()), scale*(0.5 - Math.random()) ) ); } return points; } public static List<TriangulationPoint> uniformGrid( int n, double scale ) { double x=0; double size = scale/n; double halfScale = 0.5*scale; ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(); for( int i=0; i<n+1; i++ ) { x = halfScale - i*size; for( int j=0; j<n+1; j++ ) { points.add( new TPoint( x, halfScale - j*size ) ); } } return points; } }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri.triangulation; public interface TriangulationProcessListener { public void triangulationEvent( TriangulationProcessEvent e, Triangulatable unit ); }
Java
package org.poly2tri.transform.coordinate; /** * A transform that aligns the XY plane normal [0,0,1] with any given target normal * * http://www.cs.brown.edu/~jfh/papers/Moller-EBA-1999/paper.pdf * * @author thahlen@gmail.com * */ public class XYToAnyTransform extends Matrix3Transform { /** * Assumes target normal is normalized */ public XYToAnyTransform( double nx, double ny, double nz ) { setTargetNormal( nx, ny, nz ); } /** * Assumes target normal is normalized * * @param nx * @param ny * @param nz */ public void setTargetNormal( double nx, double ny, double nz ) { double h,f,c,vx,vy,hvx; vx = ny; vy = -nx; c = nz; h = (1-c)/(1-c*c); hvx = h*vx; f = (c < 0) ? -c : c; if( f < 1.0 - 1.0E-4 ) { m00=c + hvx*vx; m01=hvx*vy; m02=-vy; m10=hvx*vy; m11=c + h*vy*vy; m12=vx; m20=vy; m21=-vx; m22=c; } else { // if "from" and "to" vectors are nearly parallel m00=1; m01=0; m02=0; m10=0; m11=1; m12=0; m20=0; m21=0; if( c > 0 ) { m22=1; } else { m22=-1; } } } }
Java
package org.poly2tri.transform.coordinate; import java.util.List; import org.poly2tri.geometry.primitives.Point; public class NoTransform implements CoordinateTransform { public void transform( Point p, Point store ) { store.set( p.getX(), p.getY(), p.getZ() ); } public void transform( Point p ) { } public void transform( List<? extends Point> list ) { } }
Java
package org.poly2tri.transform.coordinate; /** * A transform that aligns given source normal with the XY plane normal [0,0,1] * * @author thahlen@gmail.com */ public class AnyToXYTransform extends Matrix3Transform { /** * Assumes source normal is normalized */ public AnyToXYTransform( double nx, double ny, double nz ) { setSourceNormal( nx, ny, nz ); } /** * Assumes source normal is normalized * * @param nx * @param ny * @param nz */ public void setSourceNormal( double nx, double ny, double nz ) { double h,f,c,vx,vy,hvx; vx = -ny; vy = nx; c = nz; h = (1-c)/(1-c*c); hvx = h*vx; f = (c < 0) ? -c : c; if( f < 1.0 - 1.0E-4 ) { m00=c + hvx*vx; m01=hvx*vy; m02=-vy; m10=hvx*vy; m11=c + h*vy*vy; m12=vx; m20=vy; m21=-vx; m22=c; } else { // if "from" and "to" vectors are nearly parallel m00=1; m01=0; m02=0; m10=0; m11=1; m12=0; m20=0; m21=0; if( c > 0 ) { m22=1; } else { m22=-1; } } } }
Java
package org.poly2tri.transform.coordinate; import java.util.List; import org.poly2tri.geometry.primitives.Point; public abstract class Matrix3Transform implements CoordinateTransform { protected double m00,m01,m02,m10,m11,m12,m20,m21,m22; public void transform( Point p, Point store ) { final double px = p.getX(); final double py = p.getY(); final double pz = p.getZ(); store.set(m00 * px + m01 * py + m02 * pz, m10 * px + m11 * py + m12 * pz, m20 * px + m21 * py + m22 * pz ); } public void transform( Point p ) { final double px = p.getX(); final double py = p.getY(); final double pz = p.getZ(); p.set(m00 * px + m01 * py + m02 * pz, m10 * px + m11 * py + m12 * pz, m20 * px + m21 * py + m22 * pz ); } public void transform( List<? extends Point> list ) { for( Point p : list ) { transform( p ); } } }
Java
package org.poly2tri.transform.coordinate; import java.util.List; import org.poly2tri.geometry.primitives.Point; public abstract interface CoordinateTransform { public abstract void transform( Point p, Point store ); public abstract void transform( Point p ); public abstract void transform( List<? extends Point> list ); }
Java
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.poly2tri; import org.poly2tri.geometry.polygon.Polygon; import org.poly2tri.geometry.polygon.PolygonSet; import org.poly2tri.triangulation.Triangulatable; import org.poly2tri.triangulation.TriangulationAlgorithm; import org.poly2tri.triangulation.TriangulationContext; import org.poly2tri.triangulation.TriangulationMode; import org.poly2tri.triangulation.TriangulationProcess; import org.poly2tri.triangulation.delaunay.sweep.DTSweep; import org.poly2tri.triangulation.delaunay.sweep.DTSweepContext; import org.poly2tri.triangulation.sets.ConstrainedPointSet; import org.poly2tri.triangulation.sets.PointSet; import org.poly2tri.triangulation.util.PolygonGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Poly2Tri { private final static Logger logger = LoggerFactory.getLogger( Poly2Tri.class ); private static final TriangulationAlgorithm _defaultAlgorithm = TriangulationAlgorithm.DTSweep; public static void triangulate( PolygonSet ps ) { TriangulationContext<?> tcx = createContext( _defaultAlgorithm ); for( Polygon p : ps.getPolygons() ) { tcx.prepareTriangulation( p ); triangulate( tcx ); tcx.clear(); } } public static void triangulate( Polygon p ) { triangulate( _defaultAlgorithm, p ); } public static void triangulate( ConstrainedPointSet cps ) { triangulate( _defaultAlgorithm, cps ); } public static void triangulate( PointSet ps ) { triangulate( _defaultAlgorithm, ps ); } public static TriangulationContext<?> createContext( TriangulationAlgorithm algorithm ) { switch( algorithm ) { case DTSweep: default: return new DTSweepContext(); } } public static void triangulate( TriangulationAlgorithm algorithm, Triangulatable t ) { TriangulationContext<?> tcx; // long time = System.nanoTime(); tcx = createContext( algorithm ); tcx.prepareTriangulation( t ); triangulate( tcx ); // logger.info( "Triangulation of {} points [{}ms]", tcx.getPoints().size(), ( System.nanoTime() - time ) / 1e6 ); } public static void triangulate( TriangulationContext<?> tcx ) { switch( tcx.algorithm() ) { case DTSweep: default: DTSweep.triangulate( (DTSweepContext)tcx ); } } /** * Will do a warmup run to let the JVM optimize the triangulation code */ public static void warmup() { /* * After a method is run 10000 times, the Hotspot compiler will compile * it into native code. Periodically, the Hotspot compiler may recompile * the method. After an unspecified amount of time, then the compilation * system should become quiet. */ Polygon poly = PolygonGenerator.RandomCircleSweep2( 50, 50000 ); TriangulationProcess process = new TriangulationProcess(); process.triangulate( poly ); } }
Java
package aplicacao; import controle.Constantes; import gui.FramePrincipal; public class Executa { public static void main(String[] args) { FramePrincipal jogo = new FramePrincipal(); jogo.iniciarJogo(); } }
Java
package algoritmo; import java.awt.Point; public class Constantes { public static final int PARADO = 0; public static final int CIMA = 1; public static final int BAIXO = 2; public static final int DIREITA = 3; public static final int ESQUERDA = 4; public static final int VISAO_CIMA = 7; public static final int VISAO_BAIXO = 16; public static final int VISAO_ESQUERDA = 11; public static final int VISAO_DIREITA = 12; public static final int VISAO_SEMVISAO = -2; public static final int VISAO_DESCONHECIDO = -3; public static final int VISAO_INATINGIVEL = -4; public static final int VISAO_VAZIO = 0; public static final int VISAO_EXTERNO = -1; public static final int VISAO_PAREDE = 1; public static final int VISAO_BANCO = 3; public static final int VISAO_MOEDA = 4; public static final int VISAO_PASTILHA = 5; public static final int[] VISAO_LADRAO = { 200, 210, 220, 230 }; public static final int[] VISAO_POUPADOR = { 100, 110 }; public static final int CHEIRO_TAMLEMBRANCA = 11; /** * At� quantas rodadas lembramos do cheiro */ public static final int CHEIRO_CHEIROLIMITE = 5; public static final int CHEIRO_SEMCHEIRO = 0; public static final int LEMBRANCA_LIMITE_LADRAO = 4; public static final int LEMBRANCA_LIMITE_POUPADOR = 2; // cuidado, nao aumentar esse valor alem do campo de visao (2) public static final int LEMBRANCA_LIMITE_INATINGIVEL = 20; /** * Qual número máximo de loops que devemos esperar antes de sair correndo sem pensar em mais nada. */ public static final int HISTORICO_LOOP_MAX = 3; /** * Número de rodadas que vamos pensar que somos como o Chuck Noris - isto é, ngm pode com a gente. * Basicamente isso será usado quando precisamos fingir que não podemos ser roubados porque ficamos encurralados * pelo ladrão em um loop. */ public static final int CHUCK_NORIS_TICKS = 5; /** * Menor distancia de manhattan aceitavel do ladrao */ public static final int MIN_DIST_LADRAO = 2; /** * Numero de ticks que devemos esperar antes de começar o berserk, isso eh, sair pegando moedas desenfreadamente! * Se queremos berserk após jogar 100 turnos, entao 100 eh o valor a colocar aqui! */ public static final int THIS_IS_SPARTAAAAAA = 650; /** * Quantas moedas precisamos para estarmos ricos */ public static final int RICO = 20; public static final int MUNDO_TAM = 30; public static final int HISTORICO_POSICAO_LEN = 80; public static final int BUSCA_PROFUNDIDADE = 6; /* * Retorna true se a célula possui um ladrão. */ public static boolean contemLadrao(int valorCelula) { for (int i = 0; i < VISAO_LADRAO.length; i++) if(VISAO_LADRAO[i] == valorCelula) return true; return false; } /* * Retorna true se a célula possui um popuador. */ public static boolean contemPupador(int valorCelula) { for (int i = 0; i < VISAO_POUPADOR.length; i++) if(VISAO_POUPADOR[i] == valorCelula) return true; return false; } public static int manhattan(Point a, Point b) { return Math.abs(a.x - b.x) + Math.abs(a.y - b.y); } /** * Retorna true se o ponto eh valido */ public static boolean isValidPoint(Point p, int numeroMoedas, int[][] mundo) { // se pontos estao fora do mundo sao automaticamente invalidos if (p.x < 0 || p.y < 0 || p.x >= Constantes.MUNDO_TAM || p.y >= Constantes.MUNDO_TAM) return false; int val = mundo[p.y][p.x]; // ponto eh valido se nao eh uma parede, mundo externo ou se o ladrao estah nele return val != Constantes.VISAO_PAREDE && val != Constantes.VISAO_EXTERNO && val != Constantes.VISAO_BANCO && val != Constantes.VISAO_INATINGIVEL && ( val != Constantes.VISAO_PASTILHA // pastilhas sao validas apens se tivermos mais de 5 moedas || numeroMoedas >= 5 ) && !Constantes.contemPupador(val) && !Constantes.contemLadrao(val); } /** * Verifica se um dado quadro a uma certa distância da nossa posição é seguro. * @param numeroMoedas Número de moedas que temos * @param distanciaMovimento Distância da minha posição até o quadro analisado. * @param distanciaLadrao Distância do ladrão até a posição analisada. * @return TRUE se podemos ir para o quadro sem que haja chance de sermos roubados */ public static boolean distanciaSegura(int numeroMoedas, int distanciaMovimento, int distanciaLadrao) { // apenas queremos uma distancia segura se tivermos moedas if (numeroMoedas > 0) { int diffDistancia = distanciaLadrao - distanciaMovimento; // se o ladrao conseguir chegar um quadro antes do analisado // ou no proprio quadro antes da gente, entao precisamos // evitamos caminho if (diffDistancia <= 1) { // nao eh uma posicao boa, ir para lá significa ser roubado! return false; } } return true; } /* * Retorna qual acao tomar para ir da posicao atual a posicao destino. * Esse método decide de forma simples para onde ir. Idealmente deve-se ter posicaoDestino e atual contiguas * Nao eh aplicada qualquer logica de caminho */ public static int tomarAcao(Point pos, Point proximoQuadro) { int acao; //tentamos ir o destino if (proximoQuadro.x > pos.x) acao = Constantes.DIREITA; else if (proximoQuadro.x < pos.x) acao = Constantes.ESQUERDA; else if (proximoQuadro.y > pos.y) acao = Constantes.BAIXO; else if (proximoQuadro.y < pos.y) acao = Constantes.CIMA; else acao = Constantes.PARADO; return acao; } }
Java
package algoritmo; public class Acao { public double valor; public int acao; public boolean valida; public Acao(int acao, double valor, boolean valida) { this.acao = acao; this.valor = valor; this.valida = valida; } }
Java
package algoritmo; import java.awt.Point; import java.util.LinkedList; /** * A* pathfinding. * Encontra um caminho at� um destino a partir de uma origem. O caminho ser� m�nimo e v�lido. * Se o destino for inv�lido, essa classe pode causar uma excess�o n�o controlada. */ public class PathFinding { private class PfPoint implements Comparable { public Point p; public PfPoint parent; /* * Custo da origem at� aqui */ public int value; public int estimative; public PfPoint(Point p, int value, PfPoint parent, Point destiny) { this.p = p; this.value = value; this.parent = parent; this.estimative = estimate(destiny); } /* * Estima custo at� o destino. */ private int estimate(Point destiny) { return Constantes.manhattan(destiny, p); } @Override public boolean equals(Object that) { if (this == that) return true; if ( !(that instanceof PfPoint) ) return false; // sao iguais se pontos forem iguais return p.equals(((PfPoint)that).p); } @Override public int compareTo(Object that) { if ( !(that instanceof PfPoint) ) return -1; PfPoint o = (PfPoint)that; int myVal = value + estimative; int hisVal = o.value + o.estimative; if (myVal > hisVal) return 1; else if (myVal < hisVal) return -1; return 0; } @Override public int hashCode() { return Constantes.MUNDO_TAM * p.x + p.y; } } private int[][] mundo; private BinaryHeap openList; private boolean[] closedList; private Point origin; private Point destiny; private PfPoint pfDestiny; private Point nextPointToGo; private boolean caminhoBuscado; private int numeroMoedas; private Poupador agente; public PathFinding(Poupador agente, int[][] mundo, Point origin, Point destiny) { this.mundo = mundo; this.origin = origin; this.destiny = destiny; this.pfDestiny = null; this.caminhoBuscado = false; this.numeroMoedas = agente.sensor.getNumeroDeMoedas(); this.agente = agente; openList = new BinaryHeap(Constantes.MUNDO_TAM * 4, true); closedList = new boolean[Constantes.MUNDO_TAM * Constantes.MUNDO_TAM]; for(int i = 0; i < closedList.length; i++) closedList[i] = false; } private PfPoint isOpen(PfPoint p) { return (PfPoint)openList.get(p); } private void addOpenPoint(PfPoint p) { openList.add(p); } /** * Informa se um ponto eh valido e se existe algum custo adicional para se mover para aquele ponto dependendo da situação. * @param pos * @param custoAdicionalMovimento * @return */ private boolean isValidPoint(Point pos, Holder<Integer> custoAdicionalMovimento) { boolean valido = Constantes.isValidPoint(pos, numeroMoedas, mundo); custoAdicionalMovimento.value = 0; // por padrao, não há custo adicional para se mover if (valido) { int valorCelula = mundo[pos.y][pos.x]; Holder<Integer> distanciaLadrao = new Holder<Integer>(0); Point posLadrao = agente.ladraoMaisProximo(pos, distanciaLadrao); switch(valorCelula) { // pastilhas sao caras, evitamos pegá-las a nao ser q hajam ladroes proximos case Constantes.VISAO_PASTILHA: valido = posLadrao != null && distanciaLadrao.value < 4; break; } // aqui consideramos desviar e evitar caminhos com ladroes // vamos considerar apenas caminhos validos e se tivermos moeda (pois c.c. nao vale a pena desviar) if (numeroMoedas > 0) { // devemos evitar ir para quadros que nos deixem perigosamente proximos dos ladroes // nao devemos evitar quadros muito distantes da nossa posição inicial pois isso poderia // impedir que alguns caminhos fossem completados (ainda nao sei o quão bom é isso) // TODO: // considerar caminhos não completados - ex. se vamos ao banco e há ladrões próximos do banco // e evitamos caminhos proximos a ladroes, entao possivelmente nao encontraremos um caminho até o // banco, mas isso pode ser bom pois tentaremos fazer outra coisa, contudo podemos estar suficientemente // longo do banco para que ao chegarmos mais próximo dele, os ladrões tenham ido fazer outra coisa int distMovimento = Constantes.manhattan(pos, origin); // apenas vamos considerar pontos inseguros na região do nosso campo de visão // além disso é pura especulação if (distMovimento < 6) { int distDiff; // apenas vamos verificar se eh seguro, se existir ladrao proximo e se estiver suficientemente proximo // para nos ameacar if (posLadrao != null && ((distDiff = distMovimento - distanciaLadrao.value)) > -Constantes.MIN_DIST_LADRAO) { // aumentamos o custo proporcionalmente a quão provavel eh um roubo naquele quadro custoAdicionalMovimento.value += 100 * (Constantes.MIN_DIST_LADRAO + distDiff); } } } } return valido; } /** * Adiciona ponto a openList. * Se jah existir l�, ent�o faz atualiza��es do caminho de acordo. */ private void openPoint(PfPoint p) { Holder<Integer> custoAdicional = new Holder<Integer>(0); // se ponto nao eh valido ou estah na lista de fechados, nao fa�a nada if (!isValidPoint(p.p, custoAdicional) || isClosed(p)) return; // adicionamos o custo adicional de movimento p.value += custoAdicional.value; PfPoint pInList = isOpen(p); // se ponto nao existe, apenas o adicionamos na lista if (pInList == null) addOpenPoint(p); else { // se encontramos uma forma melhor de atingir o ponto p // entao atualizamos essa forma if (pInList.value > p.value) { pInList.value = p.value; pInList.parent = p.parent; } } } private boolean isClosed(PfPoint p) { return closedList[p.hashCode()]; } /** * Fecha ponto e indica se ponto fechado eh o destino */ private void closePoint(PfPoint p) { if (!isClosed(p)) closedList[p.hashCode()] = true; } /* * Olha pontos em vonta de p e os coloca na openList, incluindo p */ private void lookAround(PfPoint p) { // o custo de ir de p a algum outro ponto � 1 int value = p.value + 1; // cima Point np = new Point(p.p.x, p.p.y - 1); openPoint(new PfPoint(np, value, p, destiny)); // baixo np = new Point(p.p.x, p.p.y + 1); openPoint(new PfPoint(np, value, p, destiny)); // esquerda np = new Point(p.p.x - 1, p.p.y); openPoint(new PfPoint(np, value, p, destiny)); // direita np = new Point(p.p.x + 1, p.p.y); openPoint(new PfPoint(np, value, p, destiny)); } /* * Retorna ponto de menor custo na lista de abertos e o retira da lista. */ private PfPoint popLowestCostPoint() { PfPoint min = null; min = (PfPoint)openList.pop(); return min; } /* * Acha o caminho */ private void findPath() { // informa q jah foi feita busca pelo caminho caminhoBuscado = true; if (origin.equals(destiny)) return; // custo da origem eh 0 e nao tem pai PfPoint pfOrigin = new PfPoint(origin, 0, null, destiny); // adiciona pontos proximos a origem na lista de abertos lookAround(pfOrigin); // entao fecha origem closePoint(pfOrigin); PfPoint p; // enquanto tivermos pontos a olhar // pega ponto de menor custo e o remove da lista (getLowestCostPoint faz isso) while ( ( p = popLowestCostPoint() ) != null ) { // se p for igual ao destino, podemos parar if (p.p.equals(destiny)) { this.pfDestiny = p; break; } // fecha ponto de menor custo closePoint(p); // olha em vonta do ponto de menor custo lookAround(p); } // se ha caminho, entao ponto de destino foi preenchido if (pfDestiny != null) { p = pfDestiny; // se jah estamos onde queremos ir, nao temos o q fazer if (origin.equals(pfDestiny.p)) { nextPointToGo = null; } else { // procura ponto antes da origem while (p.parent.parent != null) p = p.parent; // proximo ponto a ir eh aquele q vem depois da origem (origem tem pai nulo) nextPointToGo = p.p; // descartamos origem p.parent = null; } } } /* * Retorna proximo ponto do caminho */ public Point findNextPoint() { if (!caminhoBuscado) findPath(); // jah sabemos para onde ir Point ret = nextPointToGo; // vamos deixar proximo preparado // TODO: nao implementado return ret; } /** * Realiza busca de caminho ótimo até o ponto de destino, retornando a acao a ser tomada. * @param agente * @param mundo * @param posicaoAtual * @param destino * @return */ public static int tomarMelhorDecisao(Poupador agente, int[][] mundo, Point posicaoAtual, Point destino) { int acao; PathFinding pf = new PathFinding(agente, mundo, posicaoAtual, destino); Point proximoQuadro = pf.findNextPoint(); if (proximoQuadro != null) { acao = Constantes.tomarAcao(posicaoAtual, proximoQuadro); } else acao = Constantes.PARADO; return acao; } }
Java
package algoritmo; import java.awt.Point; public class Lembranca { public int tempo; public int valor; public Point posicao; public Lembranca(Point posicao, int valor) { this.tempo = 0; this.posicao = new Point(posicao); this.valor = valor; } }
Java
package algoritmo; import java.awt.Point; import java.util.LinkedList; import java.util.ListIterator; /** * TODO: * * Verificar se cheiros funcionam * * Estimar posição de ladrões cheirados * * * Estamos sujeitos a emboscadas. Se ladrao está fora do campo de visão, mas dentro da área de ameaça * (ex. ladrao está atrás de um mudo, não podemos vê-lo, mas logo que passarmos pelo muro ele nos verá e não teremos * chance de fugir - imagine ele atrás da porta e a gente entrando no quarto). * * * * Implementar classes de comportamentos com prioridades * * Guardar moedas no banco quando ficar rico * * Implementar pathfinding para ladrão - fazer caminho mais curto que o ladrão possa para nos pegar * considerando q ele nao pode pegar moedas ou pastilhas, isso pode ajudar em alguns casos evitando * fugir por besteira * * * PROBLEMAS: * * PROBLEMA MUITO GRANDE::: as vezes o pathfind troca o caminho com a variação de personagens móveis, o que faz com que * o bixo entre em loop (nao em codigo, mas no jogo, fique andando nas mesmas posicoes), em geral isso acontece porque * o outro bixo já está em loop!!!! * * O problema acima se dá em vários casos. Um deles é quando queremos ir para o desconhecido mais proximo. Pegamos o mais proximo * pela dist de manhattan, sem considerar barreiras, contudo esse ponto na verdade, devido às barreiras, pode demorar mais para chegarmos * entao enquanto nos movemos para ir para tal ponto, acabamos nos aproximando de outro ponto desconhecido que agora tem a menor dist de manhattan * a partir dai, trocamos o destino e num caso ruim, ficando alternando entre tais pontos. * * - qndo nao tiver o q fazer vá para local com maior área livre (menor número de paredes) * dividir mapa em regioes e calcular densidade de paredes, ir para aquela regiao com menor densisdade * * COMPLETE: * * * Comportamentos: * * Guardar no banco qndo interessante * * Pegar / evitar pegar pipula qndo interessante * * Fugir ladr�o * * Descobrir mundo * * Descobrir mundo e moedas e banco * * Melhor roda para pegar moedas * * PARTIAL: * * * IGNORED: * * Banco mais proximo deve considerar densidade de ladrões próximos a ele (acho q nao vai ter mais q um banco) * * */ public class Poupador extends ProgramaPoupador { // armazena estados conhecidos do mundo --- linha -> y; coluna -> x; private int[][] mundo; /** * Mundo de cheiros possui o tamanho suficiente para manter cheiros mais fracos (mais o meu quadro) */ private int[][] cheiro; private int tick; // tick atual private LinkedList<Point> ultimasPosicoes; private LinkedList<Point> bancos; private LinkedList<Lembranca> ladroes; private LinkedList<Lembranca> poupadores; private LinkedList<Lembranca> locaisInatingiveis; private Point pontoDesconhecidoProximo; /** * Tempo que vamos dedicar para fugir de loops; */ private int tempoEvitandoLoop; private Point destinoEvitarLoop; /** * Nao use essa variavel direitamente. Se vc quer o nro total de jogadas imunes, utilize getNumeroJogasImunes(). * Essa variavel representa o nro de jogadas que podemos desprezar a fuga (para evitar loops) */ private int numeroJogadasImunesInternas; public int getNumeroJogasImunes() { return sensor.getNumeroJogadasImunes() + numeroJogadasImunesInternas; } public Poupador() { super(); inicializaMundo(); ultimasPosicoes = new LinkedList<Point>(); bancos = new LinkedList<Point>(); locaisInatingiveis = new LinkedList<Lembranca>(); ladroes = new LinkedList<Lembranca>(); poupadores = new LinkedList<Lembranca>(); pontoDesconhecidoProximo = null; numeroJogadasImunesInternas = 0; tempoEvitandoLoop = 0; tick = 0; destinoEvitarLoop = null; } // retorna posicao de forma segura private Point getPos() { return (Point)sensor.getPosicao(); } private void lembraLadrao() { lembra(ladroes, Constantes.LEMBRANCA_LIMITE_LADRAO, Constantes.VISAO_VAZIO); } private void lembraPoupador() { lembra(poupadores, Constantes.LEMBRANCA_LIMITE_POUPADOR, Constantes.VISAO_VAZIO); } /** * Esquece que alguns locais eram inatingiveis com o passar do tempo * Isso faz que com voltemos lá para tentar acessá-los novamente. Pode ser q um ladrão ficou no meio do caminho * e não quis deixar a gente entrar no local. */ private void lembrarLocalInatingivel() { lembra(locaisInatingiveis, Constantes.LEMBRANCA_LIMITE_INATINGIVEL, Constantes.VISAO_DESCONHECIDO); } private void lembra(LinkedList<Lembranca> lista, int tempoLimite, int valorLembrancaApagada) { ListIterator<Lembranca> list = lista.listIterator(); Lembranca l; while (list.hasNext()) { l = list.next(); // vimos a lembranca ha mto tempo, tire-a da lista if (++l.tempo > tempoLimite) { list.remove(); // temos que apagar o mundo também apagaLembranca(l, valorLembrancaApagada); } } } private void ignorarLocalInatingivel(Point localInatingivel) { // atualiza mundo mundo[localInatingivel.y][localInatingivel.x] = Constantes.VISAO_INATINGIVEL; locaisInatingiveis.add(new Lembranca(localInatingivel, Constantes.VISAO_INATINGIVEL)); } private void novoPoupador(Point pos, int valor) { novaLembranca(pos, valor, poupadores); } private void novoLadrao(Point pos, int valor) { novaLembranca(pos, valor, ladroes); } private void apagaLembranca(Lembranca l, int novoValor) { // temos que apagar a lembranca do mundo if (mundo[l.posicao.y][l.posicao.x] == l.valor) mundo[l.posicao.y][l.posicao.x] = novoValor; } private void novaLembranca(Point pos, int valor, LinkedList<Lembranca> lista) { boolean atualizado = false; // se vimos uma lembranca, atualizamos tal lembranca na nossa lista for (Lembranca l : lista) { if (l.valor == valor) { // apaga lembranca antiga do mundo apagaLembranca(l, Constantes.VISAO_VAZIO); l.posicao.setLocation(pos); l.tempo = 0; atualizado = true; break; } } if (!atualizado) { // se nao encontramos lembranca na lista, adicionamos nova lista.add(new Lembranca(pos, valor)); } } /** * Retorna posicao de ladrao mais proximo conhecido. * Retorna NULL se nao sabemos onde estao os ladroes * @param pos * @param distancia retorna distancia do ladrao proximo * @return */ public Point ladraoMaisProximo(Point pos, Holder<Integer> distancia) { int dist; int minDist; Point minPos; minDist = Integer.MAX_VALUE; minPos = new Point(); for (Lembranca l : ladroes) { dist = Constantes.manhattan(l.posicao, pos); if (dist < minDist) { minDist = dist; minPos.setLocation(l.posicao); } } distancia.value = minDist; if (minDist == Integer.MAX_VALUE) return null; return minPos; } // inicializa mundo em estado desconhecido private void inicializaMundo() { mundo = new int[Constantes.MUNDO_TAM][Constantes.MUNDO_TAM]; // precisamos lembrar dos cheiros proximos, pq eles somem depois de qualquer forma cheiro = new int[Constantes.CHEIRO_TAMLEMBRANCA][Constantes.CHEIRO_TAMLEMBRANCA]; for (int i = 0; i < Constantes.MUNDO_TAM; i++) for (int j = 0; j < Constantes.MUNDO_TAM; j++) mundo[i][j] = Constantes.VISAO_DESCONHECIDO; for (int i = 0; i < Constantes.CHEIRO_TAMLEMBRANCA; i++) for (int j = 0; j < Constantes.CHEIRO_TAMLEMBRANCA; j++) cheiro[i][j] = Constantes.CHEIRO_SEMCHEIRO; } // descobre novas areas e atualiza informações antigas private void descobreMundo() { Point pos = getPos(); int[] visao = sensor.getVisaoIdentificacao(); int[] cheiroLadrao = sensor.getAmbienteOlfatoLadrao(); int x, y; // atualiza tick atual tick++; // atualiza jogadas internas if (numeroJogadasImunesInternas > 0) numeroJogadasImunesInternas--; if (tempoEvitandoLoop > 0) { tempoEvitandoLoop--; } else { // aqui tempoEvitandoLoop == 0 destinoEvitarLoop = null; } x = pos.x; y = pos.y; // lembramos de ladroes vistos lembraLadrao(); lembraPoupador(); lembrarLocalInatingivel(); // onde estamos está vazio (na verdade, estará qndo sairmos daqui) mundo[y][x] = Constantes.VISAO_VAZIO; // atualiza mundo visto for (int i = 0; i < visao.length; i++) { if (i == 0 || i == 5 || i == 10 || i == 14 || i == 19) { x = pos.x - 2; y = pos.y; if (i == 0) y -= 2; else if (i == 5) y -= 1; else if (i == 14) y += 1; else if (i == 19) y += 2; } // soh vamos atualizar algo se nao estivermos na posicao do personagem if (y != pos.y || x != pos.x) { // se estivermos olhando para fora dos limites do mundo, apenas prossiga sem fazer nada, nao existe nada lá fora if (y > -1 && y < Constantes.MUNDO_TAM && x > -1 && x < Constantes.MUNDO_TAM) { // apenas atualizamos o que podemos ver if (visao[i] != Constantes.VISAO_SEMVISAO) { mundo[y][x] = visao[i]; switch(visao[i]) { // guarda bancos descobertos case Constantes.VISAO_BANCO: novoBanco(new Point(x, y)); break; default: // lembra de ladroes if (Constantes.contemLadrao(visao[i])) novoLadrao(new Point(x, y), visao[i]); else if (Constantes.contemPupador(visao[i])) novoPoupador(new Point(x, y), visao[i]); break; } } } } else { // queremos apenas pular posicao x,y nao o valor em i da visao i--; } x++; } // agora que acabamos de atualizar mundo visto // eh possivel que ladroes tenham se escondido e por isso nao atulizamos eles // vamos procuprar por ladroes q nao estao mais lá e sumir com eles // TODO: apagar ladroes "invisiveis" // Nao sei se vale a pena, talvez apenas reduzir o tempo de lembrança, nao sei o qual bom isso pode fazer // em qual quadro de cheiro estamos int centroCheiro = Constantes.CHEIRO_TAMLEMBRANCA / 2; Point posAnterior = getPosicaoAnterior(); Point minhaPos = getPos(); Point variacaoPosicao = new Point(minhaPos.x - posAnterior.x, minhaPos.y - posAnterior.y); Point cheiroOrigem, cheiroDestino; cheiroDestino = new Point(); cheiroOrigem = new Point(); // se fomos para esquerda if (variacaoPosicao.x < 0) { // copiamos o da direita para o nosso cheiroDestino.x = 0; cheiroOrigem.x = 1; } // se fomos p/ direita else if (variacaoPosicao.x > 0) { // copiamos o nosso para o da direita cheiroDestino.x = 1; cheiroOrigem.x = 0; } else { // se nao andamos, nao fazemos nada pois podemos ter q mexer em y } // se fomos para cima if (variacaoPosicao.y < 0) { // copiamos o de baixo para o nosso cheiroDestino.y = 0; cheiroOrigem.y = 1; } // se fomos p/ baixo else if (variacaoPosicao.y > 0) { // copiamos o nosso para o de baixo cheiroDestino.y = 1; cheiroOrigem.y = 0; } else { // se nao andamos, nao fazemos nada } // atualiza mundo cheirado // a cada frame, precisamos transladar cheiros se andamos // e atualizar cheiros na nossa regi�o cheirada // e atualizar "data" dos cheiros for (x = 0; x < Constantes.CHEIRO_TAMLEMBRANCA; x++) { for (y = 0; y < Constantes.CHEIRO_TAMLEMBRANCA; y++) { // soh translada cheiros se estivemos nos limites adequados if (x < Constantes.CHEIRO_TAMLEMBRANCA - 1 && y < Constantes.CHEIRO_TAMLEMBRANCA - 1) cheiro[y + cheiroDestino.y][x + cheiroDestino.x] = cheiro[y + cheiroOrigem.y][x + cheiroOrigem.x]; // se ha cheiro no quadro if (cheiro[y][x] > 0) { // se o cheiro eh mto antigo, esquechemos if (cheiro[y][x] == Constantes.CHEIRO_CHEIROLIMITE) cheiro[y][x] = Constantes.CHEIRO_SEMCHEIRO; else // senao atualizamos quanto tempo ele tem cheiro[y][x]++; } } } // atualiza cheiros da regiao cheirada cheiro[centroCheiro - 1][centroCheiro - 1] = cheiroLadrao[0]; cheiro[centroCheiro - 1][centroCheiro ] = cheiroLadrao[1]; cheiro[centroCheiro - 1][centroCheiro + 1] = cheiroLadrao[2]; cheiro[centroCheiro ][centroCheiro - 1] = cheiroLadrao[3]; // cheiro[centroCheiro ][centroCheiro ] = cheiroLadrao[ESTA SERIA MINHA POSICAO CENTRAL]; cheiro[centroCheiro ][centroCheiro + 1] = cheiroLadrao[4]; cheiro[centroCheiro + 1][centroCheiro - 1] = cheiroLadrao[5]; cheiro[centroCheiro + 1][centroCheiro ] = cheiroLadrao[6]; cheiro[centroCheiro + 1][centroCheiro + 1] = cheiroLadrao[7]; } /** * Retorna qual o ponto desconhecido mais próximo. * Retorna NULL quando não existir ponto desconhecido. * @return */ public Point desconhecidoMaisProximo() { if (pontoDesconhecidoProximo != null) { // se jah sabemos alguns ponto desconhecido proximo, entao vemos se ele ainda eh desconhecido if (mundo[pontoDesconhecidoProximo.y][pontoDesconhecidoProximo.x] != Constantes.VISAO_DESCONHECIDO) { // se nao for mais desconhecido, entao nao conhecemos o ponto! pontoDesconhecidoProximo = null; } } if (pontoDesconhecidoProximo == null) pontoDesconhecidoProximo = coisaMaisProximo(Constantes.VISAO_DESCONHECIDO); if (pontoDesconhecidoProximo == null) { // de fato nao ha pontos desconhecidos mais return null; } // retorna uma copia para nao mancharem a nossa variavel return new Point(pontoDesconhecidoProximo); } public Point moedaMaisProxima() { return coisaMaisProximo(Constantes.VISAO_MOEDA); } public Point coisaMaisProximo(int valorCoisa) { int minDist; int dist; Point curPoint; Point minPoint; Point pos; pos = getPos(); minDist = Integer.MAX_VALUE; curPoint = new Point(); minPoint = new Point(); /* * TODO: Otimizar busca. * Pontos mais proximos estarao em X,Y mais proximos de POS */ for (int i = 0; i < Constantes.MUNDO_TAM; i++) { for (int j = 0; j < Constantes.MUNDO_TAM; j++) { if (mundo[j][i] == valorCoisa) { curPoint.setLocation(i, j); dist = Constantes.manhattan(pos, curPoint); if (dist < minDist) { minPoint.setLocation(curPoint); minDist = dist; } } } } // se nao encontramos nenhum ponto desconhecido, retorne null if (minDist == Integer.MAX_VALUE) return null; return minPoint; } /* lembra de banco visto */ private void novoBanco(Point posBanco) { for (Point b : bancos) { // se conhece banco, nao o adiciona na lista if (b.x == posBanco.x && b.y == posBanco.y) return; } bancos.add(posBanco); } /* * Retorna posicao do banco mais proximo ou NULL se nao conhece nenhum banco */ public Point bancoMaisProximo() { int dist, min; Point pos = getPos(); Point posBanco = null; min = Integer.MAX_VALUE; for (Point b : bancos) { // isso acontecerá qndo o banco estiver inacessivel if (mundo[b.y][b.x] == Constantes.VISAO_INATINGIVEL) continue; // se nao podemos usar o banco, vamos para outro banco (se houver) dist = Constantes.manhattan(b, pos); // se encontramos distancia menor que a menor conhecida, atualizamos os dados if (dist < min) { min = dist; posBanco = b; } } return posBanco; } /** * Retorna algum local do mundo que seja distante do banco e de preferencia q nao seja um local que impeça a passagem de * outros. * @return */ private Point localErmo() { Point p = new Point(); Point banco = bancoMaisProximo(); // busca no perimetro do mundo locais distantes do banco e validos for (int i = 0; i < Constantes.MUNDO_TAM; i++) { p.y = 0; p.x = i; if (Constantes.isValidPoint(p, 0, mundo) && (banco == null || Constantes.manhattan(p, banco) > 3)) return p; p.y = Constantes.MUNDO_TAM-1; p.x = i; if (Constantes.isValidPoint(p, 0, mundo) && (banco == null || Constantes.manhattan(p, banco) > 3)) return p; p.y = i; p.x = 0; if (Constantes.isValidPoint(p, 0, mundo) && (banco == null || Constantes.manhattan(p, banco) > 3)) return p; p.y = i; p.x = Constantes.MUNDO_TAM-1; if (Constantes.isValidPoint(p, 0, mundo) && (banco == null || Constantes.manhattan(p, banco) > 3)) return p; } return null; } /** * Verifica se estamos nos movendo em loop. * @return número de loops realizados. 0 se não há loops */ private int historicoLoop() { Point[] hist; int loopStart; int loopNext; int loopCount; int loopLen; if (ultimasPosicoes.size() == 0) return 0; hist = ultimasPosicoes.toArray(new Point[0]); loopStart = 0; loopNext = 0; loopCount = 0; // buscamos loop inicial for (int i = 1; i < hist.length; i++) { // loop se inicia em loopStart e vai ateh alguma posicao que seja igual ao inicio if (hist[i].equals(hist[loopStart])) { loopNext = i; break; } } // nao incrementamos loopCount pois voltar a posicao inicial apenas nao significa que estamos em loop necessariamente loopLen = loopNext - loopStart; // se o final do loop nao foi alterado, entao nao ha loop // nao queremos loop parados no lugar, entao tamanho do loop tem que ser maior que 1 if (loopLen < 2) return 0; // contamos proximos loops, comecando no proximo (possivel) loop for (int i = loopNext; i < hist.length; i++) { if (hist[i].equals(hist[loopStart + (i - loopNext)])) { // se chegamos ao final do loop if (i - loopNext == loopLen - 1) { // passamos para proximo (possivel) loop loopNext = i + 1; // incrementamos contagem loopCount++; } } else // houve uma quebra do loop, nao ha mais loop daqui pra frente break; // nao conseguimos formar o loop, podemos parar com o que temos } return loopCount; } // guarda caminho dos ultimos quadros andados private void historicoPosicoes() { Point pos = getPos(); // lembramos um numero limite de ultimas posicoes if (ultimasPosicoes.size() == Constantes.HISTORICO_POSICAO_LEN) ultimasPosicoes.removeLast(); ultimasPosicoes.addFirst(pos); } // obtem posicao que estavamos no tick anterior private Point getPosicaoAnterior() { if (ultimasPosicoes.size() == 0) return getPos(); return ultimasPosicoes.getFirst(); } /** * Retorna algum vizinho de p que seja v�lido. * Se p � valido, retorna p. * Retorna NULL se nao houver nenhum. * @param p * @return */ private Point obterVizinhoValido(Point p) { if (p == null) return null; Point v = (Point)p.clone(); int numeroMoedas = sensor.getNumeroDeMoedas(); if (Constantes.isValidPoint(v, numeroMoedas, mundo)) return v; // cima v.y--; if (Constantes.isValidPoint(v, numeroMoedas, mundo)) return v; // baixo v.y += 2; if (Constantes.isValidPoint(v, numeroMoedas, mundo)) return v; // esq v.y = p.y; v.x--; if (Constantes.isValidPoint(v, numeroMoedas, mundo)) return v; // dir v.x += 2; if (Constantes.isValidPoint(v, numeroMoedas, mundo)) return v; return null; } /** * Retorna acao a ser tomada para ir da posicao atual ao destino usando pathfinding. * @param posicaoAtual * @param destino * @return */ private int goTo(Point posicaoAtual, Point destino) { int acao = Constantes.PARADO; Point destinoValido; // evita escolher um ponto invalido do mapa destinoValido = obterVizinhoValido(destino); // soh busque caminhos para destinos validos if (destinoValido != null) { Holder<Integer> ladraoDistancia = new Holder<Integer>(0); Point ladrao = ladraoMaisProximo(destinoValido, ladraoDistancia); // apenas vamos tentar ir para algum lugar que seja seguramente longe do ladrao if (ladrao == null || ladraoDistancia.value >= Constantes.MIN_DIST_LADRAO) acao = PathFinding.tomarMelhorDecisao(this, mundo, posicaoAtual, destinoValido); } // se pathfinding nao encontrou caminho // entao o local eh inacessivel if (acao == Constantes.PARADO) { ignorarLocalInatingivel(destino); } return acao; } // retorna a quanto tempo atrás a posicao foi visitada limitada por no maximo 'tempo' ticks // 0 significa que a posicao nao foi visitada, qualquer outro valor indica a quanto tempo isso a visita se deu private int isPosicaoRecente(Point pos, int tempo) { Point p; int j = 0; for (int i = ultimasPosicoes.size() - 1; j < tempo && i >= 0; i--) { p = ultimasPosicoes.get(i); if (p.x == pos.x && p.y == pos.y) return j + 1; j++; } return 0; } /* * Olha uma célula e retorna true se ela é valida para movimento (i.e., se podemos nos mover para ela) * distanciaOrigemBusca representa a distancia de manhattan entre a origem da busca e a posicao analisada * Retorna o valor de quão boa ela é em valorRet */ private boolean olharCelula(Point pos, int distanciaOrigemBusca, Holder<Double> valorRet) { double valor; int valorCelula; boolean valida; int posRecente; int numeroMoedas; int numeroJogadasImune; numeroMoedas = sensor.getNumeroDeMoedas(); // calcula qual será a quantidade de jogadas imunes q teremos numeroJogadasImune = Math.min(0, getNumeroJogasImunes() - distanciaOrigemBusca); Point posicaoAtual = getPos(); Holder<Integer> distanciaLadrao = new Holder<Integer>(0); Point ladrao = ladraoMaisProximo(pos, distanciaLadrao); valorCelula = mundo[pos.y][pos.x]; valida = Constantes.isValidPoint(pos, numeroMoedas, mundo); valor = 0; switch(valorCelula) { case Constantes.VISAO_MOEDA: valor = 10d / distanciaOrigemBusca; break; case Constantes.VISAO_PAREDE: case Constantes.VISAO_EXTERNO: valida = false; break; case Constantes.VISAO_BANCO: valor = numeroMoedas / (double)distanciaOrigemBusca; // ir ao banco soh se tivermos muitas moedas e por um caminho q nos deixe cada vez mais proximos valida = numeroMoedas > 0; // precisamos "entrar no banco" apenas se tivermos moedas break; case Constantes.VISAO_PASTILHA: // nao gostamos de pastilhas pq elas sao caras // soh pegaremos ela se ela for inicialmente valida // e se tiver algum ladrao suficientemente proximo para nos causar problemas valida = valida && ( ladrao != null && distanciaLadrao.value < 4 ); if (valida) valor = (3d - numeroJogadasImune) / distanciaLadrao.value; // considera nro de jogadas imune para evitar pegar pastilhas se jah estiver imune break; case Constantes.VISAO_DESCONHECIDO: valor = 1d / distanciaOrigemBusca; // interesse pelo desconhecido mais proximo break; default: if (Constantes.contemPupador(valorCelula)) { valor = -Constantes.BUSCA_PROFUNDIDADE / (double)distanciaOrigemBusca; // evitamos ficar perto de outros poupadores valida = false; } break; } int diffMovimento; // aqui evitamos caminhos com ladroes proximos se tivermos moedas // se estamos considerando a celula do banco, vamos depositar, nao fugir! if (ladrao != null && numeroMoedas > 0 && numeroJogadasImune > 0 && (diffMovimento = distanciaOrigemBusca - distanciaLadrao.value) > -Constantes.MIN_DIST_LADRAO && valorCelula != Constantes.VISAO_BANCO) { // nao eh uma posicao boa, ir para lá significa ser roubado! valor = -100 * (Constantes.MIN_DIST_LADRAO + diffMovimento); valida = false; } // se o local analisado for invalido (nao podemos nos mover para lá) if (!valida) { // adicionamos uma pequena valoração negativa para evitar que nosso agente durante fugas // se aprocime de locais com pouca mobilidade valor += - 0.5d / distanciaOrigemBusca; } valorRet.value = valor; return valida; } private Acao avaliarMovimento(Point pos, int profundidade, int acaoAnterior, Holder<Double> valorRet) { return avaliarMovimento(pos, profundidade, acaoAnterior, valorRet, false); } /* * Avalia movimento até uma certa profundidade e retorna acao escolhida */ private Acao avaliarMovimento(Point pos, int profundidade, int acaoAnterior, Holder<Double> valorRet, boolean raiz) { Point _pos; Acao minhaDecisao; int distManhBusca; boolean valido; double meuValor; meuValor = valorRet.value; // guardamos valor até aqui _pos = (Point)pos.clone(); // evitamos sujar variavel do chamador distManhBusca = Constantes.BUSCA_PROFUNDIDADE - profundidade + 1; // criamos decisao inicial como ficar parado minhaDecisao = new Acao(Constantes.PARADO, meuValor, true); if (raiz) { // se somos a raiz, nao temos valor anterior meuValor = 0d; } ////// BAIXO /////// if (acaoAnterior != Constantes.CIMA && pos.y < Constantes.MUNDO_TAM - 1) { _pos.y = pos.y + 1; _pos.x = pos.x; valido = olharCelula(_pos, distManhBusca, valorRet); // se podemos ir para o quadro, entao consideramos ele para analise if (valido) { // o valor do quadro analisado eh o meu valor mais o valor do proprio quadro valorRet.value += meuValor; // se precisamos analisar maior profundidade, fazemos isso aqui if (profundidade > 0) avaliarMovimento(_pos, profundidade - 1, Constantes.BAIXO, valorRet); // decidimos o que vale mais a pena fazer if (minhaDecisao.valor < valorRet.value) { minhaDecisao.acao = Constantes.BAIXO; minhaDecisao.valor = valorRet.value; } } } //// FIM BAIXO /////// ////// CIMA /////// if (acaoAnterior != Constantes.BAIXO && pos.y > 0) { _pos.y = pos.y - 1; _pos.x = pos.x; valido = olharCelula(_pos, distManhBusca, valorRet); // se podemos ir para o quadro, entao consideramos ele para analise if (valido) { // o valor do quadro analisado eh o meu valor mais o valor do proprio quadro valorRet.value += meuValor; // se precisamos analisar maior profundidade, fazemos isso aqui if (profundidade > 0) avaliarMovimento(_pos, profundidade - 1, Constantes.CIMA, valorRet); // decidimos o que vale mais a pena fazer if (minhaDecisao.valor < valorRet.value) { minhaDecisao.acao = Constantes.CIMA; minhaDecisao.valor = valorRet.value; } } } //// FIM CIMA /////// ////// ESQUERDA /////// if (acaoAnterior != Constantes.DIREITA && pos.x > 0) { _pos.y = pos.y; _pos.x = pos.x - 1; valido = olharCelula(_pos, distManhBusca, valorRet); // se podemos ir para o quadro, entao consideramos ele para analise if (valido) { // o valor do quadro analisado eh o meu valor mais o valor do proprio quadro valorRet.value += meuValor; // se precisamos analisar maior profundidade, fazemos isso aqui if (profundidade > 0) avaliarMovimento(_pos, profundidade - 1, Constantes.ESQUERDA, valorRet); // decidimos o que vale mais a pena fazer if (minhaDecisao.valor < valorRet.value) { minhaDecisao.acao = Constantes.ESQUERDA; minhaDecisao.valor = valorRet.value; } } } //// FIM ESQUERDA /////// ////// DIREITA /////// if (acaoAnterior != Constantes.ESQUERDA && pos.x < Constantes.MUNDO_TAM - 1) { _pos.x = pos.x + 1; _pos.y = pos.y; valido = olharCelula(_pos, distManhBusca, valorRet); // se podemos ir para o quadro, entao consideramos ele para analise if (valido) { // o valor do quadro analisado eh o meu valor mais o valor do proprio quadro valorRet.value += meuValor; // se precisamos analisar maior profundidade, fazemos isso aqui if (profundidade > 0) avaliarMovimento(_pos, profundidade - 1, Constantes.DIREITA, valorRet); // decidimos o que vale mais a pena fazer if (minhaDecisao.valor < valorRet.value) { minhaDecisao.acao = Constantes.DIREITA; minhaDecisao.valor = valorRet.value; } } } //// FIM DIREITA /////// // deixamos no valor de retorno o valor da nossa decisao valorRet.value = minhaDecisao.valor; return minhaDecisao; } /** * Decisao a ser tomada antes de executar árvore * @param pos * @param decisao * @return */ private Acao preDecisao(Point pos) { // aqui tomamos decisoes baseadas no estado atual // se decidirmos ao aqui, a árvore não será olhada // por padrao, ficaremos parados (nao tomaremos decisao) Acao decisao = new Acao(Constantes.PARADO, 0d, true); int numeroMoedas = sensor.getNumeroDeMoedas(); int numeroJogadasImunes = getNumeroJogasImunes(); int tamanhoLoop = historicoLoop(); Point destino; boolean bancoConhecido = true; // queremos evitar loops se formos encurralados pelos ladroes // nestes casos acabaremos em loop dependendo da acao do ladrao // se estamos em loop ha tempo suficiente if (tamanhoLoop >= Constantes.HISTORICO_LOOP_MAX || tempoEvitandoLoop > 0) { // etamos tratando loop // muda totalmente o comportamento para tentar evitar o loop // primeira vez q vamos evitar loop if (destinoEvitarLoop == null) { // TODO: melhorar isso // pode ser que escolhamos um ponto que nao tem regiao valida em volta destinoEvitarLoop = new Point((int)(Math.random() * (Constantes.MUNDO_TAM-1)),(int)(Math.random() * (Constantes.MUNDO_TAM-1))); // tempo para evitar loop tempoEvitandoLoop = Constantes.CHUCK_NORIS_TICKS; } destino = destinoEvitarLoop; } else { // nao estamos em loop, podemos fazer qualquer coisa destino = bancoMaisProximo(); // se nao conhecemos o banco, vamos procurá-lo if (destino == null) { // Eh hora do berserk? if (tick > Constantes.THIS_IS_SPARTAAAAAA) return decisao; // this is sparta! - basicamente evita buscar pelo banco, pois jah fizemos mto isso, se preocupe com pegar moedas bancoConhecido = false; destino = desconhecidoMaisProximo(); // se jah conhecemos o mundo inteiro if (destino == null) { // entao nao ha mto o que fazer, vamos embora sem fazer nada // esperamos que a arvore tenha mais sucesso return decisao; } } if (bancoConhecido) { // se banco eh conhecido mas estamos mto proximos dele, entao deixe que a arvore se encarrege de depositar if (Constantes.manhattan(pos, destino) == 1) return decisao; // problemas: ponde ter campers no banco impedindo que a gente deposite // podemos ficar perdendo tempo indo ao banco // podemos nao conhecer o banco e acabar pegando mtas moedas tentando encontrá-lo // conhecemos o banco // vamos para lá apenas se estamos ricos if (numeroMoedas < Constantes.RICO) { // se nao estamos ricos, deixa pra lá return decisao; } } } destino = obterVizinhoValido(destino); if (destino != null) { // se estamos aqui eh pq conhecemos o destino // vamos para o banco se estamos ricos e temos dinheiro para guardar decisao.acao = goTo(pos, destino); } return decisao; } /* * Pode alterar a decisao tomada pela árvore */ private Acao posDecisao(Point pos, Acao decisao) { // apenas faz algo se árvore nao pôde decidir o que fazer antes if (decisao.acao == Constantes.PARADO) { Point destino = null; // decide o que fazer // vai para o banco se tiver moedas if (sensor.getNumeroDeMoedas() > 0) destino = bancoMaisProximo(); // se o banco nao eh conhecido, entao vamos tentar outra coisa if (destino == null) { // senao conhecemos banco, vamos para algum lugar desconhecido a procura do banco destino = desconhecidoMaisProximo(); if (destino == null) { // se jah conhecemos todo o mapa, entao vamos atrás de moedas deixadas para tras destino = moedaMaisProxima(); if (destino == null) { // nao temos mais o que fazer // vamos evitar apenas atrapalhar o outro poupador, ficando longe do banco e longe de corredores destino = localErmo(); if (destino == null) { // se nao existe local ermo, eh melhor ficarmos em movimento do que possivelmente ocupando o meio // do caminho int max = 50; Point alvo = new Point(); while ((destino = obterVizinhoValido(alvo)) == null && max-- > 0) { alvo.setLocation((int)(Math.random() * (Constantes.MUNDO_TAM - 1)), (int)(Math.random() * (Constantes.MUNDO_TAM - 1))); } // se tentamos mas nao conseguimos encontrar local, desista if (destino == null) return decisao; } else if (destino.equals(pos)) { // se jah estamos no local ermo, entao podemos ficar parados destino = null; } } } } else { // se banco eh conhecido mas estamos mto proximos dele, entao deixe que a arvore se encarrege de depositar if (Constantes.manhattan(pos, destino) == 1) return decisao; } if (destino != null) { decisao.acao = goTo(pos, destino); if (decisao.acao == Constantes.PARADO) { // se nao pudemos andar, entao local era inacessivel e foi colocado na lista de inatingiveis // vamos tentar algum outro local decisao = posDecisao(pos, decisao); } } } return decisao; } private Acao decisaoArvore(Point pos, Acao decisao) { Holder<Double> valorRet; double valorParado; valorRet = new Holder<Double>(0d); // ditancia para ficar onde estamos eh 1 (finge que é pior ficar parado, em questao da fuga de ladroes) olharCelula(pos, 1, valorRet); decisao = avaliarMovimento(pos, Constantes.BUSCA_PROFUNDIDADE, Constantes.PARADO, valorRet, true); return decisao; } /* * Decide que acao tomar * */ private int avaliar(int[] visao, int[] oufato) { Point pos; Acao decisao; pos = getPos(); decisao = preDecisao(pos); // apenas olhamos a árvore se a pre-decisao não fez nada if (decisao.acao == Constantes.PARADO) decisao = decisaoArvore(pos, decisao); decisao = posDecisao(pos, decisao); return decisao.acao; } public int acao() { int[] oufato = sensor.getAmbienteOlfatoPoupador(); int[] visao = sensor.getVisaoIdentificacao(); int acao; descobreMundo(); acao = avaliar(visao, oufato); historicoPosicoes(); return acao; } }
Java
package algoritmo; public class Holder<T> { public T value; public Holder(T value) { this.value = value; } }
Java
import org.vu.contest.ContestSubmission; import org.vu.contest.ContestEvaluation; import java.util.Random; import java.util.Properties; import java.util.Arrays; import java.util.Comparator; class Crossover { int geneStart, geneEnd; // the indexes of genes the operator works on, operationStart inclusive, operationEnd exclusive Crossover(int geneStart, int geneEnd) { this.geneStart = geneStart; this.geneEnd = geneEnd; } public double[][] cross(double[] individual1, double[] individual2) { throw new UnsupportedOperationException(); } } class ParentSelection { public int[] selectParents(Individual[] population, int populationSize) {return null;} public void initSelection(Individual[] population, int populationSize) {} } interface ISurvivalSelection { public void select(Individual[] population, int populationSize); } class Mutation { final boolean evaluatesOffspring; // if the operator evaluates the offspring Mutation(boolean evaluatesOffspring) { this.evaluatesOffspring = evaluatesOffspring; } public void initGeneration() { }; // If the operator evaluates the offspring, // it Must evaluate the new individual and return false, it there were no more evaluations public boolean mutate(Individual individual) { throw new UnsupportedOperationException(); } } interface IInitialisaion { public void initialise(Individual[] population, int populationSize); } class InUniformRandom implements IInitialisaion { private ContestEvaluation evaluation_; private Random rnd_; public InUniformRandom(Random rnd, ContestEvaluation evaluation) { evaluation_ = evaluation; rnd_ = rnd; } private double[] genomebuff = new double[10]; public void initialise(Individual[] population, int populationSize) { for (int i = 0; i < populationSize; ++i) { population[i] = new Individual(); for (int j = 0; j < 10; ++j) { population[i].genome[j] = rnd_.nextDouble() * 10 - 5; genomebuff[j] = population[i].genome[j] ; } population[i].fitness = (Double) evaluation_.evaluate(genomebuff); } } } class PSUniformRandom extends ParentSelection { private Random rnd_; private boolean allowCloning; public PSUniformRandom(Random rnd, boolean allowCloning) { this.allowCloning = allowCloning; rnd_ = rnd; } public int[] selectParents(Individual[] population, int populationSize) { int[] parents = new int[2]; parents[0] = rnd_.nextInt(populationSize); parents[1] = rnd_.nextInt(populationSize); if (!allowCloning) { while(parents[0] == parents[1]) parents[1] = rnd_.nextInt(populationSize); } return parents; } } class PSRouletteWheel extends ParentSelection { // WARNING: this is slow, do not use on the first test function private Random rnd_; double sumFitness; double minFitness; private boolean allowCloning; public PSRouletteWheel(Random rnd, boolean allowCloning) { rnd_ = rnd; this.allowCloning = allowCloning; } public void initSelection(Individual[] population, int populationSize) { sumFitness = population[0].fitness; minFitness = population[0].fitness; for(int i = 1; i < populationSize; ++i) { sumFitness += population[i].fitness; if(minFitness > population[i].fitness) minFitness = population[i].fitness; } sumFitness -= populationSize * minFitness; } public int[] selectParents(Individual[] population, int populationSize) { int[] parents = new int[2]; double draw = rnd_.nextDouble() * sumFitness; parents[0] = 0; while (draw > (population[parents[0]].fitness - minFitness)) { draw = draw - (population[parents[0]].fitness - minFitness); parents[0]++; } draw = rnd_.nextDouble() * sumFitness; parents[1] = 0; while (draw > (population[parents[1]].fitness - minFitness)) { draw = draw - (population[parents[1]].fitness - minFitness); parents[1]++; } if (!allowCloning) { while(parents[1] == parents[0]) { draw = rnd_.nextDouble() * sumFitness; parents[1] = 0; while (draw > (population[parents[1]].fitness - minFitness)) { draw = draw - (population[parents[1]].fitness - minFitness); parents[1]++; } } } return parents; } } class PSRankBased extends ParentSelection { private Random rnd_; private double s, c1, c2; private boolean allowCloning; // 1.0 < s <= 2.0, if s is 0.0 then it implements exponential public PSRankBased(Random rnd, double s, boolean allowCloning) { rnd_ = rnd; this.s = s; this.allowCloning = allowCloning; } public void initSelection(Individual[] population, int populationSize) { Arrays.sort(population, 0, populationSize, new Comparator<Individual>() { @Override public int compare(Individual o1, Individual o2) { return ((Double) o2.fitness).compareTo(o1.fitness); } }); if (s == 0.0) { c1 = populationSize; for (int i = 0; i<populationSize; ++i) { c1 -= Math.exp(-i); } c1 = 1.0/c1; c2 = Math.exp(-1); } else { c1 = (2.0-s)/populationSize; c2 = 2.0*(s-1)/((populationSize-1)*populationSize); } } public int[] selectParents(Individual[] population, int populationSize) { int[] parents = new int[2]; double draw = rnd_.nextDouble(); parents[0] = 0; if (s == 0.0) { double prob = c1; while (draw > c1 - prob) { draw -= c1 - prob; prob *= c2; parents[0]++; } } else { while (draw > (c1 + parents[0]*c2)) { draw -= c1 + parents[0]*c2; parents[0]++; } } draw = rnd_.nextDouble(); parents[1] = 0; if (s == 0.0) { double prob = c1; while (draw > c1 - prob) { draw -= c1 - prob; prob *= c2; parents[1]++; } } else { while (draw > (c1 + parents[1]*c2)) { draw -= c1 + parents[1]*c2; parents[1]++; } } if (!allowCloning) { while(parents[1] == parents[0]) { draw = rnd_.nextDouble(); parents[1] = 0; if (s == 0.0) { double prob = c1; while (draw > c1 - prob) { draw -= c1 - prob; prob *= c2; parents[1]++; } } else { while (draw > (c1 + parents[1]*c2)) { draw -= c1 + parents[1]*c2; parents[1]++; } } } } parents[0] = populationSize - parents[0] - 1; parents[1] = populationSize - parents[1] - 1; return parents; } } class SSAnnihilation implements ISurvivalSelection { public SSAnnihilation() {} public void select(Individual[] population, int populationSize) { for(int i = populationSize; i < population.length; i++) { population[i - populationSize].copy(population[i]); } } } class SSRankBased implements ISurvivalSelection { private Random rnd_; private double s, c1, c2; // 1.0 < s <= 2.0, if s is 0.0 then it implements exponential public SSRankBased(Random rnd, double s) { rnd_ = rnd; this.s = s; } public void select(Individual[] population, int populationSize) { Arrays.sort(population, 0, population.length, new Comparator<Individual>() { @Override public int compare(Individual o1, Individual o2) { return ((Double) o2.fitness).compareTo(o1.fitness); } }); if (s == 0.0) { c1 = population.length; for (int i = 0; i<population.length; ++i) { c1 -= Math.exp(-i); } c1 = 1.0/c1; c2 = Math.exp(-1); } else { c1 = (2.0-s)/population.length; c2 = 2.0*(s-1)/((population.length-1)*population.length); } int selected; double draw; for(int i = populationSize; i < population.length; i++) { draw = rnd_.nextDouble(); selected = 0; if (s == 0.0) { double prob = c1; while (draw > c1 - prob) { draw -= c1 - prob; prob *= c2; selected++; } } else { while (draw > (c1 + selected*c2)) { draw -= c1 + selected*c2; selected++; } } population[i - populationSize].copy(population[selected]); } } } class SSSimpleSort implements ISurvivalSelection { public SSSimpleSort() {} public void select(Individual[] population, int populationSize) { Arrays.sort(population, new Comparator<Individual>() { @Override public int compare(Individual o1, Individual o2) { return ((Double) o2.fitness).compareTo(o1.fitness); } }); } } class NPointCrossover extends Crossover { private int N; private Random rnd_; public NPointCrossover(Random random, int geneStart, int geneEnd, int N) { super(geneStart, geneEnd); this.N = N; rnd_ = random; } public double[][] cross(double[] parent1, double[] parent2) { if (N > geneEnd - geneStart - 1) return null; int[] Xpoints = new int[N]; int numxpoints = 0; int draw; int i; while(numxpoints < N) { draw = 1 + rnd_.nextInt(geneEnd - geneStart-1); i = 0; while (i < numxpoints && Xpoints[i] != draw) i++; if (i == numxpoints) { Xpoints[numxpoints] = draw; numxpoints++; } } Arrays.sort(Xpoints); double[][] children = new double[2][geneEnd - geneStart]; boolean flip = false; numxpoints = 0; for (i = 0; i < geneEnd - geneStart; ++i) { if (numxpoints < N && Xpoints[numxpoints] == i) { numxpoints++; flip = !flip; } if(flip) { children[0][i] = parent2[geneStart + i]; children[1][i] = parent1[geneStart + i]; } else { children[0][i] = parent1[geneStart + i]; children[1][i] = parent2[geneStart + i]; } } return children; } } class IstvanNFlipCrossover extends Crossover { private int N; private Random rnd_; public IstvanNFlipCrossover(Random random, int geneStart, int geneEnd, int N) { super(geneStart, geneEnd); this.N = N; rnd_ = random; } public double[][] cross(double[] parent1, double[] parent2) { if (N > geneEnd - geneStart) return null; int[] Xpoints = new int[N]; int numxpoints = 0; int draw; int i; while(numxpoints < N) { draw = rnd_.nextInt(geneEnd - geneStart); i = 0; while (i < numxpoints && Xpoints[i] != draw) i++; if (i == numxpoints) { Xpoints[numxpoints] = draw; numxpoints++; } } Arrays.sort(Xpoints); double[][] children = new double[2][geneEnd - geneStart]; numxpoints = 0; for (i = 0; i < geneEnd - geneStart; ++i) { if (numxpoints < N && Xpoints[numxpoints] == i) { numxpoints++; children[0][i] = parent2[geneStart+i]; children[1][i] = parent1[geneStart+i]; } else { children[0][i] = parent1[geneStart+i]; children[1][i] = parent2[geneStart+i]; } } return children; } } class RandomFlipCrossover extends Crossover { private Random rnd_; public RandomFlipCrossover(Random random, int geneStart, int geneEnd) { super(geneStart, geneEnd); rnd_ = random; } public double[][] cross(double[] parent1, double[] parent2) { double[][] children = new double[1][geneEnd - geneStart]; for (int i = 0; i < geneEnd - geneStart; ++i) { if (rnd_.nextBoolean()) children[0][i] = parent1[geneStart + i]; else children[0][i] = parent2[geneStart + i]; } return children; } } class AveragerCrossover extends Crossover { public AveragerCrossover(int geneStart, int geneEnd) { super(geneStart, geneEnd); } public double[][] cross(double[] parent1, double[] parent2) { double[][] children = new double[1][geneEnd - geneStart]; for (int i = 0; i < geneEnd - geneStart; ++i) { children[0][i] = (parent1[geneStart + i] + parent2[geneStart + i]) / 2.0; } return children; } } class CompoundCrossover extends Crossover { private Crossover crossover1; private Crossover crossover2; public CompoundCrossover(Crossover crossover1, Crossover crossover2) { super(crossover1.geneStart, crossover2.geneEnd); this.crossover1 = crossover1; this.crossover2 = crossover2; } public double[][] cross(double[] parent1, double[] parent2) { double[][] children1 = crossover1.cross(parent1, parent2); double[][] children2 = crossover2.cross(parent1, parent2); int numOffspring; if (children2.length < children1.length) numOffspring = children2.length; else numOffspring = children1.length; double[][] children = new double[numOffspring][geneEnd-geneStart]; for (int i = 0; i < crossover1.geneEnd - geneStart; ++i) { for (int j = 0; j < numOffspring; ++j) { children[j][i] = children1[j][i]; } } for(int i = 0; i < geneEnd - crossover2.geneStart; ++i) { for (int j = 0; j < numOffspring; ++j) { children[j][i+crossover1.geneEnd] = children2[j][i]; } } return children; } } class UniformMutation extends Mutation { private double flip_prob; private Random rnd_; public UniformMutation(Random random, double prob) { super(false); flip_prob = prob; rnd_ = random; } public boolean mutate(Individual individual) { for(int i = 0; i < individual.genome.length; ++i){ if (flip_prob > rnd_.nextDouble()) { individual.genome[i] = rnd_.nextDouble()*10.0 - 5.0; } } return true; } } class GaussianMutation extends Mutation { private double flip_prob; private Random rnd_; private double mean; private double mean_dic; private ContestEvaluation evaluation_; public GaussianMutation(Random random, ContestEvaluation evaluation, double prob, double mean) { this(random, evaluation, prob, mean, 1.0); } public GaussianMutation(Random random, ContestEvaluation evaluation, double prob, double mean, double mean_dic) { super(false); evaluation_ = evaluation; flip_prob = prob; rnd_ = random; this.mean = mean; this.mean_dic = mean_dic; } public boolean mutate(Individual individual) { for(int i = 0; i < individual.genome.length; ++i){ if (flip_prob > rnd_.nextDouble()) { individual.genome[i] = rnd_.nextGaussian()*mean + individual.genome[i]; if (individual.genome[i] > 5) individual.genome[i] = 5; else if (individual.genome[i] < -5) individual.genome[i] = -5; } } return true; } public void initGeneration() { mean *= mean_dic; } } class GaussianMutationWithGlobalControl extends Mutation { private double flip_prob; private Random rnd_; private ContestEvaluation evaluation_; public GaussianMutationWithGlobalControl(Random random, ContestEvaluation evaluation, double prob) { super(true); evaluation_ = evaluation; flip_prob = prob; rnd_ = random; } private double[] g = new double[10]; private double calGamma(double fitness) { double coef; double epsilon = 0.00000000001; if (10.0 - fitness > 1.0) coef = Math.sqrt((10.0 - fitness)); else { coef = (10.0 - fitness)/0.4; // coef = Math.pow(coef, 1.1); } if (coef < epsilon) coef = epsilon; return coef; } public boolean mutate(Individual individual) { for (int j = 0; j < 10; ++j) { g[j] = individual.genome[j]; } Double fitness = (Double) evaluation_.evaluate(g); if (fitness == null) return false; individual.fitness = fitness.doubleValue(); double gamma = calGamma(individual.fitness); for(int i = 0; i < 10; ++i){ if (flip_prob > rnd_.nextDouble()) { individual.genome[i] = rnd_.nextGaussian()*gamma + individual.genome[i]; if (individual.genome[i] > 5) individual.genome[i] = 5; else if (individual.genome[i] < -5) individual.genome[i] = -5; } } for (int j = 0; j < 10; ++j) { g[j] = individual.genome[j]; } fitness = (Double) evaluation_.evaluate(g); if (fitness == null) return false; individual.fitness = fitness.doubleValue(); // individual.genome[10] = Math.sqrt(10.0 - individual.fitness); return true; } } class UncorrelatedWithNSigmas extends Mutation { private double tau, taucommon, epsilon; private Random rnd_; public UncorrelatedWithNSigmas(Random random, double taucommon, double tau, double epsilon) { super(false); this.rnd_ = random; this.taucommon = taucommon; this.tau = tau; this.epsilon = epsilon; } public boolean mutate(Individual individual) { double n = Math.exp(taucommon * rnd_.nextGaussian()); for(int j = 10; j < 20; ++j) { individual.genome[j] = individual.genome[j] * Math.exp(tau * rnd_.nextGaussian()) * n; if(individual.genome[j] < epsilon) individual.genome[j] = epsilon; } for(int j = 0; j < 10; ++j){ individual.genome[j] += individual.genome[j+10] * rnd_.nextGaussian(); if (individual.genome[j] > 5) individual.genome[j] = 5; else if (individual.genome[j] < -5) individual.genome[j] = -5; } return true; } } class Individual { public double[] genome; public double fitness; public int successfulMutations = 0; public Individual() { fitness = 100; genome = new double[20]; for (int i = 10; i < genome.length; ++i) { genome[i] = 1; } } public void copy(Individual other) { genome = other.genome.clone(); fitness = other.fitness; } } public class player19 implements ContestSubmission { private Random rnd_; private ContestEvaluation evaluation_; private int evaluations_limit_; private Mutation mutation_; private Crossover crossover_; private ParentSelection parentSelection_; private ISurvivalSelection survivalSelection_; private IInitialisaion initialisation_; private boolean isMultimodal; private boolean hasStructure; private boolean isSeparable; public static void main(String[] args) { int runs = 10; double result = 0.0; for (int i = 0; i < runs; ++i) { ContestEvaluation eval = new SphereEvaluation(); ContestSubmission sub = new player19(); sub.setSeed(System.currentTimeMillis()); sub.setEvaluation(eval); sub.run(); result += eval.getFinalResult(); } System.out.println("Result: "+result/runs); } public player19() { rnd_ = new Random(); } public void setSeed(long seed) { // Set seed of algorithms random process rnd_.setSeed(seed); } public void setEvaluation(ContestEvaluation evaluation) { // Set evaluation problem used in the run evaluation_ = evaluation; // Get evaluation properties Properties props = evaluation.getProperties(); evaluations_limit_ = Integer.parseInt(props.getProperty("Evaluations")); isMultimodal = Boolean.parseBoolean(props.getProperty("Multimodal")); hasStructure = Boolean.parseBoolean(props.getProperty("GlobalStructure")); isSeparable = Boolean.parseBoolean(props.getProperty("Separable")); if(isMultimodal){ // Do sth }else{ // Do sth else } } private void method(int num) { switch (num) { case 1: initialisation_ = new InUniformRandom(rnd_, evaluation_); parentSelection_ = new PSUniformRandom(rnd_, false); crossover_ = new NPointCrossover(rnd_, 0, 10, 3); mutation_ = new UniformMutation(rnd_, 0.1); survivalSelection_ = new SSSimpleSort(); break; case 2: initialisation_ = new InUniformRandom(rnd_, evaluation_); parentSelection_ = new PSUniformRandom(rnd_, false); crossover_ = new NPointCrossover(rnd_, 0, 10, 3); mutation_ = new UniformMutation(rnd_, 0.7); survivalSelection_ = new SSAnnihilation(); break; case 3: initialisation_ = new InUniformRandom(rnd_, evaluation_); parentSelection_ = new PSUniformRandom(rnd_, false); crossover_ = new IstvanNFlipCrossover(rnd_, 0, 10, 3); mutation_ = new UniformMutation(rnd_, 0.1); survivalSelection_ = new SSSimpleSort(); break; case 4: initialisation_ = new InUniformRandom(rnd_, evaluation_); parentSelection_ = new PSUniformRandom(rnd_, false); crossover_ = new IstvanNFlipCrossover(rnd_, 0, 10, 3); mutation_ = new GaussianMutation(rnd_, evaluation_, 0.09, 2); survivalSelection_ = new SSSimpleSort(); break; case 5: initialisation_ = new InUniformRandom(rnd_, evaluation_); parentSelection_ = new PSRouletteWheel(rnd_, false); crossover_ = new IstvanNFlipCrossover(rnd_, 0, 10, 2); mutation_ = new GaussianMutation(rnd_, evaluation_, 0.3, 1); survivalSelection_ = new SSAnnihilation(); break; case 6: initialisation_ = new InUniformRandom(rnd_, evaluation_); parentSelection_ = new PSRouletteWheel(rnd_, false); crossover_ = new IstvanNFlipCrossover(rnd_, 0, 10, 2); mutation_ = new GaussianMutation(rnd_, evaluation_, 0.29, 0.9); survivalSelection_ = new SSAnnihilation(); break; case 7: initialisation_ = new InUniformRandom(rnd_, evaluation_); parentSelection_ = new PSRankBased(rnd_, 1.9, true); crossover_ = new IstvanNFlipCrossover(rnd_, 0, 10, 4); mutation_ = new GaussianMutation(rnd_, evaluation_, 0.1, 0.4); survivalSelection_ = new SSAnnihilation(); break; case 8: initialisation_ = new InUniformRandom(rnd_, evaluation_); parentSelection_ = new PSRankBased(rnd_, 1.9, true); crossover_ = new IstvanNFlipCrossover(rnd_, 0, 10, 3); mutation_ = new GaussianMutation(rnd_, evaluation_, 0.7, 1, 0.91); survivalSelection_ = new SSAnnihilation(); break; case 9: initialisation_ = new InUniformRandom(rnd_, evaluation_); parentSelection_ = new PSUniformRandom(rnd_, true); crossover_ = new CompoundCrossover(new RandomFlipCrossover(rnd_, 0, 10), new AveragerCrossover(10, 20)); mutation_ = new UncorrelatedWithNSigmas(rnd_, 1.0 / Math.sqrt(2*10), 1.0 / Math.sqrt(2 * Math.sqrt(10)), 0.000000001); survivalSelection_ = new SSSimpleSort(); break; case 10: initialisation_ = new InUniformRandom(rnd_, evaluation_); parentSelection_ = new PSUniformRandom(rnd_, true); crossover_ = new CompoundCrossover(new IstvanNFlipCrossover(rnd_, 0, 10, 4), new AveragerCrossover(10, 20)); mutation_ = new GaussianMutationWithGlobalControl(rnd_, evaluation_, 8.0); survivalSelection_ = new SSSimpleSort(); break; case 11: initialisation_ = new InUniformRandom(rnd_, evaluation_); parentSelection_ = new PSUniformRandom(rnd_, true); crossover_ = new CompoundCrossover(new RandomFlipCrossover(rnd_, 0, 10), new AveragerCrossover(10, 20)); mutation_ = new GaussianMutationWithGlobalControl(rnd_, evaluation_, 8.0); survivalSelection_ = new SSSimpleSort(); break; case 12: initialisation_ = new InUniformRandom(rnd_, evaluation_); parentSelection_ = new PSUniformRandom(rnd_, true); // crossover_ = null; // crossover_ = new AveragerCrossover(0, 10); crossover_ = new IstvanNFlipCrossover(rnd_, 0, 10, 5); mutation_ = new GaussianMutationWithGlobalControl(rnd_, evaluation_, 1.0); survivalSelection_ = new SSSimpleSort(); break; default: break; } } public void run() { if (isMultimodal) { // method(7); method(11); int populationSize = 15; int numOffsprings = 60; Individual[] population = new Individual[populationSize+numOffsprings]; initialisation_ = new InUniformRandom(rnd_, evaluation_); initialisation_.initialise(population, populationSize); for (int i = populationSize; i < populationSize + numOffsprings; i++) { population[i] = new Individual(); } boolean running = true; double tau = 1.0 / Math.sqrt(2 * Math.sqrt(10)) * 1.01; double taucommon = 1.0 / Math.sqrt(2*10) * 1.01; double epsilon = 0.000000001; double epsilon2 = 0.0000000001; int parent1, parent2; double[] genomebuff = new double[10]; double bestfitness; while (running) { bestfitness = -9999999; for(int i = 0; i<populationSize; ++i) { if (bestfitness < population[i].fitness) bestfitness = population[i].fitness; } for (int i = populationSize; i < populationSize + numOffsprings; i += 1) { parent1 = rnd_.nextInt(populationSize); parent2 = rnd_.nextInt(populationSize); for (int j = 0; j < 10; ++j) { double ratio; double switchlimit = 8.9; if (population[parent1].fitness == 0.0 && population[parent2].fitness == 0.0) ratio = 0.5; else if (population[parent1].fitness > switchlimit && population[parent2].fitness > switchlimit) ratio = (population[parent1].fitness - switchlimit) / (population[parent1].fitness + population[parent2].fitness - 18.0); else ratio = population[parent1].fitness / (population[parent1].fitness + population[parent2].fitness); double ratiomin = 0.4; if (ratio < ratiomin) ratio = ratiomin; else if (ratio > 1.0 - ratiomin) ratio = 1.0 - ratiomin; population[i].genome[j] = population[parent1].genome[j] * ratio + population[parent2].genome[j] * (1.0-ratio); } for(int j = 10; j < 20; ++j) { population[i].genome[j] = (population[parent1].genome[j] + population[parent2].genome[j]) / 2.0; } } for (int i = populationSize; i < populationSize+ numOffsprings; ++i) { // GAMMA MUTATION double n = Math.exp(taucommon * rnd_.nextGaussian()); for(int j = 10; j < 20; ++j) { population[i].genome[j] = population[i].genome[j] * Math.exp(tau * rnd_.nextGaussian()) * n; if(population[i].genome[j] < epsilon) population[i].genome[j] = epsilon; } // GENOME MUTATION for(int j = 0; j < 10; ++j){ population[i].genome[j] += population[i].genome[j+10] * rnd_.nextGaussian(); if (population[i].genome[j] > 5) population[i].genome[j] = 5; else if (population[i].genome[j] < -5) population[i].genome[j] = -5; } // FITTNESS EVALUATION for (int j = 0; j < 10; ++j) { genomebuff[j] = population[i].genome[j]; } Double fitness = (Double) evaluation_.evaluate(genomebuff); if (fitness == null || fitness.doubleValue() == 10.0) { running = false; break; } population[i].fitness = fitness.doubleValue(); if (population[i].fitness < 9.0) { double sum = 0.0; for (int j = 10; j < 20; ++j) { sum += population[i].genome[j] * population[i].genome[j]; } sum = Math.sqrt(sum); double coef; if (9.0 > population[i].fitness) { coef = (10.0 - population[i].fitness) / 6; coef = Math.pow(coef, 1.1); } else { coef = (10.0 - population[i].fitness); coef = Math.pow(coef, 0.3); } if (coef < epsilon2) coef = epsilon2; coef /= sum; for (int j = 10; j < 20; ++j) { population[i].genome[j] *= coef; } } } Arrays.sort(population, new Comparator<Individual>() { @Override public int compare(Individual o1, Individual o2) { return ((Double) o2.fitness).compareTo(o1.fitness); } }); } int remain = 0; while (evaluation_.evaluate(genomebuff) != null) remain++; System.out.println("Remaining evals: " + String.valueOf(remain)); if (true) return; } else { method(12); int populationSize = 15; int numOffsprings = 60; Individual[] population = new Individual[populationSize+numOffsprings]; initialisation_ = new InUniformRandom(rnd_, evaluation_); initialisation_.initialise(population, populationSize); for (int i = populationSize; i < populationSize + numOffsprings; i++) { population[i] = new Individual(); } boolean running = true; double tau = 1.0 / Math.sqrt(2 * Math.sqrt(10)) * 1.01; double taucommon = 1.0 / Math.sqrt(2*10) * 1.01; double epsilon = 0.000000001; double epsilon2 = 0.0000000001; int parent1, parent2; double[] genomebuff = new double[10]; double bestfitness; while (running) { bestfitness = -9999999; for(int i = 0; i<populationSize; ++i) { if (bestfitness < population[i].fitness) bestfitness = population[i].fitness; } for (int i = populationSize; i < populationSize + numOffsprings; i += 1) { parent1 = rnd_.nextInt(populationSize); parent2 = rnd_.nextInt(populationSize); for (int j = 0; j < 10; ++j) { parent1 = rnd_.nextInt(populationSize); parent2 = rnd_.nextInt(populationSize); double ratio; double switchlimit = 8.9; if (population[parent1].fitness <= 0.0 && population[parent2].fitness <= 0.0) ratio = 0.5; else if (population[parent1].fitness > switchlimit && population[parent2].fitness > switchlimit) ratio = (population[parent1].fitness - switchlimit) / (population[parent1].fitness + population[parent2].fitness - 18.0); else ratio = population[parent1].fitness / (population[parent1].fitness + population[parent2].fitness); double ratiomin = 0.3; if (ratio < ratiomin) ratio = ratiomin; else if (ratio > 1.0 - ratiomin) ratio = 1.0 - ratiomin; population[i].genome[j] = population[parent1].genome[j] * ratio + population[parent2].genome[j] * (1.0-ratio); } for(int j = 10; j < 20; ++j) { population[i].genome[j] = (population[parent1].genome[j] + population[parent2].genome[j]) / 2.0; } } for (int i = populationSize; i < populationSize+ numOffsprings; ++i) { // GAMMA MUTATION double n = Math.exp(taucommon * rnd_.nextGaussian()); for(int j = 10; j < 20; ++j) { population[i].genome[j] = population[i].genome[j] * Math.exp(tau * rnd_.nextGaussian()) * n; if(population[i].genome[j] < epsilon) population[i].genome[j] = epsilon; } // GENOME MUTATION for(int j = 0; j < 10; ++j){ population[i].genome[j] += population[i].genome[j+10] * rnd_.nextGaussian(); if (population[i].genome[j] > 5) population[i].genome[j] = 5; else if (population[i].genome[j] < -5) population[i].genome[j] = -5; } // FITTNESS EVALUATION for (int j = 0; j < 10; ++j) { genomebuff[j] = population[i].genome[j]; } Double fitness = (Double) evaluation_.evaluate(genomebuff); if (fitness == null || fitness.doubleValue() == 10.0) { running = false; break; } population[i].fitness = fitness.doubleValue(); if (population[i].fitness < 8.0) { double sum = 0.0; for (int j = 10; j < 20; ++j) { sum += population[i].genome[j] * population[i].genome[j]; } sum = Math.sqrt(sum); double coef; if (9.0 > population[i].fitness) { coef = (10.0 - population[i].fitness) / 4; } else { coef = (10.0 - population[i].fitness); coef = Math.pow(coef, 0.3); } if (coef < epsilon2) coef = epsilon2; coef /= sum; for (int j = 10; j < 20; ++j) { population[i].genome[j] *= coef; } } } Arrays.sort(population, new Comparator<Individual>() { @Override public int compare(Individual o1, Individual o2) { return ((Double) o2.fitness).compareTo(o1.fitness); } }); } int remain = 0; while (evaluation_.evaluate(genomebuff) != null) remain++; System.out.println("Remaining evals: " + String.valueOf(remain)); return; } int populationSize = 100; int numOffsprings = 107; Individual[] population = new Individual[populationSize+numOffsprings]; initialisation_.initialise(population, populationSize); for (int i = populationSize; i < populationSize + numOffsprings; i++) { population[i] = new Individual(); } double bestfitness; boolean running = true; double[] g = new double[10]; while (running) { bestfitness = -9999999; for(int i = 0; i<populationSize; ++i) { if (bestfitness < population[i].fitness) bestfitness = population[i].fitness; } parentSelection_.initSelection(population, populationSize); for(int i = 0; i < numOffsprings;) { int[] parents = parentSelection_.selectParents(population, populationSize); if (crossover_ != null) { double[][] crossed = crossover_.cross(population[parents[0]].genome, population[parents[1]].genome); for (int j = 0; j < crossed.length; ++j) { population[populationSize + i + j].genome = crossed[j]; population[populationSize + i + j].fitness = population[parents[0]].fitness; } i += crossed.length; } else { population[populationSize + i ].genome = population[parents[0]].genome.clone(); population[populationSize + i ].fitness = population[parents[0]].fitness; population[populationSize + i + 1].genome = population[parents[1]].genome.clone(); population[populationSize + i + 1].fitness = population[parents[1]].fitness; i += 2; } } mutation_.initGeneration(); for (int i = populationSize; i < populationSize + numOffsprings; ++i) { if (mutation_.evaluatesOffspring) { if (!mutation_.mutate(population[i])) { running = false; break; } } else { mutation_.mutate(population[i]); for (int j = 0; j < 10; ++j) { g[j] = population[i].genome[j]; } Double fitness = (Double) evaluation_.evaluate(g); if (fitness == null) { running = false; break; } population[i].fitness = fitness.doubleValue(); } } survivalSelection_.select(population, populationSize); } } }
Java
import java.util.Properties; import org.vu.contest.ContestEvaluation; // This is an example evalation. It is based on the standard sphere function. It is a maximization problem with a maximum of 10 for // vector x=0. // The sphere function itself is for minimization with minimum at 0, thus fitness is calculated as Fitness = 10 - 10*(f-fbest), // where f is the result of the sphere function // Base performance is calculated as the distance of the expected fitness of a random search (with the same amount of available // evaluations) on the sphere function to the function minimum, thus Base = E[f_best_random] - ftarget. Fitness is scaled // according to this base, thus Fitness = 10 - 10*(f-fbest)/Base public class SphereEvaluation implements ContestEvaluation { // Evaluations budget private final static int EVALS_LIMIT_ = 10000; // The base performance. It is derived by doing random search on the sphere function (see function method) with the same // amount of evaluations private final static double BASE_ = 11.5356; // The minimum of the sphere function private final static double ftarget_=0; // Best fitness so far private double best_; // Evaluations used so far private int evaluations_; // Properties of the evaluation private String multimodal_ = "false"; private String regular_ = "true"; private String separable_ = "true"; private String evals_ = Integer.toString(EVALS_LIMIT_); public SphereEvaluation() { best_ = 0; evaluations_ = 0; } // The standard sphere function. It has one minimum at 0. private double function(double[] x) { double sum = 0; for(int i=0; i<10; i++) sum += x[i]*x[i]; return sum; } @Override public Object evaluate(Object result) { // Check argument if(!(result instanceof double[])) throw new IllegalArgumentException(); double ind[] = (double[]) result; if(ind.length!=10) throw new IllegalArgumentException(); if(evaluations_>EVALS_LIMIT_) return null; // Transform function value (sphere is minimization). // Normalize using the base performance double f = 10 - 10*( (function(ind)-ftarget_) / BASE_ ) ; if(f>best_) best_ = f; evaluations_++; return new Double(f); } @Override public Object getData(Object arg0) { return null; } @Override public double getFinalResult() { return best_; } @Override public Properties getProperties() { Properties props = new Properties(); props.put("Multimodal", multimodal_); props.put("Regular", regular_); props.put("Separable", separable_); props.put("Evaluations", evals_); return props; } }
Java
/**************************************************************************** * Copyright 2009 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.brightprof; import java.math.BigDecimal; import android.content.ContentResolver; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.view.Window; import android.view.WindowManager; public class Util { /** * Calculates the current application-defined brightness value of the phone. * This is done by taking the actual system brightness (a value from 0 to 255) * and normalizing it to a scale of 0 to 100. The actual brightness percentage * is calculated on the scale of minimumBrightness to 255, though. * * @param resolver * The ContentResolver. * @param db * A database accessor pointing to a DB with the minimum * brightness setting in it. * @return A value between 0 and 100. */ static int getPhoneBrighness(ContentResolver resolver, DbAccessor db) { int systemBrightness = getSystemBrightness(resolver); int minValue = db.getMinimumBrightness(); // The system brightness can range from 0 to 255. To normalize this // to the application's 0 to 100 brightness values, we lookup the // configured minimum value and then normalize for the range // minValue to 255. BigDecimal d = new BigDecimal((systemBrightness - minValue) / (255.0 - minValue) * 100.0); d = d.setScale(0, BigDecimal.ROUND_HALF_EVEN); int normalizedBrightness = d.intValue(); if (normalizedBrightness < 0) { // This can happen if another application sets the phone's brightness // to a value lower than our configured minimum. return 0; } else { return normalizedBrightness; } } /** * Finds the phone's system brightness setting. Returns 0 if there is an error * getting this setting. * * @param resolver * The ContentResolver. * @return A value between 0 and 255. */ static int getSystemBrightness(ContentResolver resolver) { // Lookup the initial system brightness. int systemBrightness = 0; try { systemBrightness = Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS); } catch (SettingNotFoundException e) { // TODO Log an error message. } return systemBrightness; } /** * Sets the brightness for the activity supplied as well as the system * brightness level. The brightness value passed in should be an integer * between 0 and 100. This method will translate that number into a normalized * value using the devices actual maximum brightness level and the minimum * brightness level calibrated via the CalibrateActivity activity. * * @param resolver * The ContentResolver. * @param window * The activity Window. * @param brightnessPercentage * An integer between 0 and 100. */ static void setPhoneBrightness(ContentResolver resolver, Window window, DbAccessor db, int brightnessPercentage) { // Lookup the minimum acceptable brightness set by the CalibrationActivity. int min_value = db.getMinimumBrightness(); // Convert the normalized application brightness to a system value (between // min_value and 255). BigDecimal d = new BigDecimal((brightnessPercentage / 100.0) * (255 - min_value) + min_value); d = d.setScale(0, BigDecimal.ROUND_HALF_EVEN); int brightnessUnits = d.intValue(); if (brightnessUnits < min_value) { brightnessUnits = min_value; } else if (brightnessUnits > 255) { brightnessUnits = 255; } setSystemBrightness(resolver, brightnessUnits); setActivityBrightness(window, brightnessUnits); } /** * Sets the phone's global brightness level. This does not change the screen's * brightness immediately. Valid brightnesses range from 0 to 255. * * @param resolver * The ContentResolver. * @param brightnessUnits * An integer between 0 and 255. */ static void setSystemBrightness(ContentResolver resolver, int brightnessUnits) { // Change the system brightness setting. This doesn't change the // screen brightness immediately. (Scale 0 - 255). Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS, brightnessUnits); } /** * Sets the screen brightness for this activity. The screen brightness will * change immediately. As soon as the activity terminates, the brightness will * return to the system brightness. Valid brightnesses range from 0 to 255. * * @param window * The activity window. * @param brightnessUnits * An integer between 0 and 255. */ static void setActivityBrightness(Window window, int brightnessUnits) { // Set the brightness of the current window. This takes effect immediately. // When the window is closed, the new system brightness is used. // (Scale 0.0 - 1.0). WindowManager.LayoutParams lp = window.getAttributes(); lp.screenBrightness = brightnessUnits / 255.0f; window.setAttributes(lp); } // These constants are not exposed through the API, but are defined in // Settings.System: // http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;f=core/java/android/provider/Settings.java;h=f7e55db80b8849c023152ad06d97040199c4e8c5;hb=HEAD private static final String SCREEN_BRIGHTNESS_MODE = "screen_brightness_mode"; private static final int SCREEN_BRIGHTNESS_MODE_MANUAL = 0; private static final int SCREEN_BRIGHTNESS_MODE_AUTOMATIC = 1; static boolean supportsAutoBrightness(ContentResolver resolver) { // This is probably not the best way to do this. The actual capability // is stored in // com.android.internal.R.bool.config_automatic_brightness_available // which is not available through the API. try { Settings.System.getInt(resolver, SCREEN_BRIGHTNESS_MODE); return true; } catch (SettingNotFoundException e) { return false; } } static boolean getAutoBrightnessEnabled(ContentResolver resolver) { try { int autobright = Settings.System.getInt(resolver, SCREEN_BRIGHTNESS_MODE); return autobright == SCREEN_BRIGHTNESS_MODE_AUTOMATIC; } catch (SettingNotFoundException e) { return false; } } static void setAutoBrightnessEnabled(ContentResolver resolver, boolean enabled) { if (enabled) { Settings.System.putInt(resolver, SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_AUTOMATIC); } else { Settings.System.putInt(resolver, SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_MANUAL); } } }
Java
/**************************************************************************** * Copyright 2009 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.brightprof; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.ContextMenu; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.widget.AdapterView; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ListView; import android.widget.SeekBar; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; public class BrightnessProfiles extends Activity { private static final int ACTIVITY_EDIT = 0; private static final int ACTIVITY_CALIBRATE = 1; private static final int MENU_EDIT = 0; private static final int MENU_DELETE = 1; private static final int OPTION_CALIBRATE = 0; private int appBrightness; private DbAccessor dbAccessor; private Cursor listViewCursor; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Initialize the database helper. dbAccessor = new DbAccessor(this); setContentView(R.layout.main); // Button to close the main window. Button closeBtn = (Button) findViewById(R.id.close_button); closeBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { finish(); } }); // Button to open the edit dialog (in add mode). Button addBtn = (Button) findViewById(R.id.add_button); addBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent(getApplication(), EditActivity.class); startActivityForResult(i, ACTIVITY_EDIT); } }); // Setup auto brightness checkbox handler. CheckBox checkbox = (CheckBox) findViewById(R.id.auto_brightness); checkbox.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() { public void onCheckedChanged( CompoundButton buttonView, boolean isChecked) { Util.setAutoBrightnessEnabled(getContentResolver(), isChecked); lockBrightnessControls(isChecked); // Update the app brightness in case auto brightness changed it. appBrightness = Util.getPhoneBrighness(getContentResolver(), dbAccessor); setBrightness(appBrightness); refreshDisplay(); } }); // Setup slider. SeekBar slider = (SeekBar) findViewById(R.id.slider); slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) { if (fromTouch) { setBrightness(progress); refreshDisplay(); } } public void onStartTrackingTouch(SeekBar seekBar) { } public void onStopTrackingTouch(SeekBar seekBar) { } }); // Get a database cursor. listViewCursor = dbAccessor.getAllProfiles(); startManagingCursor(listViewCursor); // Populate the list view using the Cursor. String[] from = new String[] { "name" }; int[] to = new int[] { R.id.profile_name }; SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.profile, listViewCursor, from, to); ListView profileList = (ListView) findViewById(R.id.profile_list); profileList.setAdapter(adapter); // Set the per-item click handler. profileList.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { listViewCursor.moveToPosition(position); int brightness = listViewCursor.getInt(listViewCursor .getColumnIndexOrThrow(DbHelper.PROF_VALUE_COL)); setBrightness(brightness); // TODO(cgallek): This will terminate the application after a profile // is selected. Consider making this a configurable option. finish(); } }); registerForContextMenu(profileList); } @Override protected void onDestroy() { dbAccessor.closeConnections(); super.onDestroy(); } @Override protected void onResume() { // Lookup the initial system brightness and set our app's brightness // percentage appropriately. appBrightness = Util.getPhoneBrighness(getContentResolver(), dbAccessor); // Set the value for the brightness text field and slider. refreshDisplay(); super.onResume(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.add(Menu.NONE, MENU_EDIT, Menu.NONE, R.string.edit); menu.add(Menu.NONE, MENU_DELETE, Menu.NONE, R.string.delete); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case MENU_EDIT: listViewCursor.moveToPosition(info.position); Intent i = new Intent(getApplication(), EditActivity.class); i.putExtra(DbHelper.PROF_ID_COL, listViewCursor.getInt(listViewCursor .getColumnIndexOrThrow(DbHelper.PROF_ID_COL))); i.putExtra(DbHelper.PROF_NAME_COL, listViewCursor .getString(listViewCursor .getColumnIndexOrThrow(DbHelper.PROF_NAME_COL))); i.putExtra(DbHelper.PROF_VALUE_COL, listViewCursor .getInt(listViewCursor .getColumnIndexOrThrow(DbHelper.PROF_VALUE_COL))); startActivityForResult(i, ACTIVITY_EDIT); return true; case MENU_DELETE: listViewCursor.moveToPosition(info.position); int id = listViewCursor.getInt(listViewCursor .getColumnIndexOrThrow(DbHelper.PROF_ID_COL)); dbAccessor.deletProfile(id); listViewCursor.requery(); return true; default: return super.onContextItemSelected(item); } } @Override public boolean onCreateOptionsMenu(Menu menu) { boolean result = super.onCreateOptionsMenu(menu); MenuItem calibrate = menu.add(0, OPTION_CALIBRATE, 0, R.string.calibrate); calibrate.setIcon(android.R.drawable.ic_menu_preferences); return result; } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean result = super.onPrepareOptionsMenu(menu); // Don't setup the calibrate menu item if auto brightness is enabled. // Trying to calibrate while it's on is weird... MenuItem calibrate = menu.findItem(OPTION_CALIBRATE); if (Util.supportsAutoBrightness(getContentResolver()) && Util.getAutoBrightnessEnabled(getContentResolver())) { calibrate.setEnabled(false); } else { calibrate.setEnabled(true); } return result; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case OPTION_CALIBRATE: Intent i = new android.content.Intent(getApplicationContext(), CalibrateActivity.class); startActivityForResult(i, ACTIVITY_CALIBRATE); break; } return super.onOptionsItemSelected(item); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_DOWN: setBrightness(getBrightness() - 10); return true; case KeyEvent.KEYCODE_VOLUME_UP: setBrightness(getBrightness() + 10); return true; default: return super.onKeyDown(keyCode, event); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_CANCELED) { return; } if (requestCode != ACTIVITY_EDIT) { return; } Bundle extras = data.getExtras(); int id = extras.getInt(DbHelper.PROF_ID_COL); switch (resultCode) { case Activity.RESULT_OK: String name = extras.getString(DbHelper.PROF_NAME_COL); int brightness = extras.getInt(DbHelper.PROF_VALUE_COL); dbAccessor.updateProfile(id, name, brightness); listViewCursor.requery(); break; } } private void refreshDisplay() { TextView brightnessText = (TextView) findViewById(R.id.brightness); brightnessText.setText(getString(R.string.brightness) + " " + getBrightness() + "%"); SeekBar slider = (SeekBar) findViewById(R.id.slider); slider.setProgress(getBrightness()); // Show/Hide the auto brightness check box. CheckBox checkbox = (CheckBox) findViewById(R.id.auto_brightness); if (Util.supportsAutoBrightness(getContentResolver())) { checkbox.setVisibility(View.VISIBLE); if (Util.getAutoBrightnessEnabled(getContentResolver())) { checkbox.setChecked(true); lockBrightnessControls(true); } else { checkbox.setChecked(false); lockBrightnessControls(false); } } else { checkbox.setVisibility(View.GONE); lockBrightnessControls(false); } } private int getBrightness() { return appBrightness; } private void setBrightness(int brightness) { // Don't try to adjust brightness if auto brightness is enabled. if (Util.supportsAutoBrightness(getContentResolver()) && Util.getAutoBrightnessEnabled(getContentResolver())) { return; } if (brightness < 0) { appBrightness = 0; } else if (brightness > 100) { appBrightness = 100; } else { appBrightness = brightness; } Util.setPhoneBrightness(getContentResolver(), getWindow(), dbAccessor, appBrightness); refreshDisplay(); } private void lockBrightnessControls(boolean lock) { SeekBar slider = (SeekBar) findViewById(R.id.slider); ListView profileList = (ListView) findViewById(R.id.profile_list); // Note: setEnabled() doesn't seem to work with this ListView, nor does // calling setEnabled() on the individual children of the ListView. // The items become grayed out, but the click handlers are still registered. // As a work around, simply hide the entire list view. if (lock) { profileList.setVisibility(View.GONE); slider.setEnabled(false); } else { profileList.setVisibility(View.VISIBLE); slider.setEnabled(true); } } }
Java
/**************************************************************************** * Copyright 2009 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.brightprof; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class EditActivity extends Activity { private static final int UNKNOWN_ID = -1; private int profile_id_ = UNKNOWN_ID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.edit); Button okButton = (Button) findViewById(R.id.ok_button); Button cancelButton = (Button) findViewById(R.id.cancel_button); cancelButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { setResult(RESULT_CANCELED); finish(); } }); final EditText nameBox = (EditText) findViewById(R.id.edit_name); final EditText brightnessBox = (EditText) findViewById(R.id.edit_brightness); final String name; final int brightness; Bundle extras = getIntent().getExtras(); if (extras == null) { profile_id_ = UNKNOWN_ID; name = ""; brightness = -1; } else { profile_id_ = extras.getInt(DbHelper.PROF_ID_COL); name = extras.getString(DbHelper.PROF_NAME_COL); brightness = extras.getInt(DbHelper.PROF_VALUE_COL); nameBox.setText(name); brightnessBox.setText(Integer.toString(brightness)); } okButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String newName = nameBox.getText().toString(); String brightnessText = brightnessBox.getText().toString(); int newBrightness = brightness; try { newBrightness = Integer.parseInt(brightnessText); } catch (NumberFormatException e) { newBrightness = -1; } if (newName.length() == 0 || newBrightness < 0 || newBrightness > 100) { // TODO display some kind of error message? return; } // If nothing changed, act as though cancel was pressed. if (name.equals(newName) && brightness == newBrightness) { setResult(RESULT_CANCELED); finish(); } // Bundle up the new values. Bundle bundle = new Bundle(); bundle.putInt(DbHelper.PROF_ID_COL, profile_id_); bundle.putString(DbHelper.PROF_NAME_COL, newName); bundle.putInt(DbHelper.PROF_VALUE_COL, newBrightness); Intent intent = new Intent(); intent.putExtras(bundle); setResult(RESULT_OK, intent); finish(); } }); } }
Java
/**************************************************************************** * Copyright 2009 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.brightprof; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class DbAccessor { private DbHelper db; private SQLiteDatabase rDb; private SQLiteDatabase rwDb; public DbAccessor(Context context) { db = new DbHelper(context); rDb = db.getReadableDatabase(); rwDb = db.getWritableDatabase(); } public void closeConnections() { rDb.close(); rwDb.close(); } public Cursor getAllProfiles() { return rDb.query(DbHelper.DB_TABLE_PROFILES, new String[] { DbHelper.PROF_ID_COL, DbHelper.PROF_NAME_COL, DbHelper.PROF_VALUE_COL }, null, null, null, null, null); } public void updateProfile(int rowId, String name, int brightness) { ContentValues values = new ContentValues(2); values.put(DbHelper.PROF_NAME_COL, name); values.put(DbHelper.PROF_VALUE_COL, brightness); // If this is an unknown row id, create a new row. if (rowId < 0) { rwDb.insert(DbHelper.DB_TABLE_PROFILES, null, values); // Otherwise, update the supplied row id. } else { String where = DbHelper.PROF_ID_COL + " = " + rowId; rwDb.update(DbHelper.DB_TABLE_PROFILES, values, where, null); } } public void deletProfile(int rowId) { String where = DbHelper.PROF_ID_COL + " = " + rowId; rwDb.delete(DbHelper.DB_TABLE_PROFILES, where, null); } public int getMinimumBrightness() { Cursor c = rDb.query(DbHelper.DB_TABLE_CALIBRATE, new String[] { DbHelper.CALIB_MIN_BRIGHT_COL }, null, null, null, null, null); c.moveToFirst(); int b = c.getInt(c.getColumnIndexOrThrow(DbHelper.CALIB_MIN_BRIGHT_COL)); c.deactivate(); c.close(); return b; } public void setMinimumBrightness(int brightness) { ContentValues values = new ContentValues(1); values.put(DbHelper.CALIB_MIN_BRIGHT_COL, brightness); rwDb.update(DbHelper.DB_TABLE_CALIBRATE, values, null, null); } }
Java
/**************************************************************************** * Copyright 2009 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.brightprof; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.TextView; public class CalibrateActivity extends Activity { private int minBrightness = 20; private DbAccessor db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.calibrate); Button okButton = (Button) findViewById(R.id.ok_button); Button cancelButton = (Button) findViewById(R.id.cancel_button); db = new DbAccessor(this); okButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { db.setMinimumBrightness(minBrightness); // If the new minimum brightness is greater than the current screen // setting, update the setting. if (minBrightness > Util.getSystemBrightness(getContentResolver())) { Util.setSystemBrightness(getContentResolver(), minBrightness); } setResult(RESULT_OK); finish(); } }); cancelButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { setResult(RESULT_CANCELED); finish(); } }); } @Override protected void onDestroy() { db.closeConnections(); super.onDestroy(); } @Override protected void onResume() { super.onResume(); updateDisplay(); Util.setActivityBrightness(getWindow(), minBrightness); TextView current_minimum_brightness = (TextView) findViewById(R.id.current_min_brightness); current_minimum_brightness.setText("" + db.getMinimumBrightness()); } @Override protected void onPause() { // Return the brightness to it's previous state when the dialog closes. Util.setActivityBrightness(getWindow(), -1); super.onPause(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_DOWN: // Don't allow this value to go to 0. It shuts the screen off. if (minBrightness > 1) { minBrightness -= 1; updateDisplay(); Util.setActivityBrightness(getWindow(), minBrightness); } return true; case KeyEvent.KEYCODE_VOLUME_UP: if (minBrightness < 255) { minBrightness += 1; updateDisplay(); Util.setActivityBrightness(getWindow(), minBrightness); } return true; default: return super.onKeyDown(keyCode, event); } } private void updateDisplay() { TextView test_min_brightness = (TextView) findViewById(R.id.test_min_brightness); test_min_brightness.setText("" + minBrightness); } }
Java
/**************************************************************************** * Copyright 2009 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.brightprof; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DbHelper extends SQLiteOpenHelper { public static final String DB_NAME = "brightprof"; public static final String DB_TABLE_PROFILES = "profiles"; public static final String DB_TABLE_CALIBRATE = "calibrate"; public static final int DB_VERSION = 3; public static final String PROF_ID_COL = "_id"; public static final String PROF_NAME_COL = "name"; public static final String PROF_VALUE_COL = "value"; public static final String CALIB_MIN_BRIGHT_COL = "min_bright"; public DbHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // Table to hold information for each profile. db.execSQL("CREATE TABLE " + DB_TABLE_PROFILES + " (" + PROF_ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, " + PROF_NAME_COL + " TEXT NOT NULL," + PROF_VALUE_COL + " UNSIGNED INTEGER (0, 100))"); db.execSQL("INSERT INTO " + DB_TABLE_PROFILES + "( " + PROF_NAME_COL + ", " + PROF_VALUE_COL + ") VALUES ('Low', 0)"); db.execSQL("INSERT INTO " + DB_TABLE_PROFILES + "( " + PROF_NAME_COL + ", " + PROF_VALUE_COL + ") VALUES ('Normal', 15)"); db.execSQL("INSERT INTO " + DB_TABLE_PROFILES + "( " + PROF_NAME_COL + ", " + PROF_VALUE_COL + ") VALUES ('High', 100)"); createCalibrationTable(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // DB version 3 added a table for keeping track of minimum brightness. // It is no longer necessary to enforce this minimum in the profile table // (as values 0 through 100 are now valid). // This creates the new minimum brightness table for old installs. if (oldVersion < 3) { createCalibrationTable(db); } } void createCalibrationTable(SQLiteDatabase db) { // Table to hold calibration settings. db.execSQL("CREATE TABLE " + DB_TABLE_CALIBRATE + " (" + CALIB_MIN_BRIGHT_COL + " UNSIGNED INTEGER (1, 255))"); db.execSQL("INSERT INTO " + DB_TABLE_CALIBRATE + "( " + CALIB_MIN_BRIGHT_COL + ") VALUES (10)"); } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import java.util.Calendar; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Handler; import android.text.format.DateFormat; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewStub; import android.view.View.OnFocusChangeListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; /** * This class is a slight improvement over the android time picker dialog. * It allows the user to select hour, minute, and second (the android picker * does not support seconds). It also has a configurable increment feature * (30, 5, and 1). */ public final class TimePickerDialog extends AlertDialog { public interface OnTimeSetListener { public void onTimeSet(int hourOfDay, int minute, int second); } private static final String PICKER_PREFS = "TimePickerPreferences"; private static final String INCREMENT_PREF = "increment"; private OnTimeSetListener listener; private SharedPreferences prefs; private Calendar calendar; private TextView timeText; private Button amPmButton; private PickerView hourPicker; private PickerView minutePicker; private PickerView secondPicker; /** * Construct a time picker with the supplied hour minute and second. * @param context * @param title Dialog title. * @param hourOfDay 0 to 23. * @param minute 0 to 60. * @param second 0 to 60. * @param showSeconds Show/hide the seconds field. * @param setListener Callback for when the user selects 'OK'. */ public TimePickerDialog(Context context, String title, int hourOfDay, int minute, int second, final boolean showSeconds, OnTimeSetListener setListener) { this(context, title, showSeconds, setListener); calendar.set(Calendar.HOUR_OF_DAY, hourOfDay); hourPicker.pickerRefresh(); calendar.set(Calendar.MINUTE, minute); minutePicker.pickerRefresh(); calendar.set(Calendar.SECOND, second); if (showSeconds) { secondPicker.pickerRefresh(); } dialogRefresh(); } /** * Construct a time picker with 'now' as the starting time. * @param context * @param title Dialog title. * @param showSeconds Show/hid the seconds field. * @param setListener Callback for when the user selects 'OK'. */ public TimePickerDialog(Context context, String title, final boolean showSeconds, OnTimeSetListener setListener) { super(context); listener = setListener; prefs = context.getSharedPreferences(PICKER_PREFS, Context.MODE_PRIVATE); calendar = Calendar.getInstance(); // The default increment amount is stored in a shared preference. Look // it up. final int incPref = prefs.getInt(INCREMENT_PREF, IncrementValue.FIVE.ordinal()); final IncrementValue defaultIncrement = IncrementValue.values()[incPref]; // OK button setup. setButton(AlertDialog.BUTTON_POSITIVE, context.getString(R.string.ok), new OnClickListener(){ public void onClick(DialogInterface dialog, int which) { if (listener == null) { return; } int seconds = showSeconds ? calendar.get(Calendar.SECOND) : 0; listener.onTimeSet( calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), seconds); } }); // Cancel button setup. setButton(AlertDialog.BUTTON_NEGATIVE, context.getString(R.string.cancel), new OnClickListener(){ public void onClick(DialogInterface dialog, int which) { cancel(); } }); // Set title and icon. if (title.length() != 0) { setTitle(title); setIcon(R.drawable.ic_dialog_time); } // Set the view for the body section of the AlertDialog. final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View body_view = inflater.inflate(R.layout.time_picker_dialog, null); setView(body_view); // Setup each of the components of the body section. timeText = (TextView) body_view.findViewById(R.id.picker_text); amPmButton = (Button) body_view.findViewById(R.id.picker_am_pm); amPmButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (calendar.get(Calendar.AM_PM) == Calendar.AM) { calendar.set(Calendar.AM_PM, Calendar.PM); } else { calendar.set(Calendar.AM_PM, Calendar.AM); } dialogRefresh(); } }); // Setup the three time fields. if (DateFormat.is24HourFormat(getContext())) { body_view.findViewById(R.id.picker_am_pm_layout).setVisibility(View.GONE); hourPicker = new PickerView(Calendar.HOUR_OF_DAY, "%02d"); } else { body_view.findViewById(R.id.picker_am_pm_layout).setVisibility(View.VISIBLE); hourPicker = new PickerView(Calendar.HOUR, "%d"); } hourPicker.inflate(body_view, R.id.picker_hour, false, IncrementValue.ONE); minutePicker = new PickerView(Calendar.MINUTE, "%02d"); minutePicker.inflate(body_view, R.id.picker_minute, true, defaultIncrement); if (showSeconds) { secondPicker = new PickerView(Calendar.SECOND, "%02d"); secondPicker.inflate(body_view, R.id.picker_second, true, defaultIncrement); } dialogRefresh(); } private void dialogRefresh() { AlarmTime time = new AlarmTime( calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND)); timeText.setText(time.timeUntilString(getContext())); if (calendar.get(Calendar.AM_PM) == Calendar.AM) { amPmButton.setText(getContext().getString(R.string.am)); } else { amPmButton.setText(getContext().getString(R.string.pm)); } } /** * Enum that represents the states of the increment picker button. */ private enum IncrementValue { FIVE(5), ONE(1); private int value; IncrementValue(int value) { this.value = value; } public int value() { return value; } } /** * Helper class that wraps up the view elements of each number picker * (plus/minus button, text field, increment picker). */ private final class PickerView { private int calendarField; private String formatString; private EditText text = null; private Increment increment = null; private Button incrementValueButton = null; private Button plus = null; private Button minus = null; /** * Construct a numeric picker for the supplied calendar field and formats * it according to the supplied format string. * @param calendarField * @param formatString */ public PickerView(int calendarField, String formatString) { this.calendarField = calendarField; this.formatString = formatString; } /** * Inflates the ViewStub for this numeric picker. * @param parentView * @param resourceId * @param showIncrement * @param defaultIncrement */ public void inflate(View parentView, int resourceId, boolean showIncrement, IncrementValue defaultIncrement) { final ViewStub stub = (ViewStub) parentView.findViewById(resourceId); final View view = stub.inflate(); text = (EditText) view.findViewById(R.id.time_value); text.setOnFocusChangeListener(new TextChangeListener()); text.setOnEditorActionListener(new TextChangeListener()); increment = new Increment(defaultIncrement); incrementValueButton = (Button) view.findViewById(R.id.time_increment); incrementValueButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { increment.cycleToNext(); Editor editor = prefs.edit(); editor.putInt(INCREMENT_PREF, increment.value.ordinal()); editor.commit(); pickerRefresh(); } }); if (showIncrement) { incrementValueButton.setVisibility(View.VISIBLE); } else { incrementValueButton.setVisibility(View.GONE); } plus = (Button) view.findViewById(R.id.time_plus); TimeIncrementListener incrementListener = new TimeIncrementListener(); plus.setOnClickListener(incrementListener); plus.setOnTouchListener(incrementListener); plus.setOnLongClickListener(incrementListener); minus = (Button) view.findViewById(R.id.time_minus); TimeDecrementListener decrementListener= new TimeDecrementListener(); minus.setOnClickListener(decrementListener); minus.setOnTouchListener(decrementListener); minus.setOnLongClickListener(decrementListener); pickerRefresh(); } public void pickerRefresh() { int fieldValue = calendar.get(calendarField); if (calendarField == Calendar.HOUR && fieldValue == 0) { fieldValue = 12; } text.setText(String.format(formatString, fieldValue)); incrementValueButton.setText("+/- " + increment.nextValue().value()); plus.setText("+" + increment.value()); minus.setText("-" + increment.value()); dialogRefresh(); } private final class Increment { private IncrementValue value; public Increment(IncrementValue value) { this.value = value; } public IncrementValue nextValue() { int nextIndex = (value.ordinal() + 1) % IncrementValue.values().length; return IncrementValue.values()[nextIndex]; } public void cycleToNext() { value = nextValue(); } public int value() { return value.value(); } } /** * Listener that figures out what the next value should be when a numeric * picker plus/minus button is clicked. It will round up/down to the next * interval increment then increment by the increment amount on subsequent * clicks. */ private abstract class TimeAdjustListener implements View.OnClickListener, View.OnTouchListener, View.OnLongClickListener { protected abstract int sign(); private void adjust() { int currentValue = calendar.get(calendarField); int remainder = currentValue % increment.value(); if (remainder == 0) { calendar.roll(calendarField, sign() * increment.value()); } else { int difference; if (sign() > 0) { difference = increment.value() - remainder; } else { difference = -1 * remainder; } calendar.roll(calendarField, difference); } pickerRefresh(); } private Handler handler = new Handler(); private Runnable delayedAdjust = new Runnable() { @Override public void run() { adjust(); handler.postDelayed(delayedAdjust, 150); } }; @Override public void onClick(View v) { adjust(); } @Override public boolean onLongClick(View v) { delayedAdjust.run(); return false; } @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { handler.removeCallbacks(delayedAdjust); } return false; } } private final class TimeIncrementListener extends TimeAdjustListener { @Override protected int sign() { return 1; } } private final class TimeDecrementListener extends TimeAdjustListener { @Override protected int sign() { return -1; } } /** * Listener to handle direct user input into the time picker text fields. * Updates after the editor confirmation button is picked or when the * text field loses focus. */ private final class TextChangeListener implements OnFocusChangeListener, OnEditorActionListener { private void handleChange() { try { int newValue = Integer.parseInt(text.getText().toString()); if (calendarField == Calendar.HOUR && newValue == 12 && calendar.get(Calendar.AM_PM) == Calendar.AM) { calendar.set(Calendar.HOUR_OF_DAY, 0); } else if (calendarField == Calendar.HOUR && newValue == 12 && calendar.get(Calendar.AM_PM) == Calendar.PM) { calendar.set(Calendar.HOUR_OF_DAY, 12); } else { calendar.set(calendarField, newValue); } } catch (NumberFormatException e) {} pickerRefresh(); } @Override public void onFocusChange(View v, boolean hasFocus) { handleChange(); } @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { handleChange(); return false; } } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import android.app.Activity; import android.content.Context; import android.media.MediaPlayer; import android.net.Uri; import android.provider.MediaStore.Audio.Albums; import android.provider.MediaStore.Audio.ArtistColumns; import android.util.AttributeSet; import android.view.View; import android.widget.AdapterView; import android.widget.ViewFlipper; public class MediaArtistsView extends MediaListView { private final String[] artistsColumns = new String[] { ArtistColumns.ARTIST, ArtistColumns.ARTIST_KEY }; private final int[] artistsResIDs = new int[] { R.id.media_value, R.id.media_key }; private MediaAlbumsView albumsView; public MediaArtistsView(Context context) { this(context, null); } public MediaArtistsView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MediaArtistsView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); albumsView = new MediaAlbumsView(context); } @Override public void setCursorManager(Activity activity) { super.setCursorManager(activity); albumsView.setCursorManager(activity); } @Override public void addToFlipper(ViewFlipper flipper) { super.addToFlipper(flipper); albumsView.addToFlipper(flipper); } public void setMediaPlayer(MediaPlayer mPlayer) { albumsView.setMediaPlayer(mPlayer); } public void query(Uri contentUri) { query(contentUri, null); } public void query(Uri contentUri, String selection) { super.query(contentUri, ArtistColumns.ARTIST_KEY, selection, R.layout.media_picker_row, artistsColumns, artistsResIDs); } @Override public void setMediaPickListener(OnItemPickListener listener) { albumsView.setMediaPickListener(listener); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { super.onItemClick(parent, view, position, id); albumsView.query(Albums.EXTERNAL_CONTENT_URI, ArtistColumns.ARTIST_KEY + " = '" + getLastSelectedName() + "'"); getFlipper().setInAnimation(getContext(), R.anim.slide_in_left); getFlipper().setOutAnimation(getContext(), R.anim.slide_out_left); getFlipper().showNext(); } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import java.util.Calendar; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnCancelListener; import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; /** * This is the main Activity for the application. It contains a ListView * for displaying all alarms, a simple clock, and a button for adding new * alarms. The context menu allows the user to edit default settings. Long- * clicking on the clock will trigger a dialog for enabling/disabling 'debug * mode.' */ public final class ActivityAlarmClock extends Activity { private enum Dialogs { TIME_PICKER, DELETE_CONFIRM }; private enum Menus { DELETE_ALL, DEFAULT_ALARM_SETTINGS, APP_SETTINGS }; private AlarmClockServiceBinder service; private NotificationServiceBinder notifyService; private DbAccessor db; private AlarmViewAdapter adapter; private TextView clock; private Button testBtn; private Button pendingBtn; private Handler handler; private Runnable tickCallback; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.alarm_list); // Access to in-memory and persistent data structures. service = new AlarmClockServiceBinder(getApplicationContext()); db = new DbAccessor(getApplicationContext()); handler = new Handler(); notifyService = new NotificationServiceBinder(getApplicationContext()); // Setup individual UI elements. // A simple clock. clock = (TextView) findViewById(R.id.clock); // Used in debug mode. Schedules an alarm for 5 seconds in the future // when clicked. testBtn = (Button) findViewById(R.id.test_alarm); testBtn.setOnClickListener(new OnClickListener() { public void onClick(View view) { final Calendar testTime = Calendar.getInstance(); testTime.add(Calendar.SECOND, 5); service.createAlarm(new AlarmTime(testTime.get( Calendar.HOUR_OF_DAY), testTime.get(Calendar.MINUTE), testTime.get(Calendar.SECOND))); adapter.requery(); } }); // Displays a list of pending alarms (only visible in debug mode). pendingBtn = (Button) findViewById(R.id.pending_alarms); pendingBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity( new Intent(getApplicationContext(), ActivityPendingAlarms.class)); } }); // Opens the time picker dialog and allows the user to schedule a new alarm. Button addBtn = (Button) findViewById(R.id.add_alarm); addBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { showDialog(Dialogs.TIME_PICKER.ordinal()); } }); // Setup the alarm list and the underlying adapter. Clicking an individual // item will start the settings activity. final ListView alarmList = (ListView) findViewById(R.id.alarm_list); adapter = new AlarmViewAdapter(this, db, service); alarmList.setAdapter(adapter); alarmList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View view, int position, long id) { final AlarmInfo info = (AlarmInfo) adapter.getItemAtPosition(position); final Intent i = new Intent(getApplicationContext(), ActivityAlarmSettings.class); i.putExtra(ActivityAlarmSettings.EXTRAS_ALARM_ID, info.getAlarmId()); startActivity(i); } }); // This is a self-scheduling callback that is responsible for refreshing // the screen. It is started in onResume() and stopped in onPause(). tickCallback = new Runnable() { @Override public void run() { // Redraw the screen. redraw(); // Schedule the next update on the next interval boundary. AlarmUtil.Interval interval = AlarmUtil.Interval.MINUTE; if (AppSettings.isDebugMode(getApplicationContext())) { interval = AlarmUtil.Interval.SECOND; } long next = AlarmUtil.millisTillNextInterval(interval); handler.postDelayed(tickCallback, next); } }; } @Override protected void onResume() { super.onResume(); service.bind(); handler.post(tickCallback); adapter.requery(); notifyService.bind(); notifyService.call(new NotificationServiceBinder.ServiceCallback() { @Override public void run(NotificationServiceInterface service) { int count; try { count = service.firingAlarmCount(); } catch (RemoteException e) { return; } finally { handler.post(new Runnable() { @Override public void run() { notifyService.unbind(); } }); } if (count > 0) { Intent notifyActivity = new Intent(getApplicationContext(), ActivityAlarmNotification.class); notifyActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(notifyActivity); } } }); } @Override protected void onPause() { super.onPause(); handler.removeCallbacks(tickCallback); service.unbind(); } @Override protected void onDestroy() { super.onDestroy(); db.closeConnections(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuItem delete_all = menu.add(0, Menus.DELETE_ALL.ordinal(), 0, R.string.delete_all); delete_all.setIcon(android.R.drawable.ic_menu_close_clear_cancel); MenuItem alarm_settings = menu.add(0, Menus.DEFAULT_ALARM_SETTINGS.ordinal(), 0, R.string.default_settings); alarm_settings.setIcon(android.R.drawable.ic_lock_idle_alarm); MenuItem app_settings = menu.add(0, Menus.APP_SETTINGS.ordinal(), 0, R.string.app_settings); app_settings.setIcon(android.R.drawable.ic_menu_preferences); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (Menus.values()[item.getItemId()]) { case DELETE_ALL: showDialog(Dialogs.DELETE_CONFIRM.ordinal()); break; case DEFAULT_ALARM_SETTINGS: Intent alarm_settings = new Intent(getApplicationContext(), ActivityAlarmSettings.class); alarm_settings.putExtra( ActivityAlarmSettings.EXTRAS_ALARM_ID, AlarmSettings.DEFAULT_SETTINGS_ID); startActivity(alarm_settings); break; case APP_SETTINGS: Intent app_settings = new Intent(getApplicationContext(), ActivityAppSettings.class); startActivity(app_settings); break; } return super.onOptionsItemSelected(item); } private final void redraw() { // Show/hide debug buttons. if (AppSettings.isDebugMode(getApplicationContext())) { testBtn.setVisibility(View.VISIBLE); pendingBtn.setVisibility(View.VISIBLE); } else { testBtn.setVisibility(View.GONE); pendingBtn.setVisibility(View.GONE); } // Recompute expiration times in the list view adapter.notifyDataSetChanged(); // Update clock Calendar c = Calendar.getInstance(); AlarmTime time = new AlarmTime( c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), c.get(Calendar.SECOND)); clock.setText(time.localizedString(getApplicationContext())); } @Override protected Dialog onCreateDialog(int id) { switch (Dialogs.values()[id]) { case TIME_PICKER: Dialog picker = new TimePickerDialog( this, getString(R.string.add_alarm), AppSettings.isDebugMode(this), new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(int hourOfDay, int minute, int second) { // When a time is selected, create it via the service and // force the list view to re-query the alarm list. service.createAlarm(new AlarmTime(hourOfDay, minute, second)); adapter.requery(); // Destroy this dialog so that it does not save its state. removeDialog(Dialogs.TIME_PICKER.ordinal()); } }); picker.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { removeDialog(Dialogs.TIME_PICKER.ordinal()); } }); return picker; case DELETE_CONFIRM: final AlertDialog.Builder deleteConfirmBuilder = new AlertDialog.Builder(this); deleteConfirmBuilder.setTitle(R.string.delete_all); deleteConfirmBuilder.setMessage(R.string.confirm_delete); deleteConfirmBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { service.deleteAllAlarms(); adapter.requery(); dismissDialog(Dialogs.DELETE_CONFIRM.ordinal()); } }); deleteConfirmBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismissDialog(Dialogs.DELETE_CONFIRM.ordinal()); } }); return deleteConfirmBuilder.create(); default: return super.onCreateDialog(id); } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import android.app.Activity; import android.content.Context; import android.media.MediaPlayer; import android.net.Uri; import android.provider.MediaStore.Audio.AlbumColumns; import android.provider.MediaStore.Audio.Media; import android.util.AttributeSet; import android.view.View; import android.widget.AdapterView; import android.widget.ViewFlipper; public class MediaAlbumsView extends MediaListView { private final String[] albumsColumns = new String[] { AlbumColumns.ALBUM, AlbumColumns.ALBUM_KEY }; private final int[] albumsResIDs = new int[] { R.id.media_value, R.id.media_key }; private MediaSongsView songsView; public MediaAlbumsView(Context context) { this(context, null); } public MediaAlbumsView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MediaAlbumsView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); overrideSortOrder(AlbumColumns.ALBUM + " ASC"); songsView = new MediaSongsView(context); songsView.overrideSortOrder(null); } @Override public void setCursorManager(Activity activity) { super.setCursorManager(activity); songsView.setCursorManager(activity); } @Override public void addToFlipper(ViewFlipper flipper) { super.addToFlipper(flipper); songsView.addToFlipper(flipper); } public void setMediaPlayer(MediaPlayer mPlayer) { songsView.setMediaPlayer(mPlayer); } public void query(Uri contentUri) { query(contentUri, null); } public void query(Uri contentUri, String selection) { super.query(contentUri, AlbumColumns.ALBUM_KEY, selection, R.layout.media_picker_row, albumsColumns, albumsResIDs); } @Override public void setMediaPickListener(OnItemPickListener listener) { songsView.setMediaPickListener(listener); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { super.onItemClick(parent, view, position, id); songsView.query(Media.EXTERNAL_CONTENT_URI, AlbumColumns.ALBUM_KEY + " = '" + getLastSelectedName() + "'"); getFlipper().setInAnimation(getContext(), R.anim.slide_in_left); getFlipper().setOutAnimation(getContext(), R.anim.slide_out_left); getFlipper().showNext(); } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import java.util.LinkedList; import com.angrydoughnuts.android.alarmclock.WakeLock.WakeLockException; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Handler; import android.os.IBinder; import android.os.Vibrator; /** * This service is responsible for notifying the user when an alarm is * triggered. The pending intent delivered by the alarm manager service * will trigger the alarm receiver. This receiver will in turn start * this service, passing the appropriate alarm url as data in the intent. * This service is capable of receiving multiple alarm notifications * without acknowledgments and will queue them until they are sequentially * acknowledged. The service is capable of playing a sound, triggering * the vibrator and displaying the notification activity (used to acknowledge * alarms). */ public class NotificationService extends Service { public class NoAlarmsException extends Exception { private static final long serialVersionUID = 1L; } // Since the media player objects are expensive to create and destroy, // share them across invocations of this service (there should never be // more than one instance of this class in a given application). private enum MediaSingleton { INSTANCE; private MediaPlayer mediaPlayer = null; private Ringtone fallbackSound = null; private Vibrator vibrator = null; MediaSingleton() { mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); } // Force the alarm stream to be maximum volume. This will allow the user // to select a volume between 0 and 100 percent via the settings activity. private void normalizeVolume(Context c, float startVolume) { final AudioManager audio = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE); audio.setStreamVolume(AudioManager.STREAM_ALARM, audio.getStreamMaxVolume(AudioManager.STREAM_ALARM), 0); setVolume(startVolume); } private void setVolume(float volume) { mediaPlayer.setVolume(volume, volume); } private void useContext(Context c) { // The media player can fail for lots of reasons. Try to setup a backup // sound for use when the media player fails. fallbackSound = RingtoneManager.getRingtone(c, AlarmUtil.getDefaultAlarmUri()); if (fallbackSound == null) { Uri superFallback = RingtoneManager.getValidRingtoneUri(c); fallbackSound = RingtoneManager.getRingtone(c, superFallback); } // Make the fallback sound use the alarm stream as well. if (fallbackSound != null) { fallbackSound.setStreamType(AudioManager.STREAM_ALARM); } // Instantiate a vibrator. That's fun to say. vibrator = (Vibrator) c.getSystemService(Context.VIBRATOR_SERVICE); } private void ensureSound() { if (!mediaPlayer.isPlaying() && fallbackSound != null && !fallbackSound.isPlaying()) { fallbackSound.play(); } } private void vibrate() { if (vibrator != null) { vibrator.vibrate(new long[] {500, 500}, 0); } } public void play(Context c, Uri tone) { mediaPlayer.reset(); mediaPlayer.setLooping(true); try { mediaPlayer.setDataSource(c, tone); mediaPlayer.prepare(); mediaPlayer.start(); } catch (Exception e) { e.printStackTrace(); } } public void stop() { mediaPlayer.stop(); if (vibrator != null) { vibrator.cancel(); } if (fallbackSound != null) { fallbackSound.stop(); } } } // Data private LinkedList<Long> firingAlarms; private AlarmClockServiceBinder service; private DbAccessor db; // Notification tools private NotificationManager manager; private Notification notification; private PendingIntent notificationActivity; private Handler handler; private VolumeIncreaser volumeIncreaseCallback; private Runnable soundCheck; private Runnable notificationBlinker; private Runnable autoCancel; @Override public IBinder onBind(Intent intent) { return new NotificationServiceInterfaceStub(this); } @Override public void onCreate() { super.onCreate(); firingAlarms = new LinkedList<Long>(); // Access to in-memory and persistent data structures. service = new AlarmClockServiceBinder(getApplicationContext()); service.bind(); db = new DbAccessor(getApplicationContext()); // Setup audio. MediaSingleton.INSTANCE.useContext(getApplicationContext()); // Setup notification bar. manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // Use the notification activity explicitly in this intent just in case the // activity can't be viewed via the root activity. Intent intent = new Intent(getApplicationContext(), ActivityAlarmNotification.class); notificationActivity = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0); notification = new Notification(R.drawable.alarmclock_notification, null, 0); notification.flags |= Notification.FLAG_ONGOING_EVENT; // Setup a self-scheduling event loops. handler = new Handler(); volumeIncreaseCallback = new VolumeIncreaser(); soundCheck = new Runnable() { @Override public void run() { // Some sound should always be playing. MediaSingleton.INSTANCE.ensureSound(); long next = AlarmUtil.millisTillNextInterval(AlarmUtil.Interval.SECOND); handler.postDelayed(soundCheck, next); } }; notificationBlinker = new Runnable() { @Override public void run() { String notifyText; try { AlarmInfo info = db.readAlarmInfo(currentAlarmId()); notifyText = info.getName(); if (notifyText.equals("")) { notifyText = info.getTime().localizedString(getApplicationContext()); } } catch (NoAlarmsException e) { return; } notification.setLatestEventInfo(getApplicationContext(), notifyText, "", notificationActivity); if (notification.icon == R.drawable.alarmclock_notification) { notification.icon = R.drawable.alarmclock_notification2; } else { notification.icon = R.drawable.alarmclock_notification; } manager.notify(AlarmClockService.NOTIFICATION_BAR_ID, notification); long next = AlarmUtil.millisTillNextInterval(AlarmUtil.Interval.SECOND); handler.postDelayed(notificationBlinker, next); } }; autoCancel = new Runnable() { @Override public void run() { try { acknowledgeCurrentNotification(0); } catch (NoAlarmsException e) { return; } Intent notifyActivity = new Intent(getApplicationContext(), ActivityAlarmNotification.class); notifyActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); notifyActivity.putExtra(ActivityAlarmNotification.TIMEOUT_COMMAND, true); startActivity(notifyActivity); } }; } @Override public void onDestroy() { super.onDestroy(); db.closeConnections(); service.unbind(); boolean debug = AppSettings.isDebugMode(getApplicationContext()); if (debug && firingAlarms.size() != 0) { throw new IllegalStateException("Notification service terminated with pending notifications."); } try { WakeLock.assertNoneHeld(); } catch (WakeLockException e) { if (debug) { throw new IllegalStateException(e.getMessage()); } } } // OnStart was depreciated in SDK 5. It is here for backwards compatibility. // http://android-developers.blogspot.com/2010/02/service-api-changes-starting-with.html @Override public void onStart(Intent intent, int startId) { handleStart(intent, startId); } @Override public int onStartCommand(Intent intent, int flags, int startId) { handleStart(intent, startId); return START_NOT_STICKY; } private void handleStart(Intent intent, int startId) { // startService called from alarm receiver with an alarm id url. if (intent != null && intent.getData() != null) { long alarmId = AlarmUtil.alarmUriToId(intent.getData()); try { WakeLock.assertHeld(alarmId); } catch (WakeLockException e) { if (AppSettings.isDebugMode(getApplicationContext())) { throw new IllegalStateException(e.getMessage()); } } Intent notifyActivity = new Intent(getApplicationContext(), ActivityAlarmNotification.class); notifyActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(notifyActivity); boolean firstAlarm = firingAlarms.size() == 0; if (!firingAlarms.contains(alarmId)) { firingAlarms.add(alarmId); } if (firstAlarm) { soundAlarm(alarmId); } } } public long currentAlarmId() throws NoAlarmsException { if (firingAlarms.size() == 0) { throw new NoAlarmsException(); } return firingAlarms.getFirst(); } public int firingAlarmCount() { return firingAlarms.size(); } public float volume() { return volumeIncreaseCallback.volume(); } public void acknowledgeCurrentNotification(int snoozeMinutes) throws NoAlarmsException { long alarmId = currentAlarmId(); if (firingAlarms.contains(alarmId)) { firingAlarms.remove(alarmId); if (snoozeMinutes <= 0) { service.acknowledgeAlarm(alarmId); } else { service.snoozeAlarmFor(alarmId, snoozeMinutes); } } stopNotifying(); // If this was the only alarm firing, stop the service. Otherwise, // start the next alarm in the stack. if (firingAlarms.size() == 0) { stopSelf(); } else { soundAlarm(alarmId); } try { WakeLock.release(alarmId); } catch (WakeLockException e) { if (AppSettings.isDebugMode(getApplicationContext())) { throw new IllegalStateException(e.getMessage()); } } } private void soundAlarm(long alarmId) { // Begin notifying based on settings for this alaram. AlarmSettings settings = db.readAlarmSettings(alarmId); if (settings.getVibrate()) { MediaSingleton.INSTANCE.vibrate(); } volumeIncreaseCallback.reset(settings); MediaSingleton.INSTANCE.play(getApplicationContext(), settings.getTone()); // Start periodic events for handling this notification. handler.post(volumeIncreaseCallback); handler.post(soundCheck); handler.post(notificationBlinker); // Set up a canceler if this notification isn't acknowledged by the timeout. int timeoutMillis = 60 * 1000 * AppSettings.alarmTimeOutMins(getApplicationContext()); handler.postDelayed(autoCancel, timeoutMillis); } private void stopNotifying() { // Stop periodic events. handler.removeCallbacks(volumeIncreaseCallback); handler.removeCallbacks(soundCheck); handler.removeCallbacks(notificationBlinker); handler.removeCallbacks(autoCancel); // Stop notifying. MediaSingleton.INSTANCE.stop(); } /** * Helper class for gradually increasing the volume of the alarm audio * stream. */ private final class VolumeIncreaser implements Runnable { float start; float end; float increment; public float volume() { return start; } public void reset(AlarmSettings settings) { start = (float) (settings.getVolumeStartPercent() / 100.0); end = (float) (settings.getVolumeEndPercent() / 100.0); increment = (end - start) / (float) settings.getVolumeChangeTimeSec(); MediaSingleton.INSTANCE.normalizeVolume(getApplicationContext(), start); } @Override public void run() { start += increment; if (start > end) { start = end; } MediaSingleton.INSTANCE.setVolume(start); if (Math.abs(start - end) > (float) 0.0001) { handler.postDelayed(volumeIncreaseCallback, 1000); } } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.preference.Preference.OnPreferenceChangeListener; import android.provider.Settings; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; /** * Simple preferences activity to display/manage the shared preferences * that make up the global application settings. */ public class ActivityAppSettings extends PreferenceActivity { private enum Dialogs { CUSTOM_LOCK_SCREEN } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.app_settings); OnPreferenceChangeListener refreshListener = new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { // Clear the lock screen text if the user disables the feature. if (preference.getKey().equals(AppSettings.LOCK_SCREEN)) { Settings.System.putString(getContentResolver(), Settings.System.NEXT_ALARM_FORMATTED, ""); final String custom_lock_screen = getResources().getStringArray(R.array.lock_screen_values)[4]; if (newValue.equals(custom_lock_screen)) { showDialog(Dialogs.CUSTOM_LOCK_SCREEN.ordinal()); } } final Intent causeRefresh = new Intent(getApplicationContext(), AlarmClockService.class); causeRefresh.putExtra(AlarmClockService.COMMAND_EXTRA, AlarmClockService.COMMAND_NOTIFICATION_REFRESH); startService(causeRefresh); return true; } }; // Refresh the notification icon when the user changes these preferences. final Preference notification_icon = findPreference(AppSettings.NOTIFICATION_ICON); notification_icon.setOnPreferenceChangeListener(refreshListener); final Preference lock_screen = findPreference(AppSettings.LOCK_SCREEN); lock_screen.setOnPreferenceChangeListener(refreshListener); } @Override protected Dialog onCreateDialog(int id) { switch (Dialogs.values()[id]) { case CUSTOM_LOCK_SCREEN: final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); final View lockTextView = getLayoutInflater().inflate(R.layout.custom_lock_screen_dialog, null); final EditText editText = (EditText) lockTextView.findViewById(R.id.custom_lock_screen_text); editText.setText(prefs.getString(AppSettings.CUSTOM_LOCK_SCREEN_TEXT, "")); final CheckBox persistentCheck = (CheckBox) lockTextView.findViewById(R.id.custom_lock_screen_persistent); persistentCheck.setChecked(prefs.getBoolean(AppSettings.CUSTOM_LOCK_SCREEN_PERSISTENT, false)); final AlertDialog.Builder lockTextBuilder = new AlertDialog.Builder(this); lockTextBuilder.setTitle(R.string.custom_lock_screen_text); lockTextBuilder.setView(lockTextView); lockTextBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Editor editor = prefs.edit(); editor.putString(AppSettings.CUSTOM_LOCK_SCREEN_TEXT, editText.getText().toString()); editor.putBoolean(AppSettings.CUSTOM_LOCK_SCREEN_PERSISTENT, persistentCheck.isChecked()); editor.commit(); final Intent causeRefresh = new Intent(getApplicationContext(), AlarmClockService.class); causeRefresh.putExtra(AlarmClockService.COMMAND_EXTRA, AlarmClockService.COMMAND_NOTIFICATION_REFRESH); startService(causeRefresh); dismissDialog(Dialogs.CUSTOM_LOCK_SCREEN.ordinal()); } }); lockTextBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismissDialog(Dialogs.CUSTOM_LOCK_SCREEN.ordinal()); } }); return lockTextBuilder.create(); default: return super.onCreateDialog(id); } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import android.app.Activity; import android.app.Service; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.widget.ArrayAdapter; import android.widget.ListView; /** * This is a simple activity which displays all of the scheduled (in memory) * alarms that currently exist (For debugging only). */ public final class ActivityPendingAlarms extends Activity { boolean connected; private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.pending_alarms); connected = false; listView = (ListView) findViewById(R.id.pending_alarm_list); } @Override protected void onResume() { super.onResume(); final Intent i = new Intent(getApplicationContext(), AlarmClockService.class); if (!bindService(i, connection, Service.BIND_AUTO_CREATE)) { throw new IllegalStateException("Unable to bind to AlarmClockService."); } } @Override protected void onPause() { super.onPause(); if (connected) { unbindService(connection); } } private final ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { connected = true; AlarmClockInterface clock = AlarmClockInterface.Stub.asInterface(service); try { ArrayAdapter<AlarmTime> adapter = new ArrayAdapter<AlarmTime>( getApplicationContext(), R.layout.pending_alarms_item, clock.pendingAlarmTimes()); listView.setAdapter(adapter); } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onServiceDisconnected(ComponentName name) { connected = false; } }; }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import com.angrydoughnuts.android.alarmclock.NotificationService.NoAlarmsException; import android.content.Context; import android.os.RemoteException; import android.widget.Toast; public class NotificationServiceInterfaceStub extends NotificationServiceInterface.Stub { private NotificationService service; public NotificationServiceInterfaceStub(NotificationService service) { this.service = service; } @Override public long currentAlarmId() throws RemoteException { try { return service.currentAlarmId(); } catch (NoAlarmsException e) { throw new RemoteException(); } } public int firingAlarmCount() throws RemoteException { return service.firingAlarmCount(); } @Override public float volume() throws RemoteException { return service.volume(); } @Override public void acknowledgeCurrentNotification(int snoozeMinutes) throws RemoteException { debugToast("STOP NOTIFICATION"); try { service.acknowledgeCurrentNotification(snoozeMinutes); } catch (NoAlarmsException e) { throw new RemoteException(); } } private void debugToast(String message) { Context context = service.getApplicationContext(); if (AppSettings.isDebugMode(context)) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import java.util.ArrayList; import java.util.Arrays; import android.content.Context; import android.database.MatrixCursor; import android.database.MatrixCursor.RowBuilder; import android.media.MediaPlayer; import android.net.Uri; import android.provider.BaseColumns; import android.provider.MediaStore.MediaColumns; import android.util.AttributeSet; import android.view.View; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView; public class MediaSongsView extends MediaListView implements OnItemClickListener { private final String[] songsColumns = new String[] { MediaColumns.TITLE, }; final int[] songsResIDs = new int[] { R.id.media_value, }; public MediaSongsView(Context context) { this(context, null); } public MediaSongsView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MediaSongsView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); overrideSortOrder(MediaColumns.TITLE + " ASC"); } public void query(Uri contentUri) { query(contentUri, null); } public void query(Uri contentUri, String selection) { super.query(contentUri, MediaColumns.TITLE, selection, R.layout.media_picker_row, songsColumns, songsResIDs); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { super.onItemClick(parent, view, position, id); MediaPlayer mPlayer = getMediaPlayer(); if (mPlayer == null) { return; } mPlayer.reset(); try { mPlayer.setDataSource(getContext(), getLastSelectedUri()); mPlayer.prepare(); mPlayer.start(); } catch (Exception e) { e.printStackTrace(); } } public void includeDefault() { final ArrayList<String> defaultColumns = new ArrayList<String>(songsColumns.length + 1); defaultColumns.addAll(Arrays.asList(songsColumns)); defaultColumns.add(BaseColumns._ID); final MatrixCursor defaultsCursor = new MatrixCursor(defaultColumns.toArray(new String[] {})); RowBuilder row = defaultsCursor.newRow(); row.add("Default"); row.add(DEFAULT_TONE_INDEX); includeStaticCursor(defaultsCursor); } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import android.content.Context; import android.util.AttributeSet; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.DecelerateInterpolator; import android.view.animation.TranslateAnimation; import android.view.animation.Animation.AnimationListener; import android.widget.ImageView; import android.widget.TextView; import android.widget.ImageView.ScaleType; /** * Widget that contains a slider bar used for acknowledgments. The user * must slide an arrow sufficiently far enough across the bar in order * to trigger the acknowledgment. */ public class Slider extends ViewGroup { public interface OnCompleteListener { void complete(); } private static final int FADE_MILLIS = 200; private static final int SLIDE_MILLIS = 200; private static final float SLIDE_ACCEL = (float) 1.0; private static final double PERCENT_REQUIRED = 0.72; private ImageView dot; private TextView tray; private boolean tracking; private OnCompleteListener completeListener; public Slider(Context context) { this(context, null, 0); } public Slider(Context context, AttributeSet attrs) { this(context, attrs, 0); } public Slider(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // Setup the background which 'holds' the slider. tray = new TextView(getContext()); tray.setBackgroundResource(R.drawable.slider_background); tray.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); tray.setGravity(Gravity.CENTER); tray.setTextAppearance(getContext(), R.style.SliderText); tray.setText(R.string.dismiss); addView(tray); // Setup the object which will be slid. dot = new ImageView(getContext()); dot.setImageResource(R.drawable.slider_icon); dot.setBackgroundResource(R.drawable.slider_btn); dot.setScaleType(ScaleType.CENTER); dot.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); dot.setPadding(30, 10, 25, 15); addView(dot); reset(); } public void setOnCompleteListener(OnCompleteListener listener) { completeListener = listener; } public void reset() { tracking = false; // Move the dot home and fade in. if (getVisibility() != View.VISIBLE) { dot.offsetLeftAndRight(getLeft() - dot.getLeft()); setVisibility(View.VISIBLE); Animation fadeIn = new AlphaAnimation(0, 1); fadeIn.setDuration(FADE_MILLIS); startAnimation(fadeIn); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { if (!changed) { return; } // Start the dot left-aligned. dot.layout(0, 0, dot.getMeasuredWidth(), dot.getMeasuredHeight()); // Make the tray fill the background. tray.layout(0, 0, getMeasuredWidth(), getMeasuredHeight()); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { tray.measure(widthMeasureSpec, heightMeasureSpec); dot.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), heightMeasureSpec); setMeasuredDimension( Math.max(tray.getMeasuredWidth(), dot.getMeasuredWidth()), Math.max(tray.getMeasuredHeight(), dot.getMeasuredHeight())); } private boolean withinX(View v, float x) { if (x < v.getLeft() || x > v.getRight()) { return false; } else { return true; } } private boolean withinY(View v, float y) { if (y < v.getTop() || y > v.getBottom()) { return false; } else { return true; } } private void slideDotHome() { int distanceFromStart = dot.getLeft() - getLeft(); dot.offsetLeftAndRight(-distanceFromStart); Animation slideBack = new TranslateAnimation(distanceFromStart, 0, 0, 0); slideBack.setDuration(SLIDE_MILLIS); slideBack.setInterpolator(new DecelerateInterpolator(SLIDE_ACCEL)); dot.startAnimation(slideBack); } private boolean isComplete() { double dotCenterY = dot.getLeft() + dot.getMeasuredWidth()/2.0; float progressPercent = (float)(dotCenterY - getLeft()) / (float)(getRight() - getLeft()); if (progressPercent > PERCENT_REQUIRED) { return true; } else { return false; } } private void finishSlider() { setVisibility(View.INVISIBLE); Animation fadeOut = new AlphaAnimation(1, 0); fadeOut.setDuration(FADE_MILLIS); fadeOut.setAnimationListener(new AnimationListener() { @Override public void onAnimationEnd(Animation animation) { if (completeListener != null) { completeListener.complete(); } } @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationStart(Animation animation) {} }); startAnimation(fadeOut); } @Override public boolean onTouchEvent(MotionEvent event) { final int action = event.getAction(); final float x = event.getX(); final float y = event.getY(); switch (action) { case MotionEvent.ACTION_DOWN: // Start tracking if the down event is in the dot. tracking = withinX(dot, x) && withinY(dot, y); return tracking || super.onTouchEvent(event); case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: // Ignore move events which did not originate in the dot. if (!tracking) { return super.onTouchEvent(event); } // The dot has been released, check to see if we've hit the threshold, // otherwise, send the dot home. tracking = false; if (isComplete()) { finishSlider(); } else { slideDotHome(); } return true; case MotionEvent.ACTION_MOVE: // Ignore move events which did not originate in the dot. if (!tracking) { return super.onTouchEvent(event); } // Update the current location. dot.offsetLeftAndRight((int) (x - dot.getLeft() - dot.getWidth()/2.0 )); // See if we have reached the threshold. if (isComplete()) { tracking = false; finishSlider(); return true; } // Otherwise, we have not yet hit the completion threshold. Make sure // the move is still within bounds of the dot and redraw. if (!withinY(dot, y)) { // Slid out of the slider, reset to the beginning. tracking = false; slideDotHome(); } else { invalidate(); } return true; default: return super.onTouchEvent(event); } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import java.util.TreeMap; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; /** * This container holds a list of all currently scheduled alarms. * Adding/removing alarms to this container schedules/unschedules PendingIntents * with the android AlarmManager service. */ public final class PendingAlarmList { // Maps alarmId -> alarm. private TreeMap<Long, PendingAlarm> pendingAlarms; // Maps alarm time -> alarmId. private TreeMap<AlarmTime, Long> alarmTimes; private AlarmManager alarmManager; private Context context; public PendingAlarmList(Context context) { pendingAlarms = new TreeMap<Long, PendingAlarm>(); alarmTimes = new TreeMap<AlarmTime, Long>(); alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); this.context = context; } public int size() { if (pendingAlarms.size() != alarmTimes.size()) { throw new IllegalStateException("Inconsistent pending alarms: " + pendingAlarms.size() + " vs " + alarmTimes.size()); } return pendingAlarms.size(); } public void put(long alarmId, AlarmTime time) { // Remove this alarm if it exists already. remove(alarmId); // Intents are considered equal if they have the same action, data, type, // class, and categories. In order to schedule multiple alarms, every // pending intent must be different. This means that we must encode // the alarm id in the data section of the intent rather than in // the extras bundle. Intent notifyIntent = new Intent(context, ReceiverAlarm.class); notifyIntent.setData(AlarmUtil.alarmIdToUri(alarmId)); PendingIntent scheduleIntent = PendingIntent.getBroadcast(context, 0, notifyIntent, 0); // Previous instances of this intent will be overwritten in // the alarm manager. alarmManager.set(AlarmManager.RTC_WAKEUP, time.calendar().getTimeInMillis(), scheduleIntent); // Keep track of all scheduled alarms. pendingAlarms.put(alarmId, new PendingAlarm(time, scheduleIntent)); alarmTimes.put(time, alarmId); if (pendingAlarms.size() != alarmTimes.size()) { throw new IllegalStateException("Inconsistent pending alarms: " + pendingAlarms.size() + " vs " + alarmTimes.size()); } } public boolean remove(long alarmId) { PendingAlarm alarm = pendingAlarms.remove(alarmId); if (alarm == null) { return false; } Long expectedAlarmId = alarmTimes.remove(alarm.time()); alarmManager.cancel(alarm.pendingIntent()); alarm.pendingIntent().cancel(); if (expectedAlarmId != alarmId) { throw new IllegalStateException("Internal inconsistency in PendingAlarmList"); } if (pendingAlarms.size() != alarmTimes.size()) { throw new IllegalStateException("Inconsistent pending alarms: " + pendingAlarms.size() + " vs " + alarmTimes.size()); } return true; } public AlarmTime nextAlarmTime() { if (alarmTimes.size() == 0) { return null; } return alarmTimes.firstKey(); } public AlarmTime pendingTime(long alarmId) { PendingAlarm alarm = pendingAlarms.get(alarmId); return alarm == null ? null : alarm.time(); } public AlarmTime[] pendingTimes() { AlarmTime[] times = new AlarmTime[alarmTimes.size()]; alarmTimes.keySet().toArray(times); return times; } public Long[] pendingAlarms() { Long[] alarmIds = new Long[pendingAlarms.size()]; pendingAlarms.keySet().toArray(alarmIds); return alarmIds; } private class PendingAlarm { private AlarmTime time; private PendingIntent pendingIntent; PendingAlarm(AlarmTime time, PendingIntent pendingIntent) { this.time = time; this.pendingIntent = pendingIntent; } public AlarmTime time() { return time; } public PendingIntent pendingIntent() { return pendingIntent; } } }
Java
package com.angrydoughnuts.android.alarmclock; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class RecevierTimeZoneChange extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent i = new Intent(context, AlarmClockService.class); i.putExtra(AlarmClockService.COMMAND_EXTRA, AlarmClockService.COMMAND_TIMEZONE_CHANGE); context.startService(i); } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import java.lang.reflect.Field; import android.net.Uri; import android.provider.Settings; public final class AlarmUtil { static public Uri alarmIdToUri(long alarmId) { return Uri.parse("alarm_id:" + alarmId); } public static long alarmUriToId(Uri uri) { return Long.parseLong(uri.getSchemeSpecificPart()); } enum Interval { SECOND(1000), MINUTE(60 * 1000), HOUR(60 * 60 * 1000); private long millis; public long millis() { return millis; } Interval(long millis) { this.millis = millis; } } public static long millisTillNextInterval(Interval interval) { long now = System.currentTimeMillis(); return interval.millis() - now % interval.millis(); } public static long nextIntervalInUTC(Interval interval) { long now = System.currentTimeMillis(); return now + interval.millis() - now % interval.millis(); } public static Uri getDefaultAlarmUri() { // DEFAULT_ALARM_ALERT_URI is only available after SDK version 5. // Fall back to the default notification if the default alarm is // unavailable. try { Field f = Settings.System.class.getField("DEFAULT_ALARM_ALERT_URI"); return (Uri) f.get(null); } catch (Exception e) { return Settings.System.DEFAULT_NOTIFICATION_URI; } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import java.util.LinkedList; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.os.RemoteException; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.TextView; /** * This adapter is used to query the alarm database and translate each alarm * into a view which is displayed in a ListView. */ public final class AlarmViewAdapter extends ArrayAdapter<AlarmInfo> { private AlarmClockServiceBinder service; private LayoutInflater inflater; private Cursor cursor; public AlarmViewAdapter(Activity activity, DbAccessor db, AlarmClockServiceBinder service) { super(activity, 0, new LinkedList<AlarmInfo>()); this.service = service; this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.cursor = db.readAlarmInfo(); activity.startManagingCursor(cursor); loadData(); } private void loadData() { while (cursor.moveToNext()) { add(new AlarmInfo(cursor)); } } public void requery() { clear(); cursor.requery(); loadData(); notifyDataSetChanged(); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = inflater.inflate(R.layout.alarm_list_item, null); TextView timeView = (TextView) view.findViewById(R.id.alarm_time); TextView nextView = (TextView) view.findViewById(R.id.next_alarm); TextView labelView = (TextView) view.findViewById(R.id.alarm_label); TextView repeatView = (TextView) view.findViewById(R.id.alarm_repeat); CheckBox enabledView = (CheckBox) view.findViewById(R.id.alarm_enabled); final AlarmInfo info = getItem(position); AlarmTime time = null; // See if there is an instance of this alarm scheduled. if (service.clock() != null) { try { time = service.clock().pendingAlarm(info.getAlarmId()); } catch (RemoteException e) {} } // If we couldn't find a pending alarm, display the configured time. if (time == null) { time = info.getTime(); } String timeStr = time.localizedString(getContext()); String alarmId = ""; if (AppSettings.isDebugMode(getContext())) { alarmId = " [" + info.getAlarmId() + "]"; } timeView.setText(timeStr + alarmId); enabledView.setChecked(info.enabled()); nextView.setText(time.timeUntilString(getContext())); labelView.setText(info.getName()); if (!info.getTime().getDaysOfWeek().equals(Week.NO_REPEATS)) { repeatView.setText(info.getTime().getDaysOfWeek().toString(getContext())); } enabledView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { CheckBox check = (CheckBox) v; if (check.isChecked()) { service.scheduleAlarm(info.getAlarmId()); requery(); } else { service.unscheduleAlarm(info.getAlarmId()); requery(); } } }); return view; } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.preference.PreferenceManager; /** * Utility class for accessing each of the global application settings. */ public final class AppSettings { // Some of these have an extra " in them because of an old copy/paste bug. // They are forever ingrained in the settings :-( public static final String DEBUG_MODE = "DEBUG_MODE"; public static final String NOTIFICATION_ICON = "NOTIFICATION_ICON"; public static final String LOCK_SCREEN = "LOCK_SCREEN"; public static final String CUSTOM_LOCK_SCREEN_TEXT = "CUSTOM_LOCK_SCREEN"; public static final String CUSTOM_LOCK_SCREEN_PERSISTENT = "CUSTOM_LOCK_PERSISTENT"; public static final String ALARM_TIMEOUT = "ALARM_TIMEOUT"; public static final boolean displayNotificationIcon(Context c) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); return prefs.getBoolean(NOTIFICATION_ICON, true); } private static final String FORMAT_COUNTDOWN = "%c"; private static final String FORMAT_TIME = "%t"; private static final String FORMAT_BOTH = "%c (%t)"; public static final String lockScreenString(Context c, AlarmTime nextTime) { final String[] values = c.getResources().getStringArray(R.array.lock_screen_values); final String LOCK_SCREEN_COUNTDOWN = values[0]; final String LOCK_SCREEN_TIME = values[1]; final String LOCK_SCREEN_BOTH = values[2]; final String LOCK_SCREEN_NOTHING = values[3]; final String LOCK_SCREEN_CUSTOM = values[4]; final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); final String value = prefs.getString(LOCK_SCREEN, LOCK_SCREEN_COUNTDOWN); final String customFormat = prefs.getString(CUSTOM_LOCK_SCREEN_TEXT, FORMAT_COUNTDOWN); // The lock screen message should be persistent iff the persistent setting // is set AND a custom lock screen message is set. final boolean persistent = prefs.getBoolean(CUSTOM_LOCK_SCREEN_PERSISTENT, false) && value.equals(LOCK_SCREEN_CUSTOM); if (value.equals(LOCK_SCREEN_NOTHING)) { return null; } // If no alarm is set and our lock message is not persistent, return // a clearing string. if (nextTime == null && !persistent) { return ""; } String time = ""; String countdown = ""; if (nextTime != null) { time = nextTime.localizedString(c); countdown = nextTime.timeUntilString(c); } String text; if (value.equals(LOCK_SCREEN_COUNTDOWN)) { text = FORMAT_COUNTDOWN; } else if (value.equals(LOCK_SCREEN_TIME)) { text = FORMAT_TIME; } else if (value.equals(LOCK_SCREEN_BOTH)) { text = FORMAT_BOTH; } else if (value.equals(LOCK_SCREEN_CUSTOM)) { text = customFormat; } else { throw new IllegalStateException("Unknown lockscreen preference: " + value); } text = text.replace("%t", time); text = text.replace("%c", countdown); return text; } public static final boolean isDebugMode(Context c) { final String[] values = c.getResources().getStringArray(R.array.debug_values); final String DEBUG_DEFAULT = values[0]; final String DEBUG_ON = values[1]; final String DEBUG_OFF = values[2]; final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); final String value = prefs.getString(DEBUG_MODE, DEBUG_DEFAULT); if (value.equals(DEBUG_ON)) { return true; } else if (value.equals(DEBUG_OFF)) { return false; } else if (value.equals(DEBUG_DEFAULT)) { return (c.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) > 0; } else { throw new IllegalStateException("Unknown debug mode setting: "+ value); } } public static final int alarmTimeOutMins(Context c) { final String[] values = c.getResources().getStringArray(R.array.time_out_values); final String ONE_MIN = values[0]; final String FIVE_MIN = values[1]; final String TEN_MIN = values[2]; final String THIRTY_MIN = values[3]; final String SIXTY_MIN = values[4]; final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); final String value = prefs.getString(ALARM_TIMEOUT, TEN_MIN); if (value.equals(ONE_MIN)) { return 1; } else if (value.equals(FIVE_MIN)) { return 5; } else if (value.equals(TEN_MIN)) { return 10; } else if (value.equals(THIRTY_MIN)) { return 30; } else if (value.equals(SIXTY_MIN)) { return 60; } else { return 10; } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import java.util.Map; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.preference.PreferenceManager; import android.provider.Settings; import android.widget.Toast; public final class AlarmClockService extends Service { public final static String COMMAND_EXTRA = "command"; public final static int COMMAND_UNKNOWN = 1; public final static int COMMAND_NOTIFICATION_REFRESH = 2; public final static int COMMAND_DEVICE_BOOT = 3; public final static int COMMAND_TIMEZONE_CHANGE = 4; public final static int NOTIFICATION_BAR_ID = 69; private DbAccessor db; private PendingAlarmList pendingAlarms; private Notification notification; @Override public void onCreate() { super.onCreate(); // Registers an exception handler of capable of writing the stack trace // to the device's SD card. This is only possible if the proper // permissions are available. if (getPackageManager().checkPermission( "android.permission.WRITE_EXTERNAL_STORAGE", getPackageName()) == PackageManager.PERMISSION_GRANTED) { Thread.setDefaultUncaughtExceptionHandler( new LoggingUncaughtExceptionHandler("/sdcard")); } // Access to in-memory and persistent data structures. db = new DbAccessor(getApplicationContext()); pendingAlarms = new PendingAlarmList(getApplicationContext()); // Schedule enabled alarms during initial startup. for (Long alarmId : db.getEnabledAlarms()) { if (pendingAlarms.pendingTime(alarmId) != null) { continue; } if (AppSettings.isDebugMode(getApplicationContext())) { Toast.makeText(getApplicationContext(), "RENABLE " + alarmId, Toast.LENGTH_SHORT).show(); } pendingAlarms.put(alarmId, db.readAlarmInfo(alarmId).getTime()); } notification = new Notification(R.drawable.alarmclock_notification, null, 0); notification.flags |= Notification.FLAG_ONGOING_EVENT; ReceiverNotificationRefresh.startRefreshing(getApplicationContext()); } // OnStart was depreciated in SDK 5. It is here for backwards compatibility. // http://android-developers.blogspot.com/2010/02/service-api-changes-starting-with.html @Override public void onStart(Intent intent, int startId) { handleStart(intent, startId); } @Override public int onStartCommand(Intent intent, int flags, int startId) { handleStart(intent, startId); return START_STICKY; } private void handleStart(Intent intent, int startId) { if (intent != null && intent.hasExtra(COMMAND_EXTRA)) { Bundle extras = intent.getExtras(); int command = extras.getInt(COMMAND_EXTRA, COMMAND_UNKNOWN); final Handler handler = new Handler(); final Runnable maybeShutdown = new Runnable() { @Override public void run() { if (pendingAlarms.size() == 0) { stopSelf(); } } }; switch (command) { case COMMAND_NOTIFICATION_REFRESH: refreshNotification(); handler.post(maybeShutdown); break; case COMMAND_DEVICE_BOOT: fixPersistentSettings(); handler.post(maybeShutdown); break; case COMMAND_TIMEZONE_CHANGE: if (AppSettings.isDebugMode(getApplicationContext())) { Toast.makeText(getApplicationContext(), "TIMEZONE CHANGE, RESCHEDULING...", Toast.LENGTH_SHORT).show(); } for (long alarmId : pendingAlarms.pendingAlarms()) { scheduleAlarm(alarmId); if (AppSettings.isDebugMode(getApplicationContext())) { Toast.makeText(getApplicationContext(), "ALARM " + alarmId, Toast.LENGTH_SHORT).show(); } } handler.post(maybeShutdown); break; default: throw new IllegalArgumentException("Unknown service command."); } } } private void refreshNotification() { AlarmTime nextTime = pendingAlarms.nextAlarmTime(); String nextString; if (nextTime != null) { nextString = getString(R.string.next_alarm) + " " + nextTime.localizedString(getApplicationContext()) + " (" + nextTime.timeUntilString(getApplicationContext()) + ")"; } else { nextString = getString(R.string.no_pending_alarms); } // Make the notification launch the UI Activity when clicked. final Intent notificationIntent = new Intent(this, ActivityAlarmClock.class); final PendingIntent launch = PendingIntent.getActivity(this, 0, notificationIntent, 0); Context c = getApplicationContext(); notification.setLatestEventInfo(c, getString(R.string.app_name), nextString, launch); final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (pendingAlarms.size() > 0 && AppSettings.displayNotificationIcon(c)) { manager.notify(NOTIFICATION_BAR_ID, notification); } else { manager.cancel(NOTIFICATION_BAR_ID); } // Set the system alarm string for display on the lock screen. String lockScreenText = AppSettings.lockScreenString(getApplicationContext(), nextTime); if (lockScreenText != null) { Settings.System.putString(getContentResolver(), Settings.System.NEXT_ALARM_FORMATTED, lockScreenText); } } // This hack is necessary b/c I released a version of the code with a bunch // of errors in the settings strings. This should correct them. public void fixPersistentSettings() { final String badDebugName = "DEBUG_MODE\""; final String badNotificationName = "NOTFICATION_ICON"; final String badLockScreenName = "LOCK_SCREEN\""; final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); Map<String, ?> prefNames = prefs.getAll(); // Don't do anything if the bad preferences have already been fixed. if (!prefNames.containsKey(badDebugName) && !prefNames.containsKey(badNotificationName) && !prefNames.containsKey(badLockScreenName)) { return; } Editor editor = prefs.edit(); if (prefNames.containsKey(badDebugName)) { editor.putString(AppSettings.DEBUG_MODE, prefs.getString(badDebugName, null)); editor.remove(badDebugName); } if (prefNames.containsKey(badNotificationName)){ editor.putBoolean(AppSettings.NOTIFICATION_ICON, prefs.getBoolean(badNotificationName, true)); editor.remove(badNotificationName); } if (prefNames.containsKey(badLockScreenName)) { editor.putString(AppSettings.LOCK_SCREEN, prefs.getString(badLockScreenName, null)); editor.remove(badLockScreenName); } editor.commit(); } @Override public void onDestroy() { super.onDestroy(); db.closeConnections(); ReceiverNotificationRefresh.stopRefreshing(getApplicationContext()); final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.cancel(NOTIFICATION_BAR_ID); String lockScreenText = AppSettings.lockScreenString(getApplicationContext(), null); // Only clear the lock screen if the preference is set. if (lockScreenText != null) { Settings.System.putString(getContentResolver(), Settings.System.NEXT_ALARM_FORMATTED, lockScreenText); } } @Override public IBinder onBind(Intent intent) { return new AlarmClockInterfaceStub(getApplicationContext(), this); } @Override public boolean onUnbind(Intent intent) { // Decide if we need to explicitly shut down this service. Normally, // the service would shutdown after the last un-bind, but it was explicitly // started in onBind(). If there are no pending alarms, explicitly stop // the service. if (pendingAlarms.size() == 0) { stopSelf(); return false; } // Returning true causes the IBinder object to be re-used until the // service is actually shutdown. return true; } public AlarmTime pendingAlarm(long alarmId) { return pendingAlarms.pendingTime(alarmId); } public AlarmTime[] pendingAlarmTimes() { return pendingAlarms.pendingTimes(); } public void createAlarm(AlarmTime time) { // Store the alarm in the persistent database. long alarmId = db.newAlarm(time); scheduleAlarm(alarmId); } public void deleteAlarm(long alarmId) { pendingAlarms.remove(alarmId); db.deleteAlarm(alarmId); } public void deleteAllAlarms() { for (Long alarmId : db.getAllAlarms()) { deleteAlarm(alarmId); } } public void scheduleAlarm(long alarmId) { AlarmInfo info = db.readAlarmInfo(alarmId); if (info == null) { return; } // Schedule the next alarm. pendingAlarms.put(alarmId, info.getTime()); // Mark the alarm as enabled in the database. db.enableAlarm(alarmId, true); // Now that there is more than one pending alarm, explicitly start the // service so that it continues to run after binding. final Intent self = new Intent(getApplicationContext(), AlarmClockService.class); startService(self); refreshNotification(); } public void acknowledgeAlarm(long alarmId) { AlarmInfo info = db.readAlarmInfo(alarmId); if (info == null) { return; } pendingAlarms.remove(alarmId); AlarmTime time = info.getTime(); if (time.repeats()) { pendingAlarms.put(alarmId, time); } else { db.enableAlarm(alarmId, false); } refreshNotification(); } public void dismissAlarm(long alarmId) { AlarmInfo info = db.readAlarmInfo(alarmId); if (info == null) { return; } pendingAlarms.remove(alarmId); db.enableAlarm(alarmId, false); refreshNotification(); } public void snoozeAlarm(long alarmId) { snoozeAlarmFor(alarmId, db.readAlarmSettings(alarmId).getSnoozeMinutes()); } public void snoozeAlarmFor(long alarmId, int minutes) { // Clear the snoozed alarm. pendingAlarms.remove(alarmId); // Calculate the time for the next alarm. AlarmTime time = AlarmTime.snoozeInMillisUTC(minutes); // Schedule it. pendingAlarms.put(alarmId, time); refreshNotification(); } }
Java
package com.angrydoughnuts.android.alarmclock; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class ReceiverDeviceBoot extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // There doesn't seem to be any way to filter on the scheme-specific // portion of the ACTION_PACKANGE_REPLACED intent (the package // being replaced is in the ssp). Since we can't filter for it in the // Manifest file, we get every package replaced event and cancel this // event if it's not our package. if (intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)) { if (!intent.getData().getSchemeSpecificPart().equals(context.getPackageName())) { return; } } Intent i = new Intent(context, AlarmClockService.class); i.putExtra(AlarmClockService.COMMAND_EXTRA, AlarmClockService.COMMAND_DEVICE_BOOT); context.startService(i); } }
Java
package com.angrydoughnuts.android.alarmclock; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class ReceiverNotificationRefresh extends BroadcastReceiver { public static void startRefreshing(Context context) { context.sendBroadcast(intent(context)); } public static void stopRefreshing(Context context) { final AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); manager.cancel(pendingIntent(context)); } private static Intent intent(Context context) { return new Intent(context, ReceiverNotificationRefresh.class); } private static PendingIntent pendingIntent(Context context) { return PendingIntent.getBroadcast(context, 0, intent(context), 0); } @Override public void onReceive(Context context, Intent intent) { final Intent causeRefresh = new Intent(context, AlarmClockService.class); causeRefresh.putExtra(AlarmClockService.COMMAND_EXTRA, AlarmClockService.COMMAND_NOTIFICATION_REFRESH); context.startService(causeRefresh); long next = AlarmUtil.nextIntervalInUTC(AlarmUtil.Interval.MINUTE); final AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); manager.set(AlarmManager.RTC, next, pendingIntent(context)); } }
Java
package com.angrydoughnuts.android.alarmclock; import java.util.TreeMap; import android.content.Context; import android.os.PowerManager; public class WakeLock { public static class WakeLockException extends Exception { private static final long serialVersionUID = 1L; public WakeLockException(String e) { super(e); } } private static final TreeMap<Long, PowerManager.WakeLock> wakeLocks = new TreeMap<Long, PowerManager.WakeLock>(); public static final void acquire(Context context, long alarmId) throws WakeLockException { if (wakeLocks.containsKey(alarmId)) { throw new WakeLockException("Multiple acquisitions of wake lock for id: " + alarmId); } PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wakeLock = powerManager.newWakeLock( PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "Alarm Notification Wake Lock id " + alarmId); wakeLock.setReferenceCounted(false); wakeLock.acquire(); wakeLocks.put(alarmId, wakeLock); } public static final void assertHeld(long alarmId) throws WakeLockException { PowerManager.WakeLock wakeLock = wakeLocks.get(alarmId); if (wakeLock == null || !wakeLock.isHeld()) { throw new WakeLockException("Wake lock not held for alarm id: " + alarmId); } } public static final void assertAtLeastOneHeld() throws WakeLockException { for (PowerManager.WakeLock wakeLock : wakeLocks.values()) { if (wakeLock.isHeld()) { return; } } throw new WakeLockException("No wake locks are held."); } public static final void assertNoneHeld() throws WakeLockException { for (PowerManager.WakeLock wakeLock : wakeLocks.values()) { if (wakeLock.isHeld()) { throw new WakeLockException("No wake locks are held."); } } } public static final void release(long alarmId) throws WakeLockException { assertHeld(alarmId); PowerManager.WakeLock wakeLock = wakeLocks.remove(alarmId); wakeLock.release(); } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import android.content.Context; import android.os.RemoteException; import android.widget.Toast; public final class AlarmClockInterfaceStub extends AlarmClockInterface.Stub { private Context context; private AlarmClockService service; AlarmClockInterfaceStub(Context context, AlarmClockService service) { this.context = context; this.service = service; } @Override public AlarmTime pendingAlarm(long alarmId) throws RemoteException { return service.pendingAlarm(alarmId); } @Override public AlarmTime[] pendingAlarmTimes() throws RemoteException { return service.pendingAlarmTimes(); } @Override public void createAlarm(AlarmTime time) throws RemoteException { debugToast("CREATE ALARM " + time.toString()); service.createAlarm(time); } @Override public void deleteAlarm(long alarmId) throws RemoteException { debugToast("DELETE ALARM " + alarmId); service.deleteAlarm(alarmId); } @Override public void deleteAllAlarms() throws RemoteException { debugToast("DELETE ALL ALARMS"); service.deleteAllAlarms(); } @Override public void scheduleAlarm(long alarmId) throws RemoteException { debugToast("SCHEDULE ALARM " + alarmId); service.scheduleAlarm(alarmId); } @Override public void unscheduleAlarm(long alarmId) { debugToast("UNSCHEDULE ALARM " + alarmId); service.dismissAlarm(alarmId); } public void acknowledgeAlarm(long alarmId) { debugToast("ACKNOWLEDGE ALARM " + alarmId); service.acknowledgeAlarm(alarmId); } @Override public void snoozeAlarm(long alarmId) throws RemoteException { debugToast("SNOOZE ALARM " + alarmId); service.snoozeAlarm(alarmId); } @Override public void snoozeAlarmFor(long alarmId, int minutes) throws RemoteException { debugToast("SNOOZE ALARM " + alarmId + " for " + minutes); service.snoozeAlarmFor(alarmId, minutes); } private void debugToast(String message) { if (AppSettings.isDebugMode(context)) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import com.angrydoughnuts.android.alarmclock.MediaListView.OnItemPickListener; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.media.MediaPlayer; import android.net.Uri; import android.os.Message; import android.provider.MediaStore.Audio.Albums; import android.provider.MediaStore.Audio.Artists; import android.provider.MediaStore.Audio.Media; import android.view.LayoutInflater; import android.view.View; import android.widget.TabHost; import android.widget.TextView; import android.widget.ViewFlipper; import android.widget.TabHost.OnTabChangeListener; /** * A dialog which displays all of the audio media available on the phone. * It allows you to access media through 4 tabs: One that lists media * stored internally on the phone, and three that allow you to access * the media stored on the SD card. These three tabs allow you to browse by * artist, album, and song. */ public class MediaPickerDialog extends AlertDialog { public interface OnMediaPickListener { public void onMediaPick(String name, Uri media); } private final String INTERNAL_TAB = "internal"; private final String ARTISTS_TAB = "artists"; private final String ALBUMS_TAB = "albums"; private final String ALL_SONGS_TAB = "songs"; private String selectedName; private Uri selectedUri; private OnMediaPickListener pickListener; private MediaPlayer mediaPlayer; public MediaPickerDialog(final Activity context) { super(context); mediaPlayer = new MediaPlayer(); final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View body_view = inflater.inflate(R.layout.media_picker_dialog, null); setView(body_view); TabHost tabs = (TabHost) body_view.findViewById(R.id.media_tabs); tabs.setup(); tabs.addTab(tabs.newTabSpec(INTERNAL_TAB).setContent(R.id.media_picker_internal).setIndicator(context.getString(R.string.internal))); tabs.addTab(tabs.newTabSpec(ARTISTS_TAB).setContent(R.id.media_picker_artists).setIndicator(context.getString(R.string.artists))); tabs.addTab(tabs.newTabSpec(ALBUMS_TAB).setContent(R.id.media_picker_albums).setIndicator(context.getString(R.string.albums))); tabs.addTab(tabs.newTabSpec(ALL_SONGS_TAB).setContent(R.id.media_picker_songs).setIndicator(context.getString(R.string.songs))); final TextView lastSelected = (TextView) body_view.findViewById(R.id.media_picker_status); final OnItemPickListener listener = new OnItemPickListener() { @Override public void onItemPick(Uri uri, String name) { selectedUri = uri; selectedName = name; lastSelected.setText(name); } }; final MediaSongsView internalList = (MediaSongsView) body_view.findViewById(R.id.media_picker_internal); internalList.setCursorManager(context); internalList.includeDefault(); internalList.query(Media.INTERNAL_CONTENT_URI); internalList.setMediaPlayer(mediaPlayer); internalList.setMediaPickListener(listener); final MediaSongsView songsList = (MediaSongsView) body_view.findViewById(R.id.media_picker_songs); songsList.setCursorManager(context); songsList.query(Media.EXTERNAL_CONTENT_URI); songsList.setMediaPlayer(mediaPlayer); songsList.setMediaPickListener(listener); final ViewFlipper artistsFlipper = (ViewFlipper) body_view.findViewById(R.id.media_picker_artists); final MediaArtistsView artistsList = new MediaArtistsView(context); artistsList.setCursorManager(context); artistsList.addToFlipper(artistsFlipper); artistsList.query(Artists.EXTERNAL_CONTENT_URI); artistsList.setMediaPlayer(mediaPlayer); artistsList.setMediaPickListener(listener); final ViewFlipper albumsFlipper = (ViewFlipper) body_view.findViewById(R.id.media_picker_albums); final MediaAlbumsView albumsList = new MediaAlbumsView(context); albumsList.setCursorManager(context); albumsList.addToFlipper(albumsFlipper); albumsList.query(Albums.EXTERNAL_CONTENT_URI); albumsList.setMediaPlayer(mediaPlayer); albumsList.setMediaPickListener(listener); tabs.setOnTabChangedListener(new OnTabChangeListener() { @Override public void onTabChanged(String tabId) { if (tabId.equals(ARTISTS_TAB)) { artistsFlipper.setDisplayedChild(0); } else if (tabId.equals(ALBUMS_TAB)) { albumsFlipper.setDisplayedChild(0); } } }); super.setButton(BUTTON_POSITIVE, getContext().getString(R.string.ok), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (selectedUri == null || pickListener == null) { cancel(); return; } pickListener.onMediaPick(selectedName, selectedUri); } }); super.setButton(BUTTON_NEGATIVE, getContext().getString(R.string.cancel), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { selectedName = null; selectedUri = null; lastSelected.setText(""); cancel(); } }); } public void setPickListener(OnMediaPickListener listener) { this.pickListener = listener; } @Override protected void onStop() { super.onStop(); mediaPlayer.stop(); } @Override protected void finalize() throws Throwable { mediaPlayer.release(); super.finalize(); } // Make these no-ops and final so the buttons can't be overridden buy the // user nor a child. @Override public void setButton(CharSequence text, Message msg) { } @Override public final void setButton(CharSequence text, OnClickListener listener) {} @Override public final void setButton(int whichButton, CharSequence text, Message msg) {} @Override public final void setButton(int whichButton, CharSequence text, OnClickListener listener) {} @Override public final void setButton2(CharSequence text, Message msg) {} @Override public final void setButton2(CharSequence text, OnClickListener listener) {} @Override public final void setButton3(CharSequence text, Message msg) {} @Override public final void setButton3(CharSequence text, OnClickListener listener) {} }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import com.angrydoughnuts.android.alarmclock.MediaPickerDialog.OnMediaPickListener; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnMultiChoiceClickListener; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; /** * This activity is used for editing alarm settings. Settings are broken * into two pieces: alarm information and actual settings. Every alarm will * have alarm information. Alarms will only have alarm settings if the user * has overridden the default settings for a given alarm. This dialog is used * to edit both the application default settings and individual alarm settings. * When editing the application default settings, no AlarmInfo object will * be present. When editing an alarm which hasn't yet had specific settings * set, AlarmSettings will contain the default settings. There is one required * EXTRA that must be supplied when starting this activity: EXTRAS_ALARM_ID, * which should contain a long representing the alarmId of the settings * being edited. AlarmSettings.DEFAULT_SETTINGS_ID can be used to edit the * default settings. */ public final class ActivityAlarmSettings extends Activity { public static final String EXTRAS_ALARM_ID = "alarm_id"; private final int MISSING_EXTRAS = -69; private enum SettingType { TIME, NAME, DAYS_OF_WEEK, TONE, SNOOZE, VIBRATE, VOLUME_FADE; } private enum Dialogs { TIME_PICKER, NAME_PICKER, DOW_PICKER, TONE_PICKER, SNOOZE_PICKER, VOLUME_FADE_PICKER, DELETE_CONFIRM } private long alarmId; private AlarmClockServiceBinder service; private DbAccessor db; private AlarmInfo originalInfo; private AlarmInfo info; private AlarmSettings originalSettings; private AlarmSettings settings; SettingsAdapter settingsAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.settings); // An alarm id is required in the extras bundle. alarmId = getIntent().getExtras().getLong(EXTRAS_ALARM_ID, MISSING_EXTRAS); if (alarmId == MISSING_EXTRAS) { throw new IllegalStateException("EXTRAS_ALARM_ID not supplied in intent."); } // Access to in-memory and persistent data structures. service = new AlarmClockServiceBinder(getApplicationContext()); db = new DbAccessor(getApplicationContext()); // Read the current settings from the database. Keep a copy of the // original values so that we can write new values only if they differ // from the originals. originalInfo = db.readAlarmInfo(alarmId); // Info will not be available for the default settings. if (originalInfo != null) { info = new AlarmInfo(originalInfo); } originalSettings = db.readAlarmSettings(alarmId); settings = new AlarmSettings(originalSettings); // Setup individual UI elements. // Positive acknowledgment button. final Button okButton = (Button) findViewById(R.id.settings_ok); okButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Write AlarmInfo if it changed. if (originalInfo != null && !originalInfo.equals(info)) { db.writeAlarmInfo(alarmId, info); // Explicitly enable the alarm if the user changed the time. // This will reschedule the alarm if it was already enabled. // It's also probably the right thing to do if the alarm wasn't // enabled. if (!originalInfo.getTime().equals(info.getTime())) { service.scheduleAlarm(alarmId); } } // Write AlarmSettings if they have changed. if (!originalSettings.equals(settings)) { db.writeAlarmSettings(alarmId, settings); } finish(); } }); // Negative acknowledgment button. final Button cancelButton = (Button) findViewById(R.id.settings_cancel); cancelButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); // Delete button. Simply opens a confirmation dialog (which does the // actual delete). Button deleteButton = (Button) findViewById(R.id.settings_delete); deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showDialog(Dialogs.DELETE_CONFIRM.ordinal()); } }); // Setup the list of settings. Each setting is represented by a Setting // object. Create one here for each setting type. final ArrayList<Setting> settingsObjects = new ArrayList<Setting>(SettingType.values().length); // Only display AlarmInfo if the user is editing an actual alarm (as // opposed to the default application settings). if (alarmId != AlarmSettings.DEFAULT_SETTINGS_ID) { // The alarm time. settingsObjects.add(new Setting() { @Override public String name() { return getString(R.string.time); } @Override public String value() { return info.getTime().localizedString(getApplicationContext()); } @Override public SettingType type() { return SettingType.TIME; } }); // A human-readable label for the alarm. settingsObjects.add(new Setting() { @Override public String name() { return getString(R.string.label); } @Override public String value() { return info.getName().equals("") ? getString(R.string.none) : info.getName(); } @Override public SettingType type() { return SettingType.NAME; } }); // Days of the week this alarm should repeat. settingsObjects.add(new Setting() { @Override public String name() { return getString(R.string.repeat); } @Override public String value() { return info.getTime().getDaysOfWeek().toString(getApplicationContext()); } @Override public SettingType type() { return SettingType.DAYS_OF_WEEK; } }); } // The notification tone used for this alarm. settingsObjects.add(new Setting() { @Override public String name() { return getString(R.string.tone); } @Override public String value() { String value = settings.getToneName(); if (AppSettings.isDebugMode(getApplicationContext())) { value += " " + settings.getTone().toString(); } return value; } @Override public SettingType type() { return SettingType.TONE; } }); // The snooze duration for this alarm. settingsObjects.add(new Setting() { @Override public String name() { return getString(R.string.snooze_minutes); } @Override public String value() { return "" + settings.getSnoozeMinutes(); } @Override public SettingType type() { return SettingType.SNOOZE; } }); // The vibrator setting for this alarm. settingsObjects.add(new Setting() { @Override public String name() { return getString(R.string.vibrate); } @Override public String value() { return settings.getVibrate() ? getString(R.string.enabled) : getString(R.string.disabled); } @Override public SettingType type() { return SettingType.VIBRATE; } }); // How the volume should be controlled while this alarm is triggering. settingsObjects.add(new Setting() { @Override public String name() { return getString(R.string.alarm_fade); } @Override public String value() { return getString(R.string.fade_description, settings.getVolumeStartPercent(), settings.getVolumeEndPercent(), settings.getVolumeChangeTimeSec()); } @Override public SettingType type() { return SettingType.VOLUME_FADE; } }); final ListView settingsList = (ListView) findViewById(R.id.settings_list); settingsAdapter = new SettingsAdapter(getApplicationContext(), settingsObjects); settingsList.setAdapter(settingsAdapter); settingsList.setOnItemClickListener(new SettingsListClickListener()); // The delete button should not be shown when editing the default settings. if (alarmId == AlarmSettings.DEFAULT_SETTINGS_ID) { deleteButton.setVisibility(View.GONE); } } @Override protected void onResume() { super.onResume(); service.bind(); } @Override protected void onPause() { super.onPause(); service.unbind(); } @Override protected void onDestroy() { super.onDestroy(); db.closeConnections(); } @Override protected Dialog onCreateDialog(int id) { switch (Dialogs.values()[id]) { case TIME_PICKER: final AlarmTime time = info.getTime(); int hour = time.calendar().get(Calendar.HOUR_OF_DAY); int minute = time.calendar().get(Calendar.MINUTE); int second = time.calendar().get(Calendar.SECOND); return new TimePickerDialog(this, getString(R.string.time), hour, minute, second, AppSettings.isDebugMode(this), new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(int hourOfDay, int minute, int second) { info.setTime(new AlarmTime(hourOfDay, minute, second, time.getDaysOfWeek())); settingsAdapter.notifyDataSetChanged(); // Destroy this dialog so that it does not save its state. removeDialog(Dialogs.TIME_PICKER.ordinal()); } }); case NAME_PICKER: final View nameView = getLayoutInflater().inflate(R.layout.name_settings_dialog, null); final TextView label = (TextView) nameView.findViewById(R.id.name_label); label.setText(info.getName()); final AlertDialog.Builder nameBuilder = new AlertDialog.Builder(this); nameBuilder.setTitle(R.string.alarm_label); nameBuilder.setView(nameView); nameBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { info.setName(label.getEditableText().toString()); settingsAdapter.notifyDataSetChanged(); dismissDialog(Dialogs.NAME_PICKER.ordinal()); } }); nameBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismissDialog(Dialogs.NAME_PICKER.ordinal()); } }); return nameBuilder.create(); case DOW_PICKER: final AlertDialog.Builder dowBuilder = new AlertDialog.Builder(this); dowBuilder.setTitle(R.string.scheduled_days); dowBuilder.setMultiChoiceItems( info.getTime().getDaysOfWeek().names(getApplicationContext()), info.getTime().getDaysOfWeek().bitmask(), new OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { if (isChecked) { info.getTime().getDaysOfWeek().addDay(Week.Day.values()[which]); } else { info.getTime().getDaysOfWeek().removeDay(Week.Day.values()[which]); } } }); dowBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { settingsAdapter.notifyDataSetChanged(); dismissDialog(Dialogs.DOW_PICKER.ordinal()); } }); return dowBuilder.create(); case TONE_PICKER: MediaPickerDialog mediaPicker = new MediaPickerDialog(this); mediaPicker.setPickListener(new OnMediaPickListener() { @Override public void onMediaPick(String name, Uri media) { if (name.length() == 0) { name = getString(R.string.unknown_name); } settings.setTone(media, name); settingsAdapter.notifyDataSetChanged(); } }); return mediaPicker; case SNOOZE_PICKER: // This currently imposes snooze times between 1 and 60 minutes, // which isn't really necessary, but I think the picker is easier // to use than a free-text field that you have to type numbers into. final CharSequence[] items = new CharSequence[60]; // Note the array index is one-off from the value (the value of 1 is // at index 0). for (int i = 1; i <= 60; ++i) { items[i-1] = new Integer(i).toString(); } final AlertDialog.Builder snoozeBuilder = new AlertDialog.Builder(this); snoozeBuilder.setTitle(R.string.snooze_minutes); snoozeBuilder.setSingleChoiceItems(items, settings.getSnoozeMinutes() - 1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { settings.setSnoozeMinutes(item + 1); settingsAdapter.notifyDataSetChanged(); dismissDialog(Dialogs.SNOOZE_PICKER.ordinal()); } }); return snoozeBuilder.create(); case VOLUME_FADE_PICKER: final View fadeView = getLayoutInflater().inflate(R.layout.fade_settings_dialog, null); final EditText volumeStart = (EditText) fadeView.findViewById(R.id.volume_start); volumeStart.setText("" + settings.getVolumeStartPercent()); final EditText volumeEnd = (EditText) fadeView.findViewById(R.id.volume_end); volumeEnd.setText("" + settings.getVolumeEndPercent()); final EditText volumeDuration = (EditText) fadeView.findViewById(R.id.volume_duration); volumeDuration.setText("" + settings.getVolumeChangeTimeSec()); final AlertDialog.Builder fadeBuilder = new AlertDialog.Builder(this); fadeBuilder.setTitle(R.string.alarm_fade); fadeBuilder.setView(fadeView); fadeBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { settings.setVolumeStartPercent(tryParseInt(volumeStart.getText().toString(), 0)); settings.setVolumeEndPercent(tryParseInt(volumeEnd.getText().toString(), 100)); settings.setVolumeChangeTimeSec(tryParseInt(volumeDuration.getText().toString(), 20)); settingsAdapter.notifyDataSetChanged(); dismissDialog(Dialogs.VOLUME_FADE_PICKER.ordinal()); } }); fadeBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismissDialog(Dialogs.VOLUME_FADE_PICKER.ordinal()); } }); return fadeBuilder.create(); case DELETE_CONFIRM: final AlertDialog.Builder deleteConfirmBuilder = new AlertDialog.Builder(this); deleteConfirmBuilder.setTitle(R.string.delete); deleteConfirmBuilder.setMessage(R.string.confirm_delete); deleteConfirmBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { service.deleteAlarm(alarmId); dismissDialog(Dialogs.DELETE_CONFIRM.ordinal()); finish(); } }); deleteConfirmBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismissDialog(Dialogs.DELETE_CONFIRM.ordinal()); } }); return deleteConfirmBuilder.create(); default: return super.onCreateDialog(id); } } /** * This is a helper class for mapping SettingType to action. Each Setting * in the list view returns a unique SettingType. Trigger a dialog * based off of that SettingType. */ private final class SettingsListClickListener implements OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final SettingsAdapter adapter = (SettingsAdapter) parent.getAdapter(); SettingType type = adapter.getItem(position).type(); switch (type) { case TIME: showDialog(Dialogs.TIME_PICKER.ordinal()); break; case NAME: showDialog(Dialogs.NAME_PICKER.ordinal()); break; case DAYS_OF_WEEK: showDialog(Dialogs.DOW_PICKER.ordinal()); break; case TONE: showDialog(Dialogs.TONE_PICKER.ordinal()); break; case SNOOZE: showDialog(Dialogs.SNOOZE_PICKER.ordinal()); break; case VIBRATE: settings.setVibrate(!settings.getVibrate()); settingsAdapter.notifyDataSetChanged(); break; case VOLUME_FADE: showDialog(Dialogs.VOLUME_FADE_PICKER.ordinal()); break; } } } private int tryParseInt(String input, int fallback) { try { return Integer.parseInt(input); } catch (Exception e) { return fallback; } } /** * A helper interface to encapsulate the data displayed in the list view of * this activity. Consists of a setting name, a setting value, and a type. * The type is used to trigger the appropriate action from the onClick * handler. */ private abstract class Setting { public abstract String name(); public abstract String value(); public abstract SettingType type(); } /** * This adapter populates the settings_items view with the data encapsulated * in the individual Setting objects. */ private final class SettingsAdapter extends ArrayAdapter<Setting> { public SettingsAdapter(Context context, List<Setting> settingsObjects) { super(context, 0, settingsObjects); } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = getLayoutInflater(); View row = inflater.inflate(R.layout.settings_item, null); TextView name = (TextView) row.findViewById(R.id.setting_name); TextView value = (TextView) row.findViewById(R.id.setting_value); Setting setting = getItem(position); name.setText(setting.name()); value.setText(setting.value()); return row; } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import java.util.LinkedList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public final class DbAccessor { private DbHelper db; private SQLiteDatabase rDb; private SQLiteDatabase rwDb; public DbAccessor(Context context) { db = new DbHelper(context); rwDb = db.getWritableDatabase(); rDb = db.getReadableDatabase(); } public void closeConnections() { rDb.close(); rwDb.close(); } public long newAlarm(AlarmTime time) { AlarmInfo info = new AlarmInfo(time, false, ""); long id = rwDb.insert(DbHelper.DB_TABLE_ALARMS, null, info.contentValues()); if (id < 0) { throw new IllegalStateException("Unable to insert into database"); } return id; } public boolean deleteAlarm(long alarmId) { int count = rDb.delete(DbHelper.DB_TABLE_ALARMS, DbHelper.ALARMS_COL__ID + " = " + alarmId, null); // This may or may not exist. We don't care about the return value. rDb.delete(DbHelper.DB_TABLE_SETTINGS, DbHelper.SETTINGS_COL_ID + " = " + alarmId, null); return count > 0; } public boolean enableAlarm(long alarmId, boolean enabled) { ContentValues values = new ContentValues(1); values.put(DbHelper.ALARMS_COL_ENABLED, enabled); int count = rwDb.update(DbHelper.DB_TABLE_ALARMS, values, DbHelper.ALARMS_COL__ID + " = " + alarmId, null); return count != 0; } public List<Long> getEnabledAlarms() { LinkedList<Long> enabled = new LinkedList<Long>(); Cursor cursor = rDb.query(DbHelper.DB_TABLE_ALARMS, new String[] { DbHelper.ALARMS_COL__ID }, DbHelper.ALARMS_COL_ENABLED + " = 1", null, null, null, null); while (cursor.moveToNext()) { long alarmId = cursor.getLong(cursor.getColumnIndex(DbHelper.ALARMS_COL__ID)); enabled.add(alarmId); } cursor.close(); return enabled; } public List<Long> getAllAlarms() { LinkedList<Long> alarms = new LinkedList<Long>(); Cursor cursor = rDb.query(DbHelper.DB_TABLE_ALARMS, new String[] { DbHelper.ALARMS_COL__ID }, null, null, null, null, null); while (cursor.moveToNext()) { long alarmId = cursor.getLong(cursor.getColumnIndex(DbHelper.ALARMS_COL__ID)); alarms.add(alarmId); } cursor.close(); return alarms; } public boolean writeAlarmInfo(long alarmId, AlarmInfo info) { return rwDb.update(DbHelper.DB_TABLE_ALARMS, info.contentValues(), DbHelper.ALARMS_COL__ID + " = " + alarmId, null) == 1; } public Cursor readAlarmInfo() { Cursor cursor = rDb.query(DbHelper.DB_TABLE_ALARMS, AlarmInfo.contentColumns(), null, null, null, null, DbHelper.ALARMS_COL_TIME + " ASC"); return cursor; } public AlarmInfo readAlarmInfo(long alarmId) { Cursor cursor = rDb.query(DbHelper.DB_TABLE_ALARMS, AlarmInfo.contentColumns(), DbHelper.ALARMS_COL__ID + " = " + alarmId, null, null, null, null); if (cursor.getCount() != 1) { cursor.close(); return null; } cursor.moveToFirst(); AlarmInfo info = new AlarmInfo(cursor); cursor.close(); return info; } public boolean writeAlarmSettings(long alarmId, AlarmSettings settings) { Cursor cursor = rDb.query(DbHelper.DB_TABLE_SETTINGS, new String[] { DbHelper.SETTINGS_COL_ID }, DbHelper.SETTINGS_COL_ID + " = " + alarmId, null, null, null, null); boolean success = false; if (cursor.getCount() < 1) { success = rwDb.insert(DbHelper.DB_TABLE_SETTINGS, null, settings.contentValues(alarmId)) >= 0; } else { success = rwDb.update(DbHelper.DB_TABLE_SETTINGS, settings.contentValues(alarmId), DbHelper.SETTINGS_COL_ID + " = " + alarmId, null) == 1; } cursor.close(); return success; } public AlarmSettings readAlarmSettings(long alarmId) { Cursor cursor = rDb.query(DbHelper.DB_TABLE_SETTINGS, AlarmSettings.contentColumns(), DbHelper.SETTINGS_COL_ID + " = " + alarmId, null, null, null, null); if (cursor.getCount() != 1) { cursor.close(); if (alarmId == AlarmSettings.DEFAULT_SETTINGS_ID) { return new AlarmSettings(); } return readAlarmSettings(AlarmSettings.DEFAULT_SETTINGS_ID); } AlarmSettings settings = new AlarmSettings(cursor); cursor.close(); return settings; } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; /** * This class contains all of the settings data for a given alarm. It also * provides the mapping from this data to the respective columns in the * persistent settings database. */ public final class AlarmSettings { static public final long DEFAULT_SETTINGS_ID = -1; private Uri tone; private String toneName; private int snoozeMinutes; private boolean vibrate; private int volumeStartPercent; private int volumeEndPercent; private int volumeChangeTimeSec; public ContentValues contentValues(long alarmId) { ContentValues values = new ContentValues(); values.put(DbHelper.SETTINGS_COL_ID, alarmId); values.put(DbHelper.SETTINGS_COL_TONE_URL, tone.toString()); values.put(DbHelper.SETTINGS_COL_TONE_NAME, toneName); values.put(DbHelper.SETTINGS_COL_SNOOZE, snoozeMinutes); values.put(DbHelper.SETTINGS_COL_VIBRATE, vibrate); values.put(DbHelper.SETTINGS_COL_VOLUME_STARTING, volumeStartPercent); values.put(DbHelper.SETTINGS_COL_VOLUME_ENDING, volumeEndPercent); values.put(DbHelper.SETTINGS_COL_VOLUME_TIME, volumeChangeTimeSec); return values; } static public String[] contentColumns() { return new String[] { DbHelper.SETTINGS_COL_ID, DbHelper.SETTINGS_COL_TONE_URL, DbHelper.SETTINGS_COL_TONE_NAME, DbHelper.SETTINGS_COL_SNOOZE, DbHelper.SETTINGS_COL_VIBRATE, DbHelper.SETTINGS_COL_VOLUME_STARTING, DbHelper.SETTINGS_COL_VOLUME_ENDING, DbHelper.SETTINGS_COL_VOLUME_TIME }; } public AlarmSettings() { tone = AlarmUtil.getDefaultAlarmUri(); toneName = "Default"; snoozeMinutes = 10; vibrate = false; volumeStartPercent = 0; volumeEndPercent = 100; volumeChangeTimeSec = 20; } public AlarmSettings(AlarmSettings rhs) { tone = rhs.tone; toneName = rhs.toneName; snoozeMinutes = rhs.snoozeMinutes; vibrate = rhs.vibrate; volumeStartPercent = rhs.volumeStartPercent; volumeEndPercent = rhs.volumeEndPercent; volumeChangeTimeSec = rhs.volumeChangeTimeSec; } public AlarmSettings(Cursor cursor) { cursor.moveToFirst(); tone = Uri.parse(cursor.getString(cursor.getColumnIndex(DbHelper.SETTINGS_COL_TONE_URL))); toneName = cursor.getString(cursor.getColumnIndex(DbHelper.SETTINGS_COL_TONE_NAME)); snoozeMinutes = cursor.getInt(cursor.getColumnIndex(DbHelper.SETTINGS_COL_SNOOZE)); vibrate = cursor.getInt(cursor.getColumnIndex(DbHelper.SETTINGS_COL_VIBRATE)) == 1; volumeStartPercent = cursor.getInt(cursor.getColumnIndex(DbHelper.SETTINGS_COL_VOLUME_STARTING)); volumeEndPercent = cursor.getInt(cursor.getColumnIndex(DbHelper.SETTINGS_COL_VOLUME_ENDING)); volumeChangeTimeSec = cursor.getInt(cursor.getColumnIndex(DbHelper.SETTINGS_COL_VOLUME_TIME)); } @Override public boolean equals(Object o) { if (!(o instanceof AlarmSettings)) { return false; } AlarmSettings rhs = (AlarmSettings) o; return tone.equals(rhs.tone) && toneName.equals(rhs.toneName) && snoozeMinutes == rhs.snoozeMinutes && vibrate == rhs.vibrate && volumeStartPercent == rhs.volumeStartPercent && volumeEndPercent == rhs.volumeEndPercent && volumeChangeTimeSec == rhs.volumeChangeTimeSec; } public Uri getTone() { return tone; } public void setTone(Uri tone, String name) { this.tone = tone; this.toneName = name; } public String getToneName() { return toneName; } public int getSnoozeMinutes() { return snoozeMinutes; } public void setSnoozeMinutes(int minutes) { if (minutes < 1) { minutes = 1; } else if (minutes > 60) { minutes = 60; } this.snoozeMinutes = minutes; } public boolean getVibrate() { return vibrate; } public void setVibrate(boolean vibrate) { this.vibrate = vibrate; } public int getVolumeStartPercent() { return volumeStartPercent; } public void setVolumeStartPercent(int volumeStartPercent) { if (volumeStartPercent < 0) { volumeStartPercent = 0; } else if (volumeStartPercent > 100) { volumeStartPercent = 100; } this.volumeStartPercent = volumeStartPercent; } public int getVolumeEndPercent() { return volumeEndPercent; } public void setVolumeEndPercent(int volumeEndPercent) { if (volumeEndPercent < 0) { volumeEndPercent = 0; } else if (volumeEndPercent > 100) { volumeEndPercent = 100; } this.volumeEndPercent = volumeEndPercent; } public int getVolumeChangeTimeSec() { return volumeChangeTimeSec; } public void setVolumeChangeTimeSec(int volumeChangeTimeSec) { if (volumeChangeTimeSec < 1) { volumeChangeTimeSec = 1; } else if (volumeChangeTimeSec > 600) { volumeChangeTimeSec = 600; } this.volumeChangeTimeSec = volumeChangeTimeSec; } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.angrydoughnuts.android.alarmclock; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.KeyguardManager; import android.app.KeyguardManager.KeyguardLock; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; /** * This is the activity responsible for alerting the user when an alarm goes * off. It is the activity triggered by the NotificationService. It assumes * that the intent sender has acquired a screen wake lock. * NOTE: This class assumes that it will never be instantiated nor active * more than once at the same time. (ie, it assumes * android:launchMode="singleInstance" is set in the manifest file). */ public final class ActivityAlarmNotification extends Activity { public final static String TIMEOUT_COMMAND = "timeout"; private enum Dialogs { TIMEOUT } private NotificationServiceBinder notifyService; private DbAccessor db; private KeyguardLock screenLock; private Handler handler; private Runnable timeTick; // Dialog state int snoozeMinutes; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.notification); db = new DbAccessor(getApplicationContext()); // Start the notification service and bind to it. notifyService = new NotificationServiceBinder(getApplicationContext()); notifyService.bind(); // Setup a self-scheduling event loops. handler = new Handler(); timeTick = new Runnable() { @Override public void run() { notifyService.call(new NotificationServiceBinder.ServiceCallback() { @Override public void run(NotificationServiceInterface service) { try { TextView volume = (TextView) findViewById(R.id.volume); volume.setText("Volume: " + service.volume()); } catch (RemoteException e) {} long next = AlarmUtil.millisTillNextInterval(AlarmUtil.Interval.SECOND); handler.postDelayed(timeTick, next); } }); } }; // Setup the screen lock object. The screen will be unlocked onResume() and // re-locked onPause(); final KeyguardManager screenLockManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); screenLock = screenLockManager.newKeyguardLock( "AlarmNotification screen lock"); // Setup individual UI elements. final Button snoozeButton = (Button) findViewById(R.id.notify_snooze); snoozeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { notifyService.acknowledgeCurrentNotification(snoozeMinutes); finish(); } }); final Button decreaseSnoozeButton = (Button) findViewById(R.id.notify_snooze_minus_five); decreaseSnoozeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { int snooze = snoozeMinutes - 5; if (snooze < 5) { snooze = 5; } snoozeMinutes = snooze; redraw(); } }); final Button increaseSnoozeButton = (Button) findViewById(R.id.notify_snooze_plus_five); increaseSnoozeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { int snooze = snoozeMinutes + 5; if (snooze > 60) { snooze = 60; } snoozeMinutes = snooze; redraw(); } }); final Slider dismiss = (Slider) findViewById(R.id.dismiss_slider); dismiss.setOnCompleteListener(new Slider.OnCompleteListener() { @Override public void complete() { notifyService.acknowledgeCurrentNotification(0); finish(); } }); } @Override protected void onResume() { super.onResume(); screenLock.disableKeyguard(); handler.post(timeTick); redraw(); } @Override protected void onPause() { super.onPause(); handler.removeCallbacks(timeTick); screenLock.reenableKeyguard(); } @Override protected void onDestroy() { super.onDestroy(); db.closeConnections(); notifyService.unbind(); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); Bundle extras = intent.getExtras(); if (extras == null || extras.getBoolean(TIMEOUT_COMMAND, false) == false) { return; } // The notification service has signaled this activity for a second time. // This represents a acknowledgment timeout. Display the appropriate error. // (which also finish()es this activity. showDialog(Dialogs.TIMEOUT.ordinal()); } @Override protected Dialog onCreateDialog(int id) { switch (Dialogs.values()[id]) { case TIMEOUT: final AlertDialog.Builder timeoutBuilder = new AlertDialog.Builder(this); timeoutBuilder.setIcon(android.R.drawable.ic_dialog_alert); timeoutBuilder.setTitle(R.string.time_out_title); timeoutBuilder.setMessage(R.string.time_out_error); timeoutBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) {} }); AlertDialog dialog = timeoutBuilder.create(); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { finish(); }}); return dialog; default: return super.onCreateDialog(id); } } private final void redraw() { notifyService.call(new NotificationServiceBinder.ServiceCallback() { @Override public void run(NotificationServiceInterface service) { long alarmId; try { alarmId = service.currentAlarmId(); } catch (RemoteException e) { return; } AlarmInfo alarmInfo = db.readAlarmInfo(alarmId); if (snoozeMinutes == 0) { snoozeMinutes = db.readAlarmSettings(alarmId).getSnoozeMinutes(); } String info = alarmInfo.getTime().toString() + "\n" + alarmInfo.getName(); if (AppSettings.isDebugMode(getApplicationContext())) { info += " [" + alarmId + "]"; findViewById(R.id.volume).setVisibility(View.VISIBLE); } else { findViewById(R.id.volume).setVisibility(View.GONE); } TextView infoText = (TextView) findViewById(R.id.alarm_info); infoText.setText(info); TextView snoozeInfo = (TextView) findViewById(R.id.notify_snooze_time); snoozeInfo.setText(getString(R.string.snooze) + "\n" + getString(R.string.minutes, snoozeMinutes)); } }); } }
Java
package com.angrydoughnuts.android.alarmclock; import java.util.Calendar; import android.content.Context; import android.os.Parcel; import android.os.Parcelable; public class Week implements Parcelable { public static final Week NO_REPEATS = new Week(new boolean[] {false, false, false, false, false, false, false}); public static final Week EVERYDAY = new Week(new boolean[] {true, true, true, true, true, true, true}); public static final Week WEEKDAYS = new Week(new boolean[] {false, true, true, true, true, true, false}); public static final Week WEEKENDS = new Week(new boolean[] {true, false, false, false, false, false, true}); public enum Day { SUN(R.string.dow_sun), MON(R.string.dow_mon), TUE(R.string.dow_tue), WED(R.string.dow_wed), THU(R.string.dow_thu), FRI(R.string.dow_fri), SAT(R.string.dow_sat); private int stringId; Day (int stringId) { this.stringId = stringId; } public int stringId() { return stringId; } } private boolean[] bitmask; public Week(Parcel source) { bitmask = source.createBooleanArray(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeBooleanArray(bitmask); } public Week() { bitmask = new boolean[Day.values().length]; } public Week(Week rhs) { bitmask = rhs.bitmask.clone(); } public Week(boolean[] bitmask) { if (bitmask.length != Day.values().length) { throw new IllegalArgumentException("Wrong sized bitmask: " + bitmask.length); } this.bitmask = bitmask; } public boolean[] bitmask() { return bitmask; } public void addDay(Day day) { bitmask[day.ordinal()] = true; } public void removeDay(Day day) { bitmask[day.ordinal()] = false; } public boolean hasDay(Day day) { return bitmask[day.ordinal()]; } public CharSequence[] names(Context context) { CharSequence[] nameList = new CharSequence[Day.values().length]; for (Day day : Day.values()) { nameList[day.ordinal()] = context.getString(day.stringId()); } return nameList; } public String toString(Context context) { if (this.equals(NO_REPEATS)) { return context.getString(R.string.no_repeats); } if (this.equals(EVERYDAY)) { return context.getString(R.string.everyday); } if (this.equals(WEEKDAYS)) { return context.getString(R.string.weekdays); } if (this.equals(WEEKENDS)) { return context.getString(R.string.weekends); } String list = ""; for (Day day : Day.values()) { if (!bitmask[day.ordinal()]) { continue; } switch (day) { case SUN: list += " " + context.getString(R.string.dow_sun_short); break; case MON: list += " " + context.getString(R.string.dow_mon_short); break; case TUE: list += " " + context.getString(R.string.dow_tue_short); break; case WED: list += " " + context.getString(R.string.dow_wed_short); break; case THU: list += " " + context.getString(R.string.dow_thu_short); break; case FRI: list += " " + context.getString(R.string.dow_fri_short); break; case SAT: list += " " + context.getString(R.string.dow_sat_short); break; } } return list; } @Override public boolean equals(Object o) { if (!(o instanceof Week)) { return false; } Week rhs = (Week) o; if (bitmask.length != rhs.bitmask.length) { return false; } for (Day day : Day.values()) { if (bitmask[day.ordinal()] != rhs.bitmask[day.ordinal()]) { return false; } } return true; } @Override public int describeContents() { return 0; } public static final Parcelable.Creator<Week> CREATOR = new Parcelable.Creator<Week>() { @Override public Week createFromParcel(Parcel source) { return new Week(source); } @Override public Week[] newArray(int size) { return new Week[size]; } }; public static Day calendarToDay(int dow) { int ordinalOffset = dow - Calendar.SUNDAY; return Day.values()[ordinalOffset]; } }
Java