<p>Where may one find references on implementing an algorithm for calculating a "dirty rectangle" for minimizing frame buffer updates?  A display model that permits arbitrary edits and computes the minimal set of "bit blit" operations required to update the display.</p>

[{'answer_id': 78085, 'author': 'Mike Dimmick', 'author_id': 6970, 'author_profile': 'https://Stackoverflow.com/users/6970', 'pm_score': 2, 'selected': False, 'text': "<p>To build the smallest rectangle that contains all the areas that need to be repainted:</p>\n\n<ul>\n<li>Start with a blank area (perhaps a rectangle set to 0,0,0,0 - something you can detect as 'no update required')</li>\n</ul>\n\n<p>For each dirty area added:</p>\n\n<ul>\n<li>Normalize the new area (i.e. ensure that left is less than right, top less than bottom)</li>\n<li>If the dirty rectangle is currently empty, set it to the supplied area</li>\n<li>Otherwise, set the left and top co-ordinates of the dirty rectangle to the smallest of {dirty,new}, and the right and bottom co-ordinates to the largest of {dirty,new}.</li>\n</ul>\n\n<p>Windows, at least, maintains an <em>update region</em> of the changes that it's been informed of, and any repainting that needs to be done due to the window being obscured and revealed. A <em>region</em> is an object that is made up of many possibly discontinuous rectangles, polygons and ellipses. You tell Windows about a part of the screen that needs to be repainted by calling InvalidateRect - there is also an InvalidateRgn function for more complicated areas. If you choose to do some painting before the next WM_PAINT message arrives, and you want to exclude that from the dirty area, there are ValidateRect and ValidateRgn functions.</p>\n\n<p>When you start painting with BeginPaint, you supply a PAINTSTRUCT that Windows fills with information about what needs to be painted. One of the members is the smallest rectangle that contains the invalid region. You can get the region itself using GetUpdateRgn (you must call this before BeginPaint, because BeginPaint marks the whole window as valid) if you want to minimize drawing when there are multiple small invalid areas.</p>\n\n<p>I would assume that, as minimizing drawing was important on the Mac and on X when those environments were originally written, there are equivalent mechanisms for maintaining an update region.</p>\n"}, {'answer_id': 78222, 'author': 'Martin W', 'author_id': 14199, 'author_profile': 'https://Stackoverflow.com/users/14199', 'pm_score': 2, 'selected': False, 'text': '<p>What language are you using?  In Python, Pygame can do this for you.  Use the RenderUpdates Group and some Sprite objects with image and rect attributes.</p>\n\n<p>For example:</p>\n\n<pre><code>#!/usr/bin/env python\nimport pygame\n\nclass DirtyRectSprite(pygame.sprite.Sprite):\n    """Sprite with image and rect attributes."""\n    def __init__(self, some_image, *groups):\n        pygame.sprite.Sprite.__init__(self, *groups)\n        self.image = pygame.image.load(some_image).convert()\n        self.rect = self.image.get_rect()\n    def update(self):\n        pass #do something here\n\ndef main():\n    screen = pygame.display.set_mode((640, 480))\n    background = pygame.image.load(open("some_bg_image.png")).convert()\n    render_group = pygame.sprite.RenderUpdates()\n    dirty_rect_sprite = DirtyRectSprite(open("some_image.png"))\n    render_group.add(dirty_rect_sprite)\n\n    while True:\n        dirty_rect_sprite.update()\n        render_group.clear(screen, background)\n        pygame.display.update(render_group.draw(screen))\n</code></pre>\n\n<p>If you\'re not using Python+Pygame, here\'s what I would do:</p>\n\n<ul>\n<li>Make a Sprite class that\'s update(),\nmove() etc. method sets a "dirty"\nflag.</li>\n<li>Keep a rect for each sprite</li>\n<li>If your API supports updating a list of rects, use that on the list of rects whose sprites are dirty.  In SDL, this is SDL_UpdateRects.</li>\n<li>If your API doesn\'t support updating a list of rects (I\'ve never had the chance to use anything besides SDL so I wouldn\'t know), test to see if it\'s quicker to call the blit function multiple times or once with a big rect.  I doubt that any API would be faster using one big rect, but again, I haven\'t used anything besides SDL.</li>\n</ul>\n'}, {'answer_id': 309213, 'author': 'Bob Cross', 'author_id': 5812, 'author_profile': 'https://Stackoverflow.com/users/5812', 'pm_score': 2, 'selected': False, 'text': '<p>It sounds like what you need is a bounding box for each shape that you\'re rendering to the screen.  Remember that a bounding box of a polygon can be defined as a "lower left" (the minimum point) and an "upper right" (the maximum point).  That is, the x-component of the minimum point is defined as the minimum of all the x-components of each point in a polygon.  Use the same methodology for the y-component (in the case of 2D) and the maximal point of the bounding box.  </p>\n\n<p>If it\'s sufficient to have a bounding box (aka "dirty rectangle") per polygon, you\'re done.  If you need an overall composite bounding box, the same algorithm applies, except you can just populate a single box with minimal and maximal points.</p>\n\n<p>Now, if you\'re doing all this in Java, you can get your bounding box for an <code>Area</code> (which you can construct from any <code>Shape</code>) directly by using the <a href="http://java.sun.com/javase/6/docs/api/java/awt/geom/Area.html#getBounds2D()" rel="nofollow noreferrer"><code>getBound2D()</code> method</a>.</p>\n'}, {'answer_id': 322354, 'author': 'CodeAndCats', 'author_id': 26335, 'author_profile': 'https://Stackoverflow.com/users/26335', 'pm_score': 2, 'selected': False, 'text': "<p>I just recently wrote a Delphi class to calculate the difference rectangles of two images and was quite suprised by how fast it ran - fast enough to run in a short timer and after mouse/keyboard messages for recording screen activity.</p>\n\n<p>The step by step gist of how it works is by:</p>\n\n<ol>\n<li><p>Sub-dividing the image into logical 12x12 by rectangles.</p></li>\n<li><p>Looping through each pixel and if there's a difference then I tell the sub-rectangle which the pixel belongs to that there's a difference in one of it's pixels and where.</p></li>\n<li><p>Each sub-rectangle remembers the co-ordinates of it's own left-most, top-most, right-most and bottom-most difference.</p></li>\n<li><p>Once all the differences have been found, I loop through all the sub-rectangles that have differences and form bigger rectangles out of them if they are next to each other and use the left-most, top-most, right-most and bottom-most differences of those sub-rectangles to make actual difference rectangles I use.</p></li>\n</ol>\n\n<p>This seems to work quite well for me. If you haven't already implemented your own solution, let me know and I'll email you my code if you like. Also as of now, I'm a new user of StackOverflow so if you appreciate my answer then please vote it up. :)</p>\n"}, {'answer_id': 5433688, 'author': 'xan', 'author_id': 105752, 'author_profile': 'https://Stackoverflow.com/users/105752', 'pm_score': 2, 'selected': False, 'text': '<p>Look into <a href="http://en.wikipedia.org/wiki/R-tree" rel="nofollow">R-tree</a> and <a href="http://en.wikipedia.org/wiki/Quadtree" rel="nofollow">quadtree</a> data structures.</p>\n'}, {'answer_id': 6520903, 'author': 'Charles Goodwin', 'author_id': 546060, 'author_profile': 'https://Stackoverflow.com/users/546060', 'pm_score': 2, 'selected': False, 'text': '<p>Vexi is a reference implementation of this.  The class is <a href="http://vexi.svn.sourceforge.net/viewvc/vexi/trunk/org.vexi-core.main/src/main/java/org/vexi/util/DirtyList.java?revision=4163&amp;view=markup" rel="nofollow">org.vexi.util.DirtyList</a>  (Apache License), and is used as part of production systems i.e. thoroughly tested, and is well commented.</p>\n\n<p>A caveat, the currently class description is a bit inaccurate, <em>"A general-purpose data structure for holding a list of rectangular regions that need to be repainted, with intelligent coalescing."</em>  Actually it does not currently do the coalescing.  Therefore you can consider this a basic DirtyList implementation in that it only intersects dirty() requests to make sure there are no overlapping dirty regions.</p>\n\n<p>The one nuance to this implementation is that, instead of using Rect or another similar region object, the regions are stored in an array of ints i.e. in blocks of 4 ints in a 1-dimensional array.  This is done for run time efficiency although in retrospect I\'m not sure whether there\'s much merit to this.  (Yes, I implemented it.)  It should be simple enough to substitute Rect for the array blocks in use.</p>\n\n<p>The purpose of the class is to be <em>fast</em>.  With Vexi, dirty may be called thousands of times per frame, so intersections of the dirty regions with the dirty request has to be as quick as possible.  No more than 4 number comparisons are used to determine the relative position of two regions.</p>\n\n<p>It is not entirely optimal due to the missing coalescing.  Whilst it does ensure no overlaps between dirty/painted regions, you might end up with regions that line up and could be merged into a larger region - and therefore reducing the number of paint calls.</p>\n\n<p>Code snippet.  Full code <a href="http://vexi.svn.sourceforge.net/viewvc/vexi/trunk/org.vexi-core.main/src/main/java/org/vexi/util/DirtyList.java?revision=4163&amp;view=markup" rel="nofollow">online here</a>.</p>\n\n<pre><code>public class DirtyList {\n\n    /** The dirty regions (each one is an int[4]). */\n    private int[] dirties = new int[10 * 4]; // gets grown dynamically\n\n    /** The number of dirty regions */\n    private int numdirties = 0;\n\n    ...\n\n    /** \n     *  Pseudonym for running a new dirty() request against the entire dirties list\n     *  (x,y) represents the topleft coordinate and (w,h) the bottomright coordinate \n     */\n    public final void dirty(int x, int y, int w, int h) { dirty(x, y, w, h, 0); }\n\n    /** \n     *  Add a new rectangle to the dirty list; returns false if the\n     *  region fell completely within an existing rectangle or set of\n     *  rectangles (i.e. did not expand the dirty area)\n     */\n    private void dirty(int x, int y, int w, int h, int ind) {\n        int _n;\n        if (w&lt;x || h&lt;y) {\n            return;\n        }\n        for (int i=ind; i&lt;numdirties; i++) {\n            _n = 4*i;\n            // invalid dirties are marked with x=-1\n            if (dirties[_n]&lt;0) {\n                continue;\n            }\n\n            int _x = dirties[_n];\n            int _y = dirties[_n+1];\n            int _w = dirties[_n+2];\n            int _h = dirties[_n+3];\n\n            if (x &gt;= _w || y &gt;= _h || w &lt;= _x || h &lt;= _y) {\n                // new region is outside of existing region\n                continue;\n            }\n\n            if (x &lt; _x) {\n                // new region starts to the left of existing region\n\n                if (y &lt; _y) {\n                    // new region overlaps at least the top-left corner of existing region\n\n                    if (w &gt; _w) {\n                        // new region overlaps entire width of existing region\n\n                        if (h &gt; _h) {\n                            // new region contains existing region\n                            dirties[_n] = -1;\n                            continue;\n                        }// else {\n                        // new region contains top of existing region\n                        dirties[_n+1] = h;\n                        continue;\n\n                    } else {\n                        // new region overlaps to the left of existing region\n\n                        if (h &gt; _h) {\n                            // new region contains left of existing region\n                            dirties[_n] = w;\n                            continue;\n                        }// else {\n                        // new region overlaps top-left corner of existing region\n                        dirty(x, y, w, _y, i+1);\n                        dirty(x, _y, _x, h, i+1);\n                        return;\n\n                    }\n                } else {\n                    // new region starts within the vertical range of existing region\n\n                    if (w &gt; _w) {\n                        // new region horizontally overlaps existing region\n\n                        if (h &gt; _h) {\n                            // new region contains bottom of existing region\n                            dirties[_n+3] = y;\n                            continue;\n                        }// else {\n                        // new region overlaps to the left and right of existing region\n                        dirty(x, y, _x, h, i+1);\n                        dirty(_w, y, w, h, i+1);\n                        return;\n\n                    } else {\n                        // new region ends within horizontal range of existing region\n\n                        if (h &gt; _h) {\n                            // new region overlaps bottom-left corner of existing region\n                            dirty(x, y, _x, h, i+1);\n                            dirty(_x, _h, w, h, i+1);\n                            return;\n                        }// else {\n                        // existing region contains right part of new region\n                        w = _x;\n                        continue;\n                    }\n                }\n            } else {\n                // new region starts within the horizontal range of existing region\n\n                if (y &lt; _y) {\n                    // new region starts above existing region\n\n                    if (w &gt; _w) {\n                        // new region overlaps at least top-right of existing region\n\n                        if (h &gt; _h) {\n                            // new region contains the right of existing region\n                            dirties[_n+2] = x;\n                            continue;\n                        }// else {\n                        // new region overlaps top-right of existing region\n                        dirty(x, y, w, _y, i+1);\n                        dirty(_w, _y, w, h, i+1);\n                        return;\n\n                    } else {\n                        // new region is horizontally contained within existing region\n\n                        if (h &gt; _h) {\n                            // new region overlaps to the above and below of existing region\n                            dirty(x, y, w, _y, i+1);\n                            dirty(x, _h, w, h, i+1);\n                            return;\n                        }// else {\n                        // existing region contains bottom part of new region\n                        h = _y;\n                        continue;\n                    }\n                } else {\n                    // new region starts within existing region\n\n                    if (w &gt; _w) {\n                        // new region overlaps at least to the right of existing region\n\n                        if (h &gt; _h) {\n                            // new region overlaps bottom-right corner of existing region\n                            dirty(x, _h, w, h, i+1);\n                            dirty(_w, y, w, _h, i+1);\n                            return;\n                        }// else {\n                        // existing region contains left part of new region\n                        x = _w;\n                        continue;\n                    } else {\n                        // new region is horizontally contained within existing region\n\n                        if (h &gt; _h) {\n                            // existing region contains top part of new region\n                            y = _h;\n                            continue;\n                        }// else {\n                        // new region is contained within existing region\n                        return;\n                    }\n                }\n            }\n        }\n\n        // region is valid; store it for rendering\n        _n = numdirties*4;\n        size(_n);\n        dirties[_n] = x;\n        dirties[_n+1] = y;\n        dirties[_n+2] = w;\n        dirties[_n+3] = h;\n        numdirties++;\n    }\n\n    ...\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/76651', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']