Click here to Skip to main content
15,896,402 members
Articles / Web Development / ASP.NET

Fast Optimizing Rectangle Packing Algorithm for Building CSS Sprites

Rate me:
Please Sign up or sign in to vote.
4.90/5 (46 votes)
14 Jun 2011CPOL21 min read 313.4K   7.9K   60  
Describes a fast algorithm to pack a series of rectangles of varying widths and heights into an enclosing rectangle of minimum size
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Diagnostics;
using Mapper;
using System.Drawing;

/// <summary>
/// Version of MapperOptimalEfficiency that produces additional stats
/// </summary>
public class MapperOptimalEfficiency_AdditionalStats<S> : MapperOptimalEfficiency<S> where S : class, ISprite, new()
{
    ICanvas _canvas = null;
    List<IterationStats> _currentMappingIterationStats = null; 

	public MapperOptimalEfficiency_AdditionalStats(ICanvas canvas)
            : base(canvas)
    {
        _canvas = canvas;
    }

    /// <summary>
    /// See MapperIterative_Base
    /// </summary>
    /// <param name="canvas"></param>
    /// <param name="cutoffEfficiency"></param>
    /// <param name="maxNbrCandidateSprites"></param>
    public MapperOptimalEfficiency_AdditionalStats(ICanvas canvas, float cutoffEfficiency, int maxNbrCandidateSprites)
        : base(canvas, cutoffEfficiency, maxNbrCandidateSprites)
    {
        _canvas = canvas;
    }

    /// <summary>
    /// Does a mapping with the given images and returns the resulting stats.
    /// </summary>
    /// <param name="images"></param>
    /// <returns></returns>
    public DetailedSingleTestStats GetMappingStats(IEnumerable<IImageInfo> images)
    {
        // Mapping will call MappingRestrictedBox, which will add records to this collection.
        _currentMappingIterationStats = new List<IterationStats>();

        DetailedSingleTestStats stats = new DetailedSingleTestStats();
        TestUtils.RunTest<S>(this, images, stats);

        stats.Iterations = _currentMappingIterationStats;

        return stats;
    }

    /// <summary>
    /// This method is called by MapperOptimalEfficiency_AdditionalStats for each iteration
    /// </summary>
    /// <param name="images"></param>
    /// <param name="maxWidth"></param>
    /// <param name="maxHeight"></param>
    /// <returns></returns>
    protected override S MappingRestrictedBox(
        IOrderedEnumerable<IImageInfo> images, int maxWidth, int maxHeight, ICanvasStats canvasStats,
        out int lowestFreeHeightDeficitTallestRightFlushedImage)
    {
        S intermediateSpriteInfo = 
            base.MappingRestrictedBox(images, maxWidth, maxHeight, canvasStats, out lowestFreeHeightDeficitTallestRightFlushedImage);

        IterationStats stats = null;
        CanvasWritingStepImages canvasBLFStats = _canvas as CanvasWritingStepImages;

        List<ImagePlacementDetails> imageDetails = null;
        if (canvasBLFStats != null) { imageDetails = new List<ImagePlacementDetails>(canvasBLFStats.ImageDetails); }

        if (intermediateSpriteInfo != null)
        {
            stats =
                new IterationStats
                {
                    Result = IterationResult.Success,
                    MaxCanvasWidth = maxWidth,
                    MaxCanvasHeight = maxHeight,
                    IntermediateSpriteWidth = intermediateSpriteInfo.Width,
                    IntermediateSpriteHeight = intermediateSpriteInfo.Height,
                    ImageDetails = imageDetails
                };
        }
        else
        {
            stats =
                new IterationStats
                {
                    Result = IterationResult.Failure,
                    MaxCanvasWidth = maxWidth,
                    MaxCanvasHeight = maxHeight,
                    ImageDetails = imageDetails
                };
        }

        _currentMappingIterationStats.Add(stats);

        // Clear out the current image details as kept by the canvas, otherwise we get the same details again next time.
        if (canvasBLFStats != null) { canvasBLFStats.ImageDetails.Clear(); }

        return intermediateSpriteInfo;
    }

    /// <summary>
    /// </summary>
    /// <param name="images"></param>
    /// <param name="maxWidth"></param>
    /// <param name="maxHeight"></param>
    /// <returns></returns>
    protected override bool CandidateCanvasFeasable(
        int canvasMaxWidth, int canvasMaxHeight, int bestSpriteArea, int totalAreaAllImages,
        out bool candidateBiggerThanBestSprite, out bool candidateSmallerThanCombinedImages)
    {
        bool isFeasable =
            base.CandidateCanvasFeasable(
                canvasMaxWidth, canvasMaxHeight, bestSpriteArea, totalAreaAllImages,
                out candidateBiggerThanBestSprite, out candidateSmallerThanCombinedImages);

        IterationStats stats = null;

        if (candidateBiggerThanBestSprite)
        {
            stats = new IterationStats
            {
                Result = IterationResult.BiggerThanBestSprite,
                MaxCanvasWidth = canvasMaxWidth,
                MaxCanvasHeight = canvasMaxHeight
            };
        }
        else if (candidateSmallerThanCombinedImages)
        {
            stats = new IterationStats
            {
                Result = IterationResult.SmallerThanCombinedImages,
                MaxCanvasWidth = canvasMaxWidth,
                MaxCanvasHeight = canvasMaxHeight
            };
        }

        if (stats != null)
        {
            _currentMappingIterationStats.Add(stats);
        }

        return isFeasable;
    }
}


By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Australia Australia
Twitter: @MattPerdeck
LinkedIn: au.linkedin.com/in/mattperdeck
Current project: JSNLog JavaScript Logging Package

Matt has over 9 years .NET and SQL Server development experience. Before getting into .Net, he worked on a number of systems, ranging from the largest ATM network in The Netherlands to embedded software in advanced Wide Area Networks and the largest ticketing web site in Australia. He has lived and worked in Australia, The Netherlands, Slovakia and Thailand.

He is the author of the book ASP.NET Performance Secrets (www.amazon.com/ASP-NET-Site-Performance-Secrets-Perdeck/dp/1849690685) in which he shows in clear and practical terms how to quickly find the biggest bottlenecks holding back the performance of your web site, and how to then remove those bottlenecks. The book deals with all environments affecting a web site - the web server, the database server and the browser.

Matt currently lives in Sydney, Australia. He recently worked at Readify and the global professional services company PwC. He now works at SP Health, a global provider of weight loss web sites such at CSIRO's TotalWellBeingDiet.com and BiggestLoserClub.com.

Comments and Discussions