Advertisement
gmlscripts

ds_grid_flood_fill

Mar 12th, 2015
467
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /// ds_grid_flood_fill(grid,x,y,val)
  2. //
  3. //  Fills a bounded area within a grid with a given value.
  4. //  The area is bounded by values unequal to the initial
  5. //  value found at a given seeded position.
  6. //
  7. //      grid        grid data structure, grid
  8. //      x,y         position to seed fill from, integer
  9. //      val         value filling bounded area, real or string
  10. //
  11. //  Note: Requires short-circuit evaluation enabled.
  12. //
  13. /// GMLscripts.com/license
  14. {
  15.     var grid = argument0;
  16.     var seedx = argument1;
  17.     var seedy = argument2;
  18.     var newval = argument3;
  19.  
  20.     var w = ds_grid_width(grid);
  21.     var h = ds_grid_height(grid);
  22.    
  23.     var oldval = grid[# seedx, seedy];
  24.  
  25.     var stackx = ds_queue_create();
  26.     var stacky = ds_queue_create();
  27.    
  28.     ds_queue_enqueue(stackx, seedx);
  29.     ds_queue_enqueue(stacky, seedy);
  30.        
  31.     while (ds_queue_size(stackx))
  32.     {
  33.         var px = ds_queue_dequeue(stackx);
  34.         var py = ds_queue_dequeue(stacky);
  35.         var y1 = py;
  36.         while (y1 >= 0 && grid[# px, y1] == oldval) y1--;
  37.         y1++;
  38.         var spanLeft = false;
  39.         var spanRight = false;
  40.         while (y1 < h && grid[# px, y1] == oldval)
  41.         {
  42.             grid[# px,y1] = newval;
  43.             if (!spanLeft && px > 0 && grid[# px-1, y1] == oldval)
  44.             {
  45.                 ds_queue_enqueue(stackx, px-1);
  46.                 ds_queue_enqueue(stacky, y1);
  47.                 spanLeft = true;
  48.             }
  49.             else if (spanLeft && px > 0 && grid[# px-1, y1] != oldval)
  50.             {
  51.                 spanLeft = false;
  52.             }
  53.             if (!spanRight && px < w-1 && grid[# px+1, y1] == oldval)
  54.             {
  55.                 ds_queue_enqueue(stackx, px+1);
  56.                 ds_queue_enqueue(stacky, y1);
  57.                 spanRight = true;
  58.             }
  59.             else if (spanRight && px < w-1 && grid[# px+1, y1] != oldval)
  60.             {
  61.                 spanRight = false;
  62.             }
  63.             y1++;
  64.         }
  65.     }
  66.    
  67.     ds_queue_destroy(stackx);
  68.     ds_queue_destroy(stacky);
  69.    
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement