A whole lot of widening, refactoring, thinking, rethinking and fiddling around

for what ultimately boils down adding this method to BundledComponentRepository:

    @Override // from IMImageProvider
    public Mirage getTileImage (String path, Rectangle bounds, Colorization[] zations)
    {
        // we don't need our images prepared for screen rendering
        BufferedImage src = _imgr.getImage(getImageKey(path), zations);
        if (bounds != null) {
            src = src.getSubimage(bounds.x, bounds.y, bounds.width, bounds.height);
        }
        return new BufferedMirage(src);
    }

So much fun to revisit code I wrote six years ago.


git-svn-id: svn+ssh://src.earth.threerings.net/nenya/trunk@283 ed5b42cb-e716-0410-a449-f6a68f950b19
This commit is contained in:
Michael Bayne
2007-08-03 22:04:04 +00:00
parent bbd5dd284e
commit 069fe85c70
11 changed files with 390 additions and 486 deletions
@@ -39,10 +39,13 @@ import com.samskivert.util.Tuple;
import com.threerings.resource.ResourceBundle;
import com.threerings.resource.ResourceManager;
import com.threerings.media.image.BufferedMirage;
import com.threerings.media.image.Colorization;
import com.threerings.media.image.FastImageIO;
import com.threerings.media.image.ImageDataProvider;
import com.threerings.media.image.ImageManager;
import com.threerings.media.image.ImageUtil;
import com.threerings.media.image.Mirage;
import com.threerings.media.tile.IMImageProvider;
import com.threerings.media.tile.Tile;
@@ -63,8 +66,7 @@ import com.threerings.cast.StandardActions;
import com.threerings.cast.TrimmedMultiFrameImage;
/**
* A component repository implementation that obtains information from
* resource bundles.
* A component repository implementation that obtains information from resource bundles.
*
* @see ResourceManager
*/
@@ -72,18 +74,15 @@ public class BundledComponentRepository
implements DirectionCodes, ComponentRepository
{
/**
* Constructs a repository which will obtain its resource set from the
* supplied resource manager.
* Constructs a repository which will obtain its resource set from the supplied resource
* manager.
*
* @param rmgr the resource manager from which to obtain our resource
* set.
* @param imgr the image manager that we'll use to decode and cache
* images.
* @param name the name of the resource set from which we will be
* loading our component data.
* @param rmgr the resource manager from which to obtain our resource set.
* @param imgr the image manager that we'll use to decode and cache images.
* @param name the name of the resource set from which we will be loading our component data.
*
* @exception IOException thrown if an I/O error occurs while reading
* our metadata from the resource bundles.
* @exception IOException thrown if an I/O error occurs while reading our metadata from the
* resource bundles.
*/
public BundledComponentRepository (
ResourceManager rmgr, ImageManager imgr, String name)
@@ -92,8 +91,7 @@ public class BundledComponentRepository
// keep this guy around
_imgr = imgr;
// first we obtain the resource set from whence will come our
// bundles
// first we obtain the resource set from whence will come our bundles
ResourceBundle[] rbundles = rmgr.getResourceSet(name);
// look for our metadata info in each of the bundles
@@ -124,17 +122,14 @@ public class BundledComponentRepository
}
// create a frame provider for this bundle
FrameProvider fprov =
new ResourceBundleProvider(_imgr, rbundles[i]);
FrameProvider fprov = new ResourceBundleProvider(_imgr, rbundles[i]);
// now create character component instances for each component
// in the serialized table
// now create char. component instances for each component in the serialized table
Iterator iter = comps.keySet().iterator();
while (iter.hasNext()) {
int componentId = ((Integer)iter.next()).intValue();
Tuple info = (Tuple)comps.get(componentId);
createComponent(componentId, (String)info.left,
(String)info.right, fprov);
createComponent(componentId, (String)info.left, (String)info.right, fprov);
}
}
@@ -143,8 +138,8 @@ public class BundledComponentRepository
"Internal error unserializing metadata").initCause(cnfe);
}
// if we failed to load our classes or actions, create empty
// hashtables so that we can safely enumerate our emptiness
// if we failed to load our classes or actions, create empty hashtables so that we can
// safely enumerate our emptiness
if (_actions == null) {
_actions = new HashMap();
}
@@ -154,11 +149,10 @@ public class BundledComponentRepository
}
/**
* Configures the bundled component repository to wipe any bundles
* that report certain kinds of failure. In the event that an unpacked
* bundle becomes corrupt, this is useful in that it will force the
* bundle to be unpacked on the next application invocation,
* potentially remedying the problem of a corrupt unpacking.
* Configures the bundled component repository to wipe any bundles that report certain kinds of
* failure. In the event that an unpacked bundle becomes corrupt, this is useful in that it
* will force the bundle to be unpacked on the next application invocation, potentially
* remedying the problem of a corrupt unpacking.
*/
public void setWipeOnFailure (boolean wipeOnFailure)
{
@@ -169,8 +163,7 @@ public class BundledComponentRepository
public CharacterComponent getComponent (int componentId)
throws NoSuchComponentException
{
CharacterComponent component = (CharacterComponent)
_components.get(componentId);
CharacterComponent component = (CharacterComponent)_components.get(componentId);
if (component == null) {
throw new NoSuchComponentException(componentId);
}
@@ -217,14 +210,12 @@ public class BundledComponentRepository
// documentation inherited
public Iterator enumerateComponentIds (final ComponentClass compClass)
{
Predicate<Integer> pred = new Predicate<Integer>() {
return new Predicate<Integer>() {
public boolean isMatch (Integer input) {
CharacterComponent comp = (CharacterComponent)
_components.get(input);
CharacterComponent comp = (CharacterComponent)_components.get(input);
return comp.componentClass.equals(compClass);
}
};
return pred.filter(_components.keySet().iterator());
}.filter(_components.keySet().iterator());
}
/**
@@ -236,15 +227,13 @@ public class BundledComponentRepository
// look up the component class information
ComponentClass clazz = (ComponentClass)_classes.get(cclass);
if (clazz == null) {
Log.warning("Non-existent component class " +
"[class=" + cclass + ", name=" + cname +
Log.warning("Non-existent component class [class=" + cclass + ", name=" + cname +
", id=" + componentId + "].");
return;
}
// create the component
CharacterComponent component = new CharacterComponent(
componentId, cname, clazz, fprov);
CharacterComponent component = new CharacterComponent(componentId, cname, clazz, fprov);
// stick it into the appropriate tables
_components.put(componentId, component);
@@ -258,21 +247,19 @@ public class BundledComponentRepository
if (!comps.contains(component)) {
comps.add(component);
} else {
Log.info("Requested to register the same component twice? " +
"[component=" + component + "].");
Log.info("Requested to register the same component twice? [comp=" + component + "].");
}
}
/**
* Instances of these provide images to our component action tilesets
* and frames to our components.
* Instances of these provide images to our component action tilesets and frames to our
* components.
*/
protected class ResourceBundleProvider extends IMImageProvider
implements ImageDataProvider, FrameProvider
{
/**
* Constructs an instance that will obtain image data from the
* specified resource bundle.
* Constructs an instance that will obtain image data from the specified resource bundle.
*/
public ResourceBundleProvider (ImageManager imgr, ResourceBundle bundle)
{
@@ -281,27 +268,25 @@ public class BundledComponentRepository
_bundle = bundle;
}
// documentation inherited from interface
// from interface ImageDataProvider
public String getIdent ()
{
return "bcr:" + _bundle.getSource();
}
// documentation inherited from interface
// from interface ImageDataProvider
public BufferedImage loadImage (String path) throws IOException
{
return FastImageIO.read(_bundle.getResourceFile(path));
}
// documentation inherited
public ActionFrames getFrames (
CharacterComponent component, String action, String type)
// from interface FrameProvider
public ActionFrames getFrames (CharacterComponent component, String action, String type)
{
// obtain the action sequence definition for this action
ActionSequence actseq = (ActionSequence)_actions.get(action);
if (actseq == null) {
Log.warning("Missing action sequence definition " +
"[action=" + action +
Log.warning("Missing action sequence definition [action=" + action +
", component=" + component + "].");
return null;
}
@@ -313,13 +298,12 @@ public class BundledComponentRepository
dimgpath += "_" + type;
}
String root = component.componentClass.name + "/" +
component.name + "/";
String root = component.componentClass.name + "/" + component.name + "/";
String cpath = root + imgpath + BundleUtil.TILESET_EXTENSION;
String dpath = root + dimgpath + BundleUtil.TILESET_EXTENSION;
// look to see if this tileset is already cached (as the
// custom action or the default action)
// look to see if this tileset is already cached (as the custom action or the default
// action)
TileSet aset = (TileSet)_setcache.get(cpath);
if (aset == null) {
aset = (TileSet)_setcache.get(dpath);
@@ -332,25 +316,22 @@ public class BundledComponentRepository
try {
// then try loading up a tileset customized for this action
if (aset == null) {
aset = (TileSet)BundleUtil.loadObject(
_bundle, cpath, false);
aset = (TileSet)BundleUtil.loadObject(_bundle, cpath, false);
}
// if that failed, try loading the default tileset
if (aset == null) {
aset = (TileSet)BundleUtil.loadObject(
_bundle, dpath, false);
aset = (TileSet)BundleUtil.loadObject(_bundle, dpath, false);
_setcache.put(dpath, aset);
}
// if that failed too, we're hosed
if (aset == null) {
// if this is a shadow or crop image, no need to freak out
// as they are optional
// if this is a shadow or crop image, no need to freak out as they are optional
if (!StandardActions.CROP_TYPE.equals(type) &&
!StandardActions.SHADOW_TYPE.equals(type)) {
Log.warning("Unable to locate tileset for action '" +
imgpath + "' " + component + ".");
Log.warning("Unable to locate tileset for action '" + imgpath + "' " +
component + ".");
if (_wipeOnFailure) {
_bundle.wipeBundle(false);
}
@@ -363,13 +344,23 @@ public class BundledComponentRepository
return new TileSetFrameImage(aset, actseq);
} catch (Exception e) {
Log.warning("Error loading tileset for action '" + imgpath +
"' " + component + ".");
Log.warning("Error loading tset for action '" + imgpath + "' " + component + ".");
Log.logStackTrace(e);
return null;
}
}
@Override // from IMImageProvider
public Mirage getTileImage (String path, Rectangle bounds, Colorization[] zations)
{
// we don't need our images prepared for screen rendering
BufferedImage src = _imgr.getImage(getImageKey(path), zations);
if (bounds != null) {
src = src.getSubimage(bounds.x, bounds.y, bounds.width, bounds.height);
}
return new BufferedMirage(src);
}
/** The resource bundle from which we obtain image data. */
protected ResourceBundle _bundle;
@@ -378,14 +369,13 @@ public class BundledComponentRepository
}
/**
* Used to provide multiframe images using data obtained from a
* tileset.
* Used to provide multiframe images using data obtained from a tileset.
*/
protected static class TileSetFrameImage implements ActionFrames
{
/**
* Constructs a tileset frame image with the specified tileset and
* for the specified orientation.
* Constructs a tileset frame image with the specified tileset and for the specified
* orientation.
*/
public TileSetFrameImage (TileSet set, ActionSequence actseq)
{
@@ -393,8 +383,8 @@ public class BundledComponentRepository
}
/**
* Constructs a tileset frame image with the specified tileset and
* for the specified orientation, with an optional translation.
* Constructs a tileset frame image with the specified tileset and for the specified
* orientation, with an optional translation.
*/
public TileSetFrameImage (TileSet set, ActionSequence actseq, int dx, int dy)
{
@@ -407,8 +397,7 @@ public class BundledComponentRepository
_ocount = actseq.orients.length;
_fcount = set.getTileCount() / _ocount;
// create our mapping from orientation to animation sequence
// index
// create our mapping from orientation to animation sequence index
for (int ii = 0; ii < _ocount; ii++) {
_orients.put(actseq.orients[ii], ii);
}
@@ -424,51 +413,32 @@ public class BundledComponentRepository
public TrimmedMultiFrameImage getFrames (final int orient)
{
return new TrimmedMultiFrameImage() {
// documentation inherited
public int getFrameCount ()
{
public int getFrameCount () {
return _fcount;
}
// documentation inherited from interface
public int getWidth (int index)
{
Tile tile = getTile(orient, index);
return (tile == null) ? 0 : tile.getWidth();
public int getWidth (int index) {
return _set.getTile(getTileIndex(orient, index)).getWidth();
}
// documentation inherited from interface
public int getHeight (int index)
{
Tile tile = getTile(orient, index);
return (tile == null) ? 0 : tile.getHeight();
public int getHeight (int index) {
return _set.getTile(getTileIndex(orient, index)).getHeight();
}
// documentation inherited from interface
public void paintFrame (Graphics2D g, int index, int x, int y)
{
Tile tile = getTile(orient, index);
if (tile != null) {
tile.paint(g, x + _dx, y + _dy);
}
public void paintFrame (Graphics2D g, int index, int x, int y) {
_set.getTile(getTileIndex(orient, index)).paint(g, x + _dx, y + _dy);
}
// documentation inherited from interface
public boolean hitTest (int index, int x, int y)
{
Tile tile = getTile(orient, index);
return (tile != null) ? tile.hitTest(x + _dx, y + _dy) : false;
public boolean hitTest (int index, int x, int y) {
return _set.getTile(getTileIndex(orient, index)).hitTest(x + _dx, y + _dy);
}
// documentation inherited from interface
public void getTrimmedBounds (int index, Rectangle bounds)
{
Tile tile = getTile(orient, index);
public void getTrimmedBounds (int index, Rectangle bounds) {
Tile tile = _set.getTile(getTileIndex(orient, index));
if (tile instanceof TrimmedTile) {
((TrimmedTile)tile).getTrimmedBounds(bounds);
} else {
bounds.setBounds(
0, 0, tile.getWidth(), tile.getHeight());
bounds.setBounds(0, 0, tile.getWidth(), tile.getHeight());
}
bounds.translate(_dx, _dy);
}
@@ -499,13 +469,9 @@ public class BundledComponentRepository
return new TileSetFrameImage(_set, _actseq, dx, dy);
}
/**
* Fetches the requested tile.
*/
protected Tile getTile (int orient, int index)
protected int getTileIndex (int orient, int index)
{
int tileIndex = _orients.get(orient) * _fcount + index;
return _set.getTile(tileIndex);
return _orients.get(orient) * _fcount + index;
}
/** The tileset from which we obtain our frame images. */
@@ -520,8 +486,7 @@ public class BundledComponentRepository
/** Frame and orientation counts. */
protected int _fcount, _ocount;
/** A mapping from orientation code to animation sequence
* index. */
/** A mapping from orientation code to animation sequence index. */
protected IntIntMap _orients = new IntIntMap();
}
@@ -54,17 +54,14 @@ public class IMImageProvider implements ImageProvider
}
// documentation inherited from interface
public Mirage getTileImage (String path, Rectangle bounds,
Colorization[] zations)
public Mirage getTileImage (String path, Rectangle bounds, Colorization[] zations)
{
return _imgr.getMirage(getImageKey(path), bounds, zations);
}
protected final ImageManager.ImageKey getImageKey (String path)
{
return (_dprov == null) ?
_imgr.getImageKey(_rset, path) :
_imgr.getImageKey(_dprov, path);
return (_dprov == null) ? _imgr.getImageKey(_rset, path) : _imgr.getImageKey(_dprov, path);
}
protected ImageManager _imgr;
@@ -29,10 +29,9 @@ import com.threerings.media.image.ImageManager;
import com.threerings.media.image.Mirage;
/**
* Provides a generic interface via which tileset images may be loaded. In
* most cases, a running application will want to obtain images via the
* {@link ImageManager}, but in some circumstances a simpler image
* provider may be desirable to avoid the overhead of the image manager
* Provides a generic interface via which tileset images may be loaded. In most cases, a running
* application will want to obtain images via the {@link ImageManager}, but in some circumstances a
* simpler image provider may be desirable to avoid the overhead of the image manager
* infrastructure when simple image loading is all that is desired.
*/
public interface ImageProvider
@@ -40,25 +39,22 @@ public interface ImageProvider
/**
* Returns the raw tileset image with the specified path.
*
* @param path the path that identifies the desired image (corresponds
* to the image path from the tileset).
* @param zations if non-null, colorizations to apply to the source
* image before returning it.
* @param path the path that identifies the desired image (corresponds to the image path from
* the tileset).
* @param zations if non-null, colorizations to apply to the source image before returning it.
*/
public BufferedImage getTileSetImage (String path, Colorization[] zations);
/**
* Obtains the tile image with the specified path in the form of a
* {@link Mirage}. It should be cropped from the tileset image
* identified by the supplied path.
* Obtains the tile image with the specified path in the form of a {@link Mirage}. It should be
* cropped from the tileset image identified by the supplied path.
*
* @param path the path that identifies the desired image (corresponds
* to the image path from the tileset).
* @param bounds if non-null, the region of the image to be returned
* as a mirage. If null, the entire image should be returned.
* @param zations if non-null, colorizations to apply to the image
* before converting it into a mirage.
* @param path the path that identifies the desired image (corresponds to the image path from
* the tileset).
* @param bounds if non-null, the region of the image to be returned as a mirage. If null, the
* entire image should be returned.
* @param zations if non-null, colorizations to apply to the image before converting it into a
* mirage.
*/
public Mirage getTileImage (String path, Rectangle bounds,
Colorization[] zations);
public Mirage getTileImage (String path, Rectangle bounds, Colorization[] zations);
}
@@ -35,34 +35,34 @@ import com.threerings.media.image.Colorization;
*/
public class ObjectTileSet extends SwissArmyTileSet
implements RecolorableTileSet
{
{
/** A constraint prefix indicating that the object must have empty space in
* the suffixed direction (N, E, S, or W). */
public static final String SPACE = "SPACE_";
/** A constraint indicating that the object is a surface (e.g., table). */
public static final String SURFACE = "SURFACE";
/** A constraint indicating that the object must be placed on a surface. */
public static final String ON_SURFACE = "ON_SURFACE";
/** A constraint prefix indicating that the object is a wall facing the
* suffixed direction (N, E, S, or W). */
public static final String WALL = "WALL_";
/** A constraint prefix indicating that the object must be placed on a
* wall facing the suffixed direction (N, E, S, or W). */
public static final String ON_WALL = "ON_WALL_";
/** A constraint prefix indicating that the object must be attached to a
* wall facing the suffixed direction (N, E, S, or W). */
public static final String ATTACH = "ATTACH_";
/** The low suffix for walls and attachments. Low attachments can be placed
* on low or normal walls; normal attachments can only be placed on normal
* walls. */
public static final String LOW = "_LOW";
/**
* Sets the widths (in unit tile count) of the objects in this
* tileset. This must be accompanied by a call to {@link
@@ -148,7 +148,7 @@ public class ObjectTileSet extends SwissArmyTileSet
{
_constraints = constraints;
}
/**
* Returns the x coordinate of the spot associated with the specified
* tile index.
@@ -184,7 +184,7 @@ public class ObjectTileSet extends SwissArmyTileSet
{
return (_constraints == null) ? null : _constraints[tileIdx];
}
/**
* Checks whether the tile at the specified index has the given constraint.
*/
@@ -193,7 +193,7 @@ public class ObjectTileSet extends SwissArmyTileSet
return (_constraints == null) ? false :
ListUtil.contains(_constraints[tileIdx], constraint);
}
// documentation inherited from interface RecolorableTileSet
public String[] getColorizations ()
{
@@ -288,7 +288,7 @@ public class ObjectTileSet extends SwissArmyTileSet
/** Lists of constraints associated with our tiles. */
protected String[][] _constraints;
/** Increase this value when object's serialized state is impacted by
* a class change (modification of fields, inheritance). */
private static final long serialVersionUID = 2;
@@ -33,9 +33,8 @@ import com.threerings.media.image.Colorization;
import com.threerings.media.image.Mirage;
/**
* An image provider that can be used by command line tools to load images
* and provide them to tilesets when doing things like preprocessing
* tileset images.
* An image provider that can be used by command line tools to load images and provide them to
* tilesets when doing things like preprocessing tileset images.
*/
public abstract class SimpleCachingImageProvider implements ImageProvider
{
@@ -48,27 +47,23 @@ public abstract class SimpleCachingImageProvider implements ImageProvider
image = loadImage(path);
_cache.put(path, image);
} catch (IOException ioe) {
Log.warning("Failed to load image [path=" + path +
", ioe=" + ioe + "].");
Log.warning("Failed to load image [path=" + path + ", ioe=" + ioe + "].");
}
}
return image;
}
// documentation inherited from interface
public Mirage getTileImage (String path, Rectangle bounds,
Colorization[] zations)
public Mirage getTileImage (String path, Rectangle bounds, Colorization[] zations)
{
// mostly fake it
BufferedImage tsimg = getTileSetImage(path, zations);
tsimg = tsimg.getSubimage(bounds.x, bounds.y,
bounds.width, bounds.height);
tsimg = tsimg.getSubimage(bounds.x, bounds.y, bounds.width, bounds.height);
return new BufferedMirage(tsimg);
}
/**
* Derived classes must implement this method to actually load the raw
* source images.
* Derived classes must implement this method to actually load the raw source images.
*/
protected abstract BufferedImage loadImage (String path)
throws IOException;
@@ -31,11 +31,10 @@ import java.io.ObjectInputStream;
import com.samskivert.util.StringUtil;
/**
* The swiss army tileset supports a diverse variety of tiles in the
* tileset image. Each row can contain varying numbers of tiles and each
* row can have its own width and height. Tiles can be separated from the
* edge of the tileset image by some border offset and can be separated
* from one another by a gap distance.
* The swiss army tileset supports a diverse variety of tiles in the tileset image. Each row can
* contain varying numbers of tiles and each row can have its own width and height. Tiles can be
* separated from the edge of the tileset image by some border offset and can be separated from one
* another by a gap distance.
*/
public class SwissArmyTileSet extends TileSet
{
@@ -45,105 +44,8 @@ public class SwissArmyTileSet extends TileSet
return _numTiles;
}
/**
* Sets the tile counts which are the number of tiles in each row of
* the tileset image. Each row can have an arbitrary number of tiles.
*/
public void setTileCounts (int[] tileCounts)
{
_tileCounts = tileCounts;
// compute our total tile count
computeTileCount();
}
/**
* Returns the tile count settings.
*/
public int[] getTileCounts ()
{
return _tileCounts;
}
/**
* Computes our total tile count from the individual counts for each
* row.
*/
protected void computeTileCount ()
{
// compute our number of tiles
_numTiles = 0;
for (int i = 0; i < _tileCounts.length; i++) {
_numTiles += _tileCounts[i];
}
}
/**
* Sets the tile widths for each row. Each row can have tiles of a
* different width.
*/
public void setWidths (int[] widths)
{
_widths = widths;
}
/**
* Returns the width settings.
*/
public int[] getWidths ()
{
return _widths;
}
/**
* Sets the tile heights for each row. Each row can have tiles of a
* different height.
*/
public void setHeights (int[] heights)
{
_heights = heights;
}
/**
* Returns the height settings.
*/
public int[] getHeights ()
{
return _heights;
}
/**
* Sets the offset in pixels of the upper left corner of the first
* tile in the first row. If the tileset image has a border, this can
* be set to account for it.
*/
public void setOffsetPos (Point offsetPos)
{
_offsetPos = offsetPos;
}
/**
* Sets the size of the gap between tiles (in pixels). If the tiles
* have space between them, this can be set to account for it.
*/
public void setGapSize (Dimension gapSize)
{
_gapSize = gapSize;
}
// documentation inherited
protected void toString (StringBuilder buf)
{
super.toString(buf);
buf.append(", widths=").append(StringUtil.toString(_widths));
buf.append(", heights=").append(StringUtil.toString(_heights));
buf.append(", tileCounts=").append(StringUtil.toString(_tileCounts));
buf.append(", offsetPos=").append(StringUtil.toString(_offsetPos));
buf.append(", gapSize=").append(StringUtil.toString(_gapSize));
}
// documentation inherited
protected Rectangle computeTileBounds (int tileIndex)
public Rectangle computeTileBounds (int tileIndex, Rectangle bounds)
{
// find the row number containing the sought-after tile
int ridx, tcount, ty, tx;
@@ -165,11 +67,104 @@ public class SwissArmyTileSet extends TileSet
tx += (xidx * (_widths[ridx] + _gapSize.width));
// Log.info("Computed tile bounds [tileIndex=" + tileIndex +
// ", ridx=" + ridx + ", xidx=" + xidx +
// ", tx=" + tx + ", ty=" + ty + "].");
// ", ridx=" + ridx + ", xidx=" + xidx + ", tx=" + tx + ", ty=" + ty + "].");
// crop the tile-sized image chunk from the full image
return new Rectangle(tx, ty, _widths[ridx], _heights[ridx]);
bounds.setBounds(tx, ty, _widths[ridx], _heights[ridx]);
return bounds;
}
/**
* Sets the tile counts which are the number of tiles in each row of the tileset image. Each
* row can have an arbitrary number of tiles.
*/
public void setTileCounts (int[] tileCounts)
{
_tileCounts = tileCounts;
// compute our total tile count
computeTileCount();
}
/**
* Returns the tile count settings.
*/
public int[] getTileCounts ()
{
return _tileCounts;
}
/**
* Computes our total tile count from the individual counts for each row.
*/
protected void computeTileCount ()
{
// compute our number of tiles
_numTiles = 0;
for (int i = 0; i < _tileCounts.length; i++) {
_numTiles += _tileCounts[i];
}
}
/**
* Sets the tile widths for each row. Each row can have tiles of a different width.
*/
public void setWidths (int[] widths)
{
_widths = widths;
}
/**
* Returns the width settings.
*/
public int[] getWidths ()
{
return _widths;
}
/**
* Sets the tile heights for each row. Each row can have tiles of a different height.
*/
public void setHeights (int[] heights)
{
_heights = heights;
}
/**
* Returns the height settings.
*/
public int[] getHeights ()
{
return _heights;
}
/**
* Sets the offset in pixels of the upper left corner of the first tile in the first row. If
* the tileset image has a border, this can be set to account for it.
*/
public void setOffsetPos (Point offsetPos)
{
_offsetPos = offsetPos;
}
/**
* Sets the size of the gap between tiles (in pixels). If the tiles have space between them,
* this can be set to account for it.
*/
public void setGapSize (Dimension gapSize)
{
_gapSize = gapSize;
}
// documentation inherited
protected void toString (StringBuilder buf)
{
super.toString(buf);
buf.append(", widths=").append(StringUtil.toString(_widths));
buf.append(", heights=").append(StringUtil.toString(_heights));
buf.append(", tileCounts=").append(StringUtil.toString(_tileCounts));
buf.append(", offsetPos=").append(StringUtil.toString(_offsetPos));
buf.append(", gapSize=").append(StringUtil.toString(_gapSize));
}
private void readObject (ObjectInputStream in)
@@ -193,15 +188,15 @@ public class SwissArmyTileSet extends TileSet
/** The height of the tiles in each row in pixels. */
protected int[] _heights;
/** The offset distance (x, y) in pixels from the top-left of the
* image to the start of the first tile image. */
/** The offset distance (x, y) in pixels from the top-left of the image to the start of the
* first tile image. */
protected Point _offsetPos = new Point();
/** The distance (x, y) in pixels between each tile in each row
* horizontally, and between each row of tiles vertically. */
/** The distance (x, y) in pixels between each tile in each row horizontally, and between each
* row of tiles vertically. */
protected Dimension _gapSize = new Dimension();
/** Increase this value when object's serialized state is impacted by
* a class change (modification of fields, inheritance). */
/** Increase this value when object's serialized state is impacted by a class change
* (modification of fields, inheritance). */
private static final long serialVersionUID = 1;
}
+88 -113
View File
@@ -40,20 +40,17 @@ import com.threerings.media.util.MultiFrameImage;
import com.threerings.media.util.MultiFrameImageImpl;
/**
* A tileset stores information on a single logical set of tiles. It
* provides a clean interface for the {@link TileManager} or other
* entities to retrieve individual tiles from the tile set and
* encapsulates the potentially sophisticated process of extracting the
* tile image from a composite tileset image.
* A tileset stores information on a single logical set of tiles. It provides a clean interface for
* the {@link TileManager} or other entities to retrieve individual tiles from the tile set and
* encapsulates the potentially sophisticated process of extracting the tile image from a composite
* tileset image.
*
* <p> Tiles are referenced by their tile id. The tile id is essentially
* the tile number, assuming the tile at the top-left of the image is tile
* id zero and tiles are numbered, in ascending order, left to right, top
* to bottom.
* <p> Tiles are referenced by their tile id. The tile id is essentially the tile number, assuming
* the tile at the top-left of the image is tile id zero and tiles are numbered, in ascending
* order, left to right, top to bottom.
*
* <p> This class is serializable and will be serialized, so derived
* classes should be sure to mark non-persistent fields as
* <code>transient</code>.
* <p> This class is serializable and will be serialized, so derived classes should be sure to mark
* non-persistent fields as <code>transient</code>.
*/
public abstract class TileSet
implements Cloneable, Serializable
@@ -62,19 +59,17 @@ public abstract class TileSet
public static interface Colorizer
{
/**
* Returns the colorization to be used for the specified named
* colorization class.
* Returns the colorization to be used for the specified named colorization class.
*
* @param index the index of the colorization being requested in
* the tileset's colorization list.
* @param index the index of the colorization being requested in the tileset's colorization
* list.
*/
public Colorization getColorization (int index, String zation);
}
/**
* Configures this tileset with an image provider that it can use to
* load its tileset image. This will be called automatically when the
* tileset is fetched via the {@link TileManager}.
* Configures this tileset with an image provider that it can use to load its tileset image.
* This will be called automatically when the tileset is fetched via the {@link TileManager}.
*/
public void setImageProvider (ImageProvider improv)
{
@@ -98,8 +93,8 @@ public abstract class TileSet
}
/**
* Sets the path to the image that will be used by this tileset. This
* must be called before the first call to {@link #getTile}.
* Sets the path to the image that will be used by this tileset. This must be called before the
* first call to {@link #getTile}.
*/
public void setImagePath (String imagePath)
{
@@ -120,8 +115,8 @@ public abstract class TileSet
public abstract int getTileCount ();
/**
* Creates a copy of this tileset which will apply the supplied
* colorizations to its tileset image when creating tiles.
* Creates a copy of this tileset which will apply the supplied colorizations to its tileset
* image when creating tiles.
*/
public TileSet clone (Colorization[] zations)
{
@@ -131,19 +126,16 @@ public abstract class TileSet
return tset;
} catch (CloneNotSupportedException cnse) {
Log.warning("Unable to clone tileset prior to colorization " +
"[tset=" + this +
", zations=" + StringUtil.toString(zations) +
", error=" + cnse + "].");
Log.warning("Unable to clone tileset prior to colorization [tset=" + this +
", zations=" + StringUtil.toString(zations) + ", error=" + cnse + "].");
return null;
}
}
/**
* Returns a new tileset that is a clone of this tileset with the
* image path updated to reference the given path. Useful for
* configuring a single tileset and then generating additional
* tilesets with new images with the same configuration.
* Returns a new tileset that is a clone of this tileset with the image path updated to
* reference the given path. Useful for configuring a single tileset and then generating
* additional tilesets with new images with the same configuration.
*/
public TileSet clone (String imagePath)
throws CloneNotSupportedException
@@ -154,8 +146,20 @@ public abstract class TileSet
}
/**
* Equivalent to {@link #getTile(int,Colorizer)} with a null
* <code>Colorizer</code> argument.
* Computes and fills in the bounds for the specified tile based on the mechanism used by the
* derived class to do such things. The width and height of the bounds should be the size of
* the tile image and the x and y offset should be the offset in the tileset image for the
* image data of the specified tile.
*
* @param tileIndex the index of the tile whose bounds are to be computed.
* @param bounds the rectangle object into which to fill the bounds.
*
* @return the rectangle passed into the bounds parameter.
*/
public abstract Rectangle computeTileBounds (int tileIndex, Rectangle bounds);
/**
* Equivalent to {@link #getTile(int,Colorizer)} with a null <code>Colorizer</code> argument.
*/
public Tile getTile (int tileIndex)
{
@@ -163,17 +167,15 @@ public abstract class TileSet
}
/**
* Creates a {@link Tile} object from this tileset corresponding to
* the specified tile id and returns that tile. A null tile will never
* be returned, but one with an error image may be returned if a
* problem occurs loading the underlying tileset image.
* Creates a {@link Tile} object from this tileset corresponding to the specified tile id and
* returns that tile. A null tile will never be returned, but one with an error image may be
* returned if a problem occurs loading the underlying tileset image.
*
* @param tileIndex the index of the tile in the tileset. Tile indexes
* start with zero as the upper left tile and increase by one as the
* tiles move left to right and top to bottom over the source image.
* @param rizer an entity that will be used to obtain colorizations
* for tilesets that are recolorizable. Passing null if the tileset is
* known not to be recolorizable is valid.
* @param tileIndex the index of the tile in the tileset. Tile indexes start with zero as the
* upper left tile and increase by one as the tiles move left to right and top to bottom over
* the source image.
* @param rizer an entity that will be used to obtain colorizations for tilesets that are
* recolorizable. Passing null if the tileset is known not to be recolorizable is valid.
*
* @return the tile object.
*/
@@ -183,16 +185,15 @@ public abstract class TileSet
}
/**
* Creates a {@link Tile} object from this tileset corresponding to
* the specified tile id and returns that tile. A null tile will never
* be returned, but one with an error image may be returned if a
* problem occurs loading the underlying tileset image.
* Creates a {@link Tile} object from this tileset corresponding to the specified tile id and
* returns that tile. A null tile will never be returned, but one with an error image may be
* returned if a problem occurs loading the underlying tileset image.
*
* @param tileIndex the index of the tile in the tileset. Tile indexes
* start with zero as the upper left tile and increase by one as the
* tiles move left to right and top to bottom over the source image.
* @param zations colorizations to be applied to the tile image prior
* to returning it. These may be null for uncolorized images.
* @param tileIndex the index of the tile in the tileset. Tile indexes start with zero as the
* upper left tile and increase by one as the tiles move left to right and top to bottom over
* the source image.
* @param zations colorizations to be applied to the tile image prior to returning it. These
* may be null for uncolorized images.
*
* @return the tile object.
*/
@@ -200,8 +201,8 @@ public abstract class TileSet
{
Tile tile = null;
// first look in the active set; if it's in use by anyone or in
// the cache, it will be in the active set
// first look in the active set; if it's in use by anyone or in the cache, it will be in
// the active set
synchronized (_atiles) {
_key.tileSet = this;
_key.tileIndex = tileIndex;
@@ -229,10 +230,9 @@ public abstract class TileSet
}
/**
* Returns a prepared version of the image that would be used by the
* tile at the specified index. Because tilesets are often used simply
* to provide access to a collection of uniform images, this method is
* provided to bypass the creation of a {@link Tile} object when all
* Returns a prepared version of the image that would be used by the tile at the specified
* index. Because tilesets are often used simply to provide access to a collection of uniform
* images, this method is provided to bypass the creation of a {@link Tile} object when all
* that is desired is access to the underlying image.
*/
public Mirage getTileMirage (int tileIndex)
@@ -241,36 +241,32 @@ public abstract class TileSet
}
/**
* Returns a prepared version of the image that would be used by the
* tile at the specified index. Because tilesets are often used simply
* to provide access to a collection of uniform images, this method is
* provided to bypass the creation of a {@link Tile} object when all
* Returns a prepared version of the image that would be used by the tile at the specified
* index. Because tilesets are often used simply to provide access to a collection of uniform
* images, this method is provided to bypass the creation of a {@link Tile} object when all
* that is desired is access to the underlying image.
*/
public Mirage getTileMirage (int tileIndex, Colorization[] zations)
{
Rectangle bounds = computeTileBounds(tileIndex);
Rectangle bounds = computeTileBounds(tileIndex, new Rectangle());
Mirage mirage = null;
if (checkTileIndex(tileIndex)) {
if (_improv == null) {
Log.warning("Aiya! Tile set missing image provider " +
"[path=" + _imagePath + "].");
Log.warning("Aiya! Tile set missing image provider [path=" + _imagePath + "].");
} else {
mirage = _improv.getTileImage(_imagePath, bounds, zations);
}
}
if (mirage == null) {
mirage = new BufferedMirage(
ImageUtil.createErrorImage(bounds.width, bounds.height));
mirage = new BufferedMirage(ImageUtil.createErrorImage(bounds.width, bounds.height));
}
return mirage;
}
/**
* Returns the entire, raw, uncut, unprepared tileset source image.
* Don't use this method unless you know what you're doing! This image
* should not be rendered directly to the screen, you should obtain a
* tile ({@link #getTile}), or a tile mirage ({@link #getTileMirage}).
* Returns the entire, raw, uncut, unprepared tileset source image. Don't use this method
* unless you know what you're doing! This image should not be rendered directly to the screen,
* you should obtain a tile ({@link #getTile}), or a tile mirage ({@link #getTileMirage}).
*/
public BufferedImage getRawTileSetImage ()
{
@@ -278,22 +274,20 @@ public abstract class TileSet
}
/**
* Returns the raw (unprepared) image that would be used by the tile
* at the specified index. Don't use this method unless you know what
* you're doing! If you're going to be painting this image onto the
* screen directly, use {@link #getTileMirage} because that prepares
* the image for display. Only use this if you're going to do further
* processing and prepare the subsequent image for display onscreen.
* Returns the raw (unprepared) image that would be used by the tile at the specified
* index. Don't use this method unless you know what you're doing! If you're going to be
* painting this image onto the screen directly, use {@link #getTileMirage} because that
* prepares the image for display. Only use this if you're going to do further processing and
* prepare the subsequent image for display onscreen.
*/
public BufferedImage getRawTileImage (int tileIndex)
{
Rectangle bounds = computeTileBounds(tileIndex);
Rectangle bounds = computeTileBounds(tileIndex, new Rectangle());
BufferedImage img = null;
if (checkTileIndex(tileIndex)) {
BufferedImage timg = getRawTileSetImage();
if (timg != null) {
img = timg.getSubimage(bounds.x, bounds.y,
bounds.width, bounds.height);
img = timg.getSubimage(bounds.x, bounds.y, bounds.width, bounds.height);
} else {
Log.warning("Missing source image " + this);
}
@@ -305,11 +299,10 @@ public abstract class TileSet
}
/**
* Returns colorizations for the specified tile image. The default is
* to return any colorizations associated with the tileset via a call
* to {@link #clone(Colorization[])}, however derived classes may have
* dynamic colorization policies that look up colorization assignments
* from the supplied colorizer.
* Returns colorizations for the specified tile image. The default is to return any
* colorizations associated with the tileset via a call to {@link #clone(Colorization[])},
* however derived classes may have dynamic colorization policies that look up colorization
* assignments from the supplied colorizer.
*/
protected Colorization[] getColorizations (int tileIndex, Colorizer rizer)
{
@@ -325,30 +318,16 @@ public abstract class TileSet
if (tileIndex >= 0 && tileIndex < tcount) {
return true;
} else {
Log.warning("Requested invalid tile [tset=" + this +
", index=" + tileIndex + "].");
Log.warning("Requested invalid tile [tset=" + this + ", index=" + tileIndex + "].");
Thread.dumpStack();
return false;
}
}
/**
* Computes and returns the bounds for the specified tile based on the
* mechanism used by the derived class to do such things. The width
* and height of the bounds should be the size of the tile image and
* the x and y offset should be the offset in the tileset image for
* the image data of the specified tile.
*
* @param tileIndex the index of the tile whose bounds are to be
* computed.
*/
protected abstract Rectangle computeTileBounds (int tileIndex);
/**
* Creates a blank tile of the appropriate type for this tileset.
*
* @return a blank tile ready to be populated with its image and
* metadata.
* @return a blank tile ready to be populated with its image and metadata.
*/
protected Tile createTile ()
{
@@ -356,14 +335,12 @@ public abstract class TileSet
}
/**
* Initializes the supplied tile. Derived classes can override this
* method to add in their own tile information, but should be sure to
* call <code>super.initTile()</code>.
* Initializes the supplied tile. Derived classes can override this method to add in their own
* tile information, but should be sure to call <code>super.initTile()</code>.
*
* @param tile the tile to initialize.
* @param tileIndex the index of the tile.
* @param zations the colorizations to be used when generating the
* tile image.
* @param zations the colorizations to be used when generating the tile image.
*/
protected void initTile (Tile tile, int tileIndex, Colorization[] zations)
{
@@ -383,8 +360,8 @@ public abstract class TileSet
}
/**
* Reports statistics detailing the image manager cache performance
* and the current size of the cached images.
* Reports statistics detailing the image manager cache performance and the current size of the
* cached images.
*/
protected void reportCachePerformance ()
{
@@ -415,9 +392,8 @@ public abstract class TileSet
}
/**
* Derived classes can override this, calling
* <code>super.toString(buf)</code> and then appending additional
* information to the buffer.
* Derived classes can override this, calling <code>super.toString(buf)</code> and then
* appending additional information to the buffer.
*/
protected void toString (StringBuilder buf)
{
@@ -445,8 +421,7 @@ public abstract class TileSet
/** A map containing weak references to all "active" tiles. */
protected static HashMap _atiles = new HashMap();
/** A key used to look things up in the cache without creating
* craploads of keys unduly. */
/** A key used to look things up in the cache without creating craploads of keys unduly. */
protected static Tile.Key _key = new Tile.Key(null, 0, null);
/** Throttle our cache status logging to once every 300 seconds. */
@@ -33,11 +33,10 @@ import com.threerings.media.image.Colorization;
import com.threerings.media.tile.util.TileSetTrimmer;
/**
* An object tileset in which the objects have been trimmed to the
* smallest possible images that still contain all of their
* non-transparent pixels. The objects' origins are adjusted so that the
* objects otherwise behave exactly as the untrimmed objects and are thus
* interchangeable (and more memory efficient).
* An object tileset in which the objects have been trimmed to the smallest possible images that
* still contain all of their non-transparent pixels. The objects' origins are adjusted so that the
* objects otherwise behave exactly as the untrimmed objects and are thus interchangeable (and more
* memory efficient).
*/
public class TrimmedObjectTileSet extends TileSet
implements RecolorableTileSet
@@ -48,9 +47,15 @@ public class TrimmedObjectTileSet extends TileSet
return _bounds.length;
}
// documentation inherited
public Rectangle computeTileBounds (int tileIndex, Rectangle bounds)
{
bounds.setBounds(_bounds[tileIndex]);
return bounds;
}
/**
* Returns the x coordinate of the spot associated with the specified
* tile index.
* Returns the x coordinate of the spot associated with the specified tile index.
*/
public int getXSpot (int tileIdx)
{
@@ -58,8 +63,7 @@ public class TrimmedObjectTileSet extends TileSet
}
/**
* Returns the y coordinate of the spot associated with the specified
* tile index.
* Returns the y coordinate of the spot associated with the specified tile index.
*/
public int getYSpot (int tileIdx)
{
@@ -67,9 +71,8 @@ public class TrimmedObjectTileSet extends TileSet
}
/**
* Returns the orientation of the spot associated with the specified
* tile index, or <code>-1</code> if the object has no associated
* spot.
* Returns the orientation of the spot associated with the specified tile index, or
* <code>-1</code> if the object has no associated spot.
*/
public int getSpotOrient (int tileIdx)
{
@@ -77,8 +80,8 @@ public class TrimmedObjectTileSet extends TileSet
}
/**
* Returns the constraints associated with the specified tile index, or
* <code>null</code> if the object has no associated constraints.
* Returns the constraints associated with the specified tile index, or <code>null</code> if
* the object has no associated constraints.
*/
public String[] getConstraints (int tileIdx)
{
@@ -116,12 +119,6 @@ public class TrimmedObjectTileSet extends TileSet
return _ometrics[tileIdx].height;
}
// documentation inherited
protected Rectangle computeTileBounds (int tileIndex)
{
return _bounds[tileIndex];
}
// documentation inherited
protected Colorization[] getColorizations (int tileIndex, Colorizer rizer)
{
@@ -170,12 +167,10 @@ public class TrimmedObjectTileSet extends TileSet
}
/**
* Creates a trimmed object tileset from the supplied source object
* tileset. The image path must be set by hand to the appropriate path
* based on where the image data that is written to the
* <code>destImage</code> parameter is actually stored on the file
* system. See {@link TileSetTrimmer#trimTileSet} for further
* information.
* Creates a trimmed object tileset from the supplied source object tileset. The image path
* must be set by hand to the appropriate path based on where the image data that is written to
* the <code>destImage</code> parameter is actually stored on the file system. See {@link
* TileSetTrimmer#trimTileSet} for further information.
*/
public static TrimmedObjectTileSet trimObjectTileSet (
ObjectTileSet source, OutputStream destImage)
@@ -185,8 +180,7 @@ public class TrimmedObjectTileSet extends TileSet
tset.setName(source.getName());
int tcount = source.getTileCount();
// System.out.println("Trimming object tile set " +
// "[source=" + source + "].");
// System.out.println("Trimming object tile set [source=" + source + "].");
// create our metrics arrays
tset._bounds = new Rectangle[tcount];
@@ -232,21 +226,17 @@ public class TrimmedObjectTileSet extends TileSet
}
// create the trimmed tileset image
TileSetTrimmer.TrimMetricsReceiver tmr =
new TileSetTrimmer.TrimMetricsReceiver() {
public void trimmedTile (int tileIndex, int imageX, int imageY,
int trimX, int trimY,
int trimWidth, int trimHeight) {
tset._ometrics[tileIndex].x -= trimX;
tset._ometrics[tileIndex].y -= trimY;
tset._bounds[tileIndex] =
new Rectangle(imageX, imageY, trimWidth, trimHeight);
}
};
TileSetTrimmer.TrimMetricsReceiver tmr = new TileSetTrimmer.TrimMetricsReceiver() {
public void trimmedTile (int tileIndex, int imageX, int imageY,
int trimX, int trimY, int trimWidth, int trimHeight) {
tset._ometrics[tileIndex].x -= trimX;
tset._ometrics[tileIndex].y -= trimY;
tset._bounds[tileIndex] = new Rectangle(imageX, imageY, trimWidth, trimHeight);
}
};
TileSetTrimmer.trimTileSet(source, destImage, tmr);
// Log.info("Trimmed object tileset " +
// "[bounds=" + StringUtil.toString(tset._bounds) +
// Log.info("Trimmed object tileset [bounds=" + StringUtil.toString(tset._bounds) +
// ", metrics=" + StringUtil.toString(tset._ometrics) + "].");
return tset;
@@ -276,17 +266,17 @@ public class TrimmedObjectTileSet extends TileSet
return StringUtil.fieldsToString(this);
}
/** Increase this value when object's serialized state is impacted
* by a class change (modification of fields, inheritance). */
/** Increase this value when object's serialized state is impacted by a class change
* (modification of fields, inheritance). */
private static final long serialVersionUID = 2;
}
/** Contains the width and height of each object tile and the offset
* into the tileset image of their image data. */
/** Contains the width and height of each object tile and the offset into the tileset image of
* their image data. */
protected Rectangle[] _bounds;
/** Contains the origin offset for each object tile and the object
* footprint width and height (in tile units). */
/** Contains the origin offset for each object tile and the object footprint width and height
* (in tile units). */
protected Rectangle[] _ometrics;
/** Extra bits relating to our objects. */
@@ -295,7 +285,7 @@ public class TrimmedObjectTileSet extends TileSet
/** Colorization classes that apply to our objects. */
protected String[] _zations;
/** Increase this value when object's serialized state is impacted by
* a class change (modification of fields, inheritance). */
/** Increase this value when object's serialized state is impacted by a class change
* (modification of fields, inheritance). */
private static final long serialVersionUID = 1;
}
@@ -27,19 +27,17 @@ import java.awt.Rectangle;
import com.samskivert.util.StringUtil;
/**
* Behaves just like a regular tile, but contains a "trimmed" image which
* is one where the source image has been trimmed to the smallest
* rectangle that contains all the non-transparent pixels of the original
* image.
* Behaves just like a regular tile, but contains a "trimmed" image which is one where the source
* image has been trimmed to the smallest rectangle that contains all the non-transparent pixels of
* the original image.
*/
public class TrimmedTile extends Tile
{
/**
* Sets the trimmed bounds of this tile.
*
* @param tbounds contains the width and height of the
* <em>untrimmed</em> tile, but the x and y offset of the
* <em>trimmed</em> tile image in the original untrimmed tile image.
* @param tbounds contains the width and height of the <em>untrimmed</em> tile, but the x and y
* offset of the <em>trimmed</em> tile image in the original untrimmed tile image.
*/
public void setTrimmedBounds (Rectangle tbounds)
{
@@ -65,13 +63,12 @@ public class TrimmedTile extends Tile
}
/**
* Fills in the bounds of the trimmed image within the coordinate
* system defined by the complete virtual tile.
* Fills in the bounds of the trimmed image within the coordinate system defined by the
* complete virtual tile.
*/
public void getTrimmedBounds (Rectangle tbounds)
{
tbounds.setBounds(_tbounds.x, _tbounds.y,
_mirage.getWidth(), _mirage.getHeight());
tbounds.setBounds(_tbounds.x, _tbounds.y, _mirage.getWidth(), _mirage.getHeight());
}
// documentation inherited
@@ -30,8 +30,8 @@ import com.threerings.media.image.Colorization;
import com.threerings.media.tile.util.TileSetTrimmer;
/**
* Contains the necessary information to create a set of trimmed tiles
* from a base image and the associated trim metrics.
* Contains the necessary information to create a set of trimmed tiles from a base image and the
* associated trim metrics.
*/
public class TrimmedTileSet extends TileSet
{
@@ -42,9 +42,10 @@ public class TrimmedTileSet extends TileSet
}
// documentation inherited
protected Rectangle computeTileBounds (int tileIndex)
public Rectangle computeTileBounds (int tileIndex, Rectangle bounds)
{
return _obounds[tileIndex];
bounds.setBounds(_obounds[tileIndex]);
return bounds;
}
// documentation inherited
@@ -61,14 +62,12 @@ public class TrimmedTileSet extends TileSet
}
/**
* Creates a trimmed tileset from the supplied source tileset. The
* image path must be set by hand to the appropriate path based on
* where the image data that is written to the <code>destImage</code>
* parameter is actually stored on the file system. See {@link
* Creates a trimmed tileset from the supplied source tileset. The image path must be set by
* hand to the appropriate path based on where the image data that is written to the
* <code>destImage</code> parameter is actually stored on the file system. See {@link
* TileSetTrimmer#trimTileSet} for further information.
*/
public static TrimmedTileSet trimTileSet (
TileSet source, OutputStream destImage)
public static TrimmedTileSet trimTileSet (TileSet source, OutputStream destImage)
throws IOException
{
final TrimmedTileSet tset = new TrimmedTileSet();
@@ -79,36 +78,32 @@ public class TrimmedTileSet extends TileSet
// grab the dimensions of the original tiles
for (int ii = 0; ii < tcount; ii++) {
tset._tbounds[ii] = source.computeTileBounds(ii);
tset._tbounds[ii] = source.computeTileBounds(ii, new Rectangle());
}
// create the trimmed tileset image
TileSetTrimmer.TrimMetricsReceiver tmr =
new TileSetTrimmer.TrimMetricsReceiver() {
public void trimmedTile (int tileIndex, int imageX, int imageY,
int trimX, int trimY,
int trimWidth, int trimHeight) {
tset._tbounds[tileIndex].x = trimX;
tset._tbounds[tileIndex].y = trimY;
tset._obounds[tileIndex] =
new Rectangle(imageX, imageY, trimWidth, trimHeight);
}
};
TileSetTrimmer.TrimMetricsReceiver tmr = new TileSetTrimmer.TrimMetricsReceiver() {
public void trimmedTile (int tileIndex, int imageX, int imageY,
int trimX, int trimY, int trimWidth, int trimHeight) {
tset._tbounds[tileIndex].x = trimX;
tset._tbounds[tileIndex].y = trimY;
tset._obounds[tileIndex] = new Rectangle(imageX, imageY, trimWidth, trimHeight);
}
};
TileSetTrimmer.trimTileSet(source, destImage, tmr);
return tset;
}
/** The width and height of the trimmed tile, and the x and y offset
* of the trimmed image within our tileset image. */
/** The width and height of the trimmed tile, and the x and y offset of the trimmed image
* within our tileset image. */
protected Rectangle[] _obounds;
/** The width and height of the untrimmed image and the x and y offset
* within the untrimmed image at which the trimmed image should be
* rendered. */
/** The width and height of the untrimmed image and the x and y offset within the untrimmed
* image at which the trimmed image should be rendered. */
protected Rectangle[] _tbounds;
/** Increase this value when object's serialized state is impacted by
* a class change (modification of fields, inheritance). */
/** Increase this value when object's serialized state is impacted by a class change
* (modification of fields, inheritance). */
private static final long serialVersionUID = 1;
}
@@ -27,11 +27,10 @@ import java.awt.image.BufferedImage;
import com.threerings.geom.GeomUtil;
/**
* A uniform tileset is one that is composed of tiles that are all the
* same width and height and are arranged into rows, with each row having
* the same number of tiles except possibly the final row which can
* contain the same as or less than the number of tiles contained by the
* previous rows.
* A uniform tileset is one that is composed of tiles that are all the same width and height and
* are arranged into rows, with each row having the same number of tiles except possibly the final
* row which can contain the same as or less than the number of tiles contained by the previous
* rows.
*/
public class UniformTileSet extends TileSet
{
@@ -44,6 +43,14 @@ public class UniformTileSet extends TileSet
return perRow * perCol;
}
// documentation inherited
public Rectangle computeTileBounds (int tileIndex, Rectangle bounds)
{
BufferedImage tsimg = getRawTileSetImage();
GeomUtil.getTile(tsimg.getWidth(), tsimg.getHeight(), _width, _height, tileIndex, bounds);
return bounds;
}
/**
* Specifies the width of the tiles in this tileset.
*/
@@ -76,14 +83,6 @@ public class UniformTileSet extends TileSet
return _height;
}
// documentation inherited
protected Rectangle computeTileBounds (int tileIndex)
{
BufferedImage tsimg = getRawTileSetImage();
return GeomUtil.getTile(tsimg.getWidth(), tsimg.getHeight(),
_width, _height, tileIndex);
}
// documentation inherited
protected void toString (StringBuilder buf)
{