//
// Triple Play - utilities for use in PlayN-based games
// Copyright (c) 2011-2013, Three Rings Design, Inc. - All rights reserved.
// http://github.com/threerings/tripleplay/blob/master/LICENSE

package tripleplay.ui.bgs;

import pythagoras.f.IDimension;

import playn.core.Image;
import playn.core.ImmediateLayer;
import playn.core.Surface;

import tripleplay.ui.Background;

/**
 * Displays a background image, centered in the space defined for the background and cropped.
 */
public class CroppedImageBackground extends Background
{
    public CroppedImageBackground (Image image) {
        _image = image;
    }

    @Override protected Instance instantiate (IDimension size) {
        final float swidth = size.width(),   sheight = size.height();
        float iwidth = _image.width(), iheight = _image.height();
        final float sx, sy, dx, dy;
        if (swidth > iwidth) {
            sx = 0;
            dx = (swidth - iwidth)/2;
        } else {
            sx = (iwidth - swidth)/2;
            dx = 0;
        }
        if (sheight > iheight) {
            sy = 0;
            dy = (sheight - iheight)/2;
        } else {
            sy = (iheight - sheight)/2;
            dy = 0;
        }
        return new LayerInstance(size, new ImmediateLayer.Renderer() {
            public void render (Surface surf) {
                if (alpha != null) surf.setAlpha(alpha);
                surf.drawImage(_image, dx, dy, swidth, sheight, sx, sy, swidth, sheight);
            }
        });
    }

    protected final Image _image;
}

@@ -471,17 +471,106 @@
 cropped.
+ If%0A * the image is smaller than the needed space, in either dimension, it will be tiled.
 %0A
-
  */%0Apubl
@@ -846,16 +846,22 @@
         
+final 
 float iw
@@ -934,21 +934,106 @@
 oat 
-sx, sy, dx, d
+cwidth = Math.min(swidth, iwidth), cheight = Math.min(sheight, iheight);%0A        final float sx, s
 y;%0A 
@@ -1086,46 +1086,8 @@
  0;%0A
-            dx = (swidth - iwidth)/2;%0A
     
@@ -1141,28 +1141,8 @@
 /2;%0A
-            dx = 0;%0A
     
@@ -1204,48 +1204,8 @@
  0;%0A
-            dy = (sheight - iheight)/2;%0A
     
@@ -1261,28 +1261,8 @@
 /2;%0A
-            dy = 0;%0A
     
@@ -1443,16 +1443,304 @@
 alpha);%0A
+                float dy = 0;%0A                while (dy %3C sheight) %7B%0A                    float dheight = Math.min(cheight, sheight-dy);%0A                    float dx = 0;%0A                    while (dx %3C swidth) %7B%0A                        float dwidth = Math.min(cwidth, swidth-dx);%0A        
         
@@ -1778,25 +1778,25 @@
 dx, dy, 
-s
+d
 width, 
-s
+d
 height, 
@@ -1807,17 +1807,17 @@
 sy, 
-s
+d
 width, 
-s
+d
 heig
@@ -1813,32 +1813,145 @@
 idth, dheight);%0A
+                        dx += cwidth;%0A                    %7D%0A                    dy += cheight;%0A                %7D%0A
             %7D%0A  

Improve behavior when source image is smaller than bg space.