Friday, November 28, 2014

Conway's BufferedImageOp of Life

    protected class ConwayImageOp implements BufferedImageOp {

        @Override
        public BufferedImage filter(BufferedImage bi, BufferedImage bout) {
            int width = bi.getWidth();
            int height = bi.getHeight();
            int[] rgbArray = new int[bi.getWidth() * bi.getHeight()];
            int[] modArray = new int[bi.getWidth() * bi.getHeight()];
            rgbArray = bi.getRGB(0, 0, bi.getWidth(), bi.getHeight(), rgbArray, 0, bi.getWidth());
            int peer;
            int x, y, xr, yr;
            int[][] karray = {
                {-1, -1}, {-1, 0}, {-1, 1},
                {0,  -1},           {0, 1},
                {1, -1},  {1, 0},   {1,  1}
            };

            for (int index = 0, mi = rgbArray.length; index < mi; index++) {                
                int[] counts = new int[24];
                x = index % bi.getWidth();
                y = index / bi.getWidth();
                for (int m = 0, q = karray.length; m < q; m++) {
                    if (karray[m] != null) {
                        xr = x + karray[m][0];
                        yr = y + karray[m][1];

                        if ((karray[m] != null) && (((xr >= 0) && (yr >= 0) && (xr < width) && (yr < height)))) {
                            peer = rgbArray[(yr * width) + xr];
                            for (int i = 0; i < 24; i++) {
                                if (((peer >> i) & 1) == 1) counts[i]++;
                            }
                        }

                    }
                }
                int current = rgbArray[index];
                int conway = 0;
                for (int pix = 0; pix < 24; pix++) {
                    conway |=  (Conway(((current >> pix) & 1), counts[pix]) << pix);
                }
                modArray[index] = conway | 0xFF000000;
            }
            bout.setRGB(0, 0, bout.getWidth(), bout.getHeight(), modArray, 0, bout.getWidth());
            return bout;
        }
        
        int Conway(int current, int sum) {
            if (sum == 3) return 1;
            if ((current == 1) && (sum == 2)) return 1;
            return 0;
        }

        @Override
        public Rectangle2D getBounds2D(BufferedImage bi) {
            return null;
        }

        @Override
        public BufferedImage createCompatibleDestImage(BufferedImage bi, ColorModel cm) {
            return new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_ARGB);
        }

        @Override
        public Point2D getPoint2D(Point2D pd, Point2D pd1) {
            return null;
        }

        @Override
        public RenderingHints getRenderingHints() {
            return null;
        }
    }

No comments: