Jump to content

  • Log In with Google      Sign In   
  • Create Account


Simplifying Dynamic 2D Bounding


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
3 replies to this topic

#1 epicpunnum   Members   -  Reputation: 454

Like
0Likes
Like

Posted 11 October 2012 - 05:56 PM

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.

Attached Thumbnails

  • bigcollisions.png
  • spritebounds.PNG


Sponsor:

#2 Faelenor   Members   -  Reputation: 394

Like
0Likes
Like

Posted 12 October 2012 - 05:11 AM

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.

#3 epicpunnum   Members   -  Reputation: 454

Like
0Likes
Like

Posted 12 October 2012 - 07:44 AM

I would probably go for pixel perfect collision detection using a hierarchy of boxes to speed up things instead.

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.

#4 SHC   Members   -  Reputation: 124

Like
0Likes
Like

Posted 15 April 2013 - 05:27 AM

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; }

}

Harsha...ch





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS