• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
epicpunnum

Simplifying Dynamic 2D Bounding

3 posts in this topic

Hello everyone!
A few months ago I began work on an engine to base a Java Game upon. When the concept of collision handling would be tackled, and I realized that managing collisions using rectangles would be a bad move in terms of aesthetics and accuracy. However, pixel by pixel detection also seemed bad as well, due to being horribly inefficient.
I settled for a middle ground, opting to instead have a class that creates a Polygon based upon an image, by scanning the sides of the image looking for opaque pixels over given intervals (as seen in one of my attachments). It then tries to optimize it by removing unnecessary points (like ones that are all part of the same line, or ones that are touching).
The results of my code are seen in another attachments, showing the original image, and then each of the bounding boxes using the 7 different scanning types in order (see code for order).

As one can see, there's a lot of room for improvement - mainly that the lines will intersect due mostly to the way I have it scan (scans the entire side of an image). However, I don't want to risk the code missing necessary points in the shape. So I guess my question would be: How could I simplify the shape more?


For those who would like the code, I put it below. I would definitely recommend pulling up the Polygon API.
[source lang="java"]import java.awt.Image;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.util.Arrays;
/**
* @author Ian_Donovan
* @date 10-11-12
*/
public class SpriteBounds extends Polygon{
//Scan is an enumerated type used to choose how many sides it scans.
public static enum Scan{
HORIZONTAL, VERTICAL, SANS_LEFT,
SANS_DOWN, SANS_RIGHT, SANS_UP, FULL
}

//default values for scanning below
private int interval = 10;
private Scan s = Scan.HORIZONTAL;


//constructors
//a lot of them, TODO: clean up

public SpriteBounds(Image spr){
super();
generatePoints(spr);
}

public SpriteBounds(Image spr, int interval){
super();
this.interval = interval;
generatePoints(spr);
}

public SpriteBounds(Image spr, Scan scanType){
super();
s = scanType;
generatePoints(spr);
}

public SpriteBounds(Image spr, int interval, Scan scanType){
super();
this.interval = interval;
s = scanType;
generatePoints(spr);
}

public SpriteBounds(int[] xPts, int[] yPts){
super(xPts, yPts, findNpoints(xPts,yPts));
optimize();
}

//used to manually declare npoints for constructors
private static final int findNpoints(int[] xPts, int[] yPts){
if (xPts.length <= yPts.length)
return xPts.length;
else
return yPts.length;
}

//custom methods

private void generatePoints(Image spr){
//makes sure dimensions are loaded
while(spr.getWidth(null)==-1 && spr.getHeight(null)==-1)
continue;
System.out.println("w: "+spr.getWidth(null)+"\th: "+spr.getHeight(null));

BufferedImage bsp = new BufferedImage(spr.getWidth(null),
spr.getHeight(null), BufferedImage.TYPE_INT_ARGB);
bsp.getGraphics().drawImage(spr,0,0,null);

if (s==Scan.HORIZONTAL || s==Scan.SANS_DOWN || s==Scan.SANS_RIGHT ||
s==Scan.SANS_UP || s==Scan.FULL)
scanLeft(bsp);
if (s==Scan.VERTICAL || s==Scan.SANS_LEFT || s==Scan.SANS_RIGHT ||
s==Scan.SANS_UP || s==Scan.FULL)
scanDown(bsp);
if (s==Scan.HORIZONTAL || s==Scan.SANS_LEFT || s==Scan.SANS_DOWN ||
s==Scan.SANS_UP || s==Scan.FULL)
scanRight(bsp);
if (s==Scan.VERTICAL || s==Scan.SANS_LEFT || s==Scan.SANS_DOWN ||
s==Scan.SANS_RIGHT || s==Scan.FULL)
scanUp(bsp);
optimize();
}


/**
* POINT SCANNING METHODS
* NOTE: Scanning counter-clockwise (left,down,right,up cycle)
*/

private final void scanLeft(BufferedImage bsp){
//left sides going down
for (int r=0; r<bsp.getHeight(); r+=interval)
for (int c=0; c<bsp.getWidth(); c++){
if ( !isTransparent(bsp.getRGB(c,r)) ){
this.addPoint(c,r);
break;
}
}
}

private final void scanDown(BufferedImage bsp){
//scans bottom sides from left
for (int c=bsp.getWidth()-1; c>=0; c-=interval)
for (int r=bsp.getHeight()-1; r>=0; r--){
if ( !isTransparent(bsp.getRGB(c,r)) ){
this.addPoint(c,r);
break;
}
}
}

private final void scanRight(BufferedImage bsp){
//right sides coming back up
for (int r=bsp.getHeight()-1; r>=0; r-=interval)
for (int c=bsp.getWidth()-1; c>=0; c--){
if ( !isTransparent(bsp.getRGB(c,r)) ){
this.addPoint(c,r);
break;
}
}
}

private final void scanUp(BufferedImage bsp){
//scans top from the right
for (int c=bsp.getWidth()-1; c>=0; c-=interval)
for (int r=0; r<bsp.getHeight(); r++){
if ( !isTransparent(bsp.getRGB(c,r)) ){
this.addPoint(c,r);
break;
}
}
}

private static final boolean isTransparent(int value){
int alpha = (value>>24) & 0xff; //0-255
return (alpha==0);
}


//optimization methods

private void optimize(){
optimizePoints();
optimizeSlope();
}

/**
* Checks each point for duplicates or adjacent ones
* Only checks ones within one element of it, so
* shapes are not distorted.
*/
private final void optimizePoints(){
for (int i=0; i<npoints-1; i++){
if( isNearPoint(i,i+1) )
removePointAt(i);
}
}

/** @return - if points indexes a & b are within 1 pixel */
private final boolean isNearPoint(int a, int b){
int x1 = this.xpoints[a];
int y1 = this.ypoints[b];
int x2 = this.xpoints[a];
int y2 = this.ypoints[b];
return (Math.abs(x1-x2)<=1 && Math.abs(y1-y2)<=1);
}

/**
* Searches for similar slopes among three points
* Removes middle points when checked, leaving endpoints
* Uses Basic slope formula, and checks for vertical lines
*/
private final void optimizeSlope(){
for (int i=1; i<npoints-1; i++){
double s1 = getSlopeAt(i,i-1);
double s2 = getSlopeAt(i,i+1);
if (Math.abs(s1-s2)<0.001) //if close enough
removePointAt(i);
}
}

/**
* @param a,b - indexes of xpoints/ypoints
* @return - slope of points with indexes a and b
* @return - Double.MIN_VALUE if out of bounds or other
* @return -
*/
private final double getSlopeAt(int a, int b){
try{
int x1 = this.xpoints[a];
int y1 = this.ypoints[a];
int x2 = this.xpoints[b];
int y2 = this.ypoints[b];
return (y1-y2)/(x1-x2);
}
catch(IndexOutOfBoundsException e){
//out of bounds of xpoints or ypoints
return Double.MIN_VALUE;
}
catch(ArithmeticException e){
//divide by zero (vertical line)
return Double.MAX_VALUE;
}
}


/**
* Removes a point of a specific coordinates x and y
* @return - amount of duplicates of point.
* NOTE: Fails if return int != 1
*/
public final int removePoint(int x, int y){
int count = 0;
//counts number of occurances
for (int i=0; i<this.npoints; i++)
if (pointExistsAt(x,y,i))
count++;
if (count!=1)
return count;
else
for (int i=0; i<this.npoints; i++)
if(pointExistsAt(x,y,i)){
removePointAt(i);
return 1;
}
return -1;
}

public final void removeAllPoint(int x, int y){
for (int i=0; i<this.npoints; i++)
if(pointExistsAt(x,y,i))
removePointAt(i);
}

private final void removePointAt(int i){
removeArrayElement(this.xpoints,i);
removeArrayElement(this.ypoints,i);
}

/** @param i - index of point arrays xpoints and ypoints */
private final boolean pointExistsAt(int x, int y, int i){
try{
return (this.xpoints[i]==x && this.ypoints[i]==y);
}
catch(ArrayIndexOutOfBoundsException e){
return false;
}
}

private static final void removeArrayElement(int[] arr, int pos){
int[] result = new int[arr.length-1];
int[] half1 = Arrays.copyOf(arr, pos);
int[] half2 = Arrays.copyOfRange(arr,pos+1,arr.length-1);
for(int i=0; i<half1.length; i++)
result[i]=half1[i];
for(int i=0; i<half2.length; i++)
result[i+pos]=half2[i];
arr = result;
}

//GETTERS AND SETTERS FOR VARIABLES

public final void moveTo(int x, int y){
setX(x);
setY(y);
}

public final void setX(int val){
this.translate(val-getX(), 0);
}
public final void setY(int val){
this.translate(val-getX(), 0);
}

public final int getX(){ return this.bounds.x; }
public final int getY(){ return this.bounds.y; }
}
[/source]

First post on this form so apologies if I'm in the wrong place, or doing something wrong by putting in this huge block of code.
0

Share this post


Link to post
Share on other sites
That's an interesting approach, but I would probably go for pixel perfect collision detection using a hierarchy of boxes to speed up things instead.
0

Share this post


Link to post
Share on other sites
[quote name='Faelenor' timestamp='1350040314' post='4989428']
I would probably go for pixel perfect collision detection using a hierarchy of boxes to speed up things instead.
[/quote]
Why's that? Polygons without any drawing functions are essentially two arrays of ints. If they're created static for all instances at the creation of the very first, I would think that it would ultimately save computation and image manipulation.
Side note: My ultimate plan is to use a general Rectangle provided by the Polygon for primary checks, and then use the actual Polygon if it is intersecting the Rectangle, so there would still be an element of that hierarchy.
0

Share this post


Link to post
Share on other sites

The code isn't viewable. So I'm posting again.

 

import java.awt.Image;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.util.Arrays;

/**
* @author Ian_Donovan
* @date 10-11-12
*/
public class SpriteBounds extends Polygon{

    //Scan is an enumerated type used to choose how many sides it scans.
    public static enum Scan{
        HORIZONTAL, VERTICAL, SANS_LEFT,
        SANS_DOWN, SANS_RIGHT, SANS_UP, FULL
    }

    //default values for scanning below
    private int interval = 10;
    private Scan s = Scan.HORIZONTAL;


    //constructors
    //a lot of them, TODO: clean up

    public SpriteBounds(Image spr){
        super();
        generatePoints(spr);
    }

    public SpriteBounds(Image spr, int interval){
        super();
        this.interval = interval;
        generatePoints(spr);
    }

    public SpriteBounds(Image spr, Scan scanType){
        super();
        s = scanType;
        generatePoints(spr);
    }

    public SpriteBounds(Image spr, int interval, Scan scanType){
        super();
        this.interval = interval;
        s = scanType;
        generatePoints(spr);
    }

    public SpriteBounds(int[] xPts, int[] yPts){
        super(xPts, yPts, findNpoints(xPts,yPts));
        optimize();
    }

    //used to manually declare npoints for constructors
    private static final int findNpoints(int[] xPts, int[] yPts){
        if (xPts.length <= yPts.length)
            return xPts.length;
        else
            return yPts.length;
    }

    //custom methods

    private void generatePoints(Image spr){
        //makes sure dimensions are loaded
        while(spr.getWidth(null)==-1 && spr.getHeight(null)==-1)
            continue;
        System.out.println("w: "+spr.getWidth(null)+"\th: "+spr.getHeight(null));

        BufferedImage bsp = new BufferedImage(spr.getWidth(null),
                                              spr.getHeight(null),
                                              BufferedImage.TYPE_INT_ARGB);
        bsp.getGraphics().drawImage(spr,0,0,null);

        if (s==Scan.HORIZONTAL || s==Scan.SANS_DOWN || s==Scan.SANS_RIGHT || s==Scan.SANS_UP || s==Scan.FULL)
            scanLeft(bsp);
            if (s==Scan.VERTICAL || s==Scan.SANS_LEFT || s==Scan.SANS_RIGHT || s==Scan.SANS_UP || s==Scan.FULL)
                scanDown(bsp);
                if (s==Scan.HORIZONTAL || s==Scan.SANS_LEFT || s==Scan.SANS_DOWN || s==Scan.SANS_UP || s==Scan.FULL)
                    scanRight(bsp);
                    if (s==Scan.VERTICAL || s==Scan.SANS_LEFT || s==Scan.SANS_DOWN || s==Scan.SANS_RIGHT || s==Scan.FULL)
                        scanUp(bsp);
                        optimize();
    }


    /**
     * POINT SCANNING METHODS
     * NOTE: Scanning counter-clockwise (left,down,right,up cycle)
     */

    private final void scanLeft(BufferedImage bsp){
        //left sides going down
        for (int r=0; r<bsp.getHeight(); r+=interval)
            for (int c=0; c<bsp.getWidth(); c++){
                if ( !isTransparent(bsp.getRGB(c,r)) ){
                    this.addPoint(c,r);
                    break;
                }
            }
    }

    private final void scanDown(BufferedImage bsp){
        //scans bottom sides from left
        for (int c=bsp.getWidth()-1; c>=0; c-=interval)
            for (int r=bsp.getHeight()-1; r>=0; r--){
                if ( !isTransparent(bsp.getRGB(c,r)) ){
                    this.addPoint(c,r);
                    break;
                }
            }
    }

    private final void scanRight(BufferedImage bsp){
        //right sides coming back up
        for (int r=bsp.getHeight()-1; r>=0; r-=interval)
            for (int c=bsp.getWidth()-1; c>=0; c--){
                if ( !isTransparent(bsp.getRGB(c,r)) ){
                    this.addPoint(c,r);
                    break;
                }
            }
    }

    private final void scanUp(BufferedImage bsp){
        //scans top from the right
        for (int c=bsp.getWidth()-1; c>=0; c-=interval)
            for (int r=0; r<bsp.getHeight(); r++){
                if ( !isTransparent(bsp.getRGB(c,r)) ){
                    this.addPoint(c,r);
                    break;
                }
            }
    }

    private static final boolean isTransparent(int value){
        int alpha = (value>>24) & 0xff; //0-255
        return (alpha==0);
    }


    //optimization methods

    private void optimize(){
        optimizePoints();
        optimizeSlope();
    }

    /**
     * Checks each point for duplicates or adjacent ones
     * Only checks ones within one element of it, so
     * shapes are not distorted.
     */
    private final void optimizePoints(){
        for (int i=0; i<npoints-1; i++){
            if( isNearPoint(i,i+1) )
                removePointAt(i);
        }
    }

    /**
     * @return - if points indexes a & b are within 1 pixel 
     */
    private final boolean isNearPoint(int a, int b){
        int x1 = this.xpoints[a];
        int y1 = this.ypoints[b];
        int x2 = this.xpoints[a];
        int y2 = this.ypoints[b];
        return (Math.abs(x1-x2)<=1 && Math.abs(y1-y2)<=1);
    }

    /**
     * Searches for similar slopes among three points
     * Removes middle points when checked, leaving endpoints
     * Uses Basic slope formula, and checks for vertical lines
     */
    private final void optimizeSlope(){
        for (int i=1; i<npoints-1; i++){
            double s1 = getSlopeAt(i,i-1);
            double s2 = getSlopeAt(i,i+1);
            if (Math.abs(s1-s2)<0.001) //if close enough
                removePointAt(i);
        }
    }

    /**
     * @param a,b - indexes of xpoints/ypoints
     * @return - slope of points with indexes a and b
     * @return - Double.MIN_VALUE if out of bounds or other
     * @return -
     */
    private final double getSlopeAt(int a, int b){
        try{
            int x1 = this.xpoints[a];
            int y1 = this.ypoints[a];
            int x2 = this.xpoints[b];
            int y2 = this.ypoints[b];
            return (y1-y2)/(x1-x2);
        }
        catch(IndexOutOfBoundsException e){
            //out of bounds of xpoints or ypoints
            return Double.MIN_VALUE;
        }
        catch(ArithmeticException e){
            //divide by zero (vertical line)
            return Double.MAX_VALUE;
        }
    }


    /**
     * Removes a point of a specific coordinates x and y
     * @return - amount of duplicates of point.
     * NOTE: Fails if return int != 1
     */
    public final int removePoint(int x, int y){
        int count = 0;
        //counts number of occurances
        for (int i=0; i<this.npoints; i++)
            if (pointExistsAt(x,y,i))
                count++;
            if (count!=1)
                return count;
            else
                for (int i=0; i<this.npoints; i++)
                    if(pointExistsAt(x,y,i)){
                        removePointAt(i);
                        return 1;
                    }
                    return -1;
    }

    public final void removeAllPoint(int x, int y){
        for (int i=0; i<this.npoints; i++)
            if(pointExistsAt(x,y,i))
                removePointAt(i);
    }

    private final void removePointAt(int i){
        removeArrayElement(this.xpoints,i);
        removeArrayElement(this.ypoints,i);
    }

    /**
     * @param i - index of point arrays xpoints and ypoints 
     */
    private final boolean pointExistsAt(int x, int y, int i){
        try{
            return (this.xpoints[i]==x && this.ypoints[i]==y);
        }
        catch(ArrayIndexOutOfBoundsException e){
            return false;
        }
    }

    private static final void removeArrayElement(int[] arr, int pos){
        int[] result = new int[arr.length-1];
        int[] half1 = Arrays.copyOf(arr, pos);
        int[] half2 = Arrays.copyOfRange(arr,pos+1,arr.length-1);
        for(int i=0; i<half1.length; i++)
            result[i]=half1[i];
        for(int i=0; i<half2.length; i++)
            result[i+pos]=half2[i];
        arr = result;
    }

    //GETTERS AND SETTERS FOR VARIABLES

    public final void moveTo(int x, int y){
        setX(x);
        setY(y);
    }

    public final void setX(int val){
        this.translate(val-getX(), 0);
    }

    public final void setY(int val){
        this.translate(val-getX(), 0);
    }

    public final int getX(){ return this.bounds.x; }
    public final int getY(){ return this.bounds.y; }

}
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0