News
Forums
Code
Logs
Gallery
Specs
Search
Flood Fill
Monkey Forums
/
Monkey Code
/
Flood Fill
Sub_Zero
(Posted 2013)
[#1]
4-Way Flood fill function using stacks:
Method FloodFill:Int(x:Int, y:Int, tcolor:Int, rcolor:Int) Local q:= New IntStack Local nx:Int, ny:Int Local trect:Int[] = New Int[DeviceWidth() * DeviceHeight()] ReadPixels(trect, 0, 0, DeviceWidth(), DeviceHeight()) If trect[x + (y*DeviceWidth())] <> tcolor Return 0 q.Push(x) q.Push(y) While q.Length > 0 ny = q.Pop() nx = q.Pop() If trect[nx + (ny*DeviceWidth())] = tcolor trect[nx + (ny*DeviceWidth())] = rcolor If nx > 0 q.Push(nx-1); q.Push(ny); 'Print "West.." Endif If nx < DeviceWidth() q.Push(nx+1); q.Push(ny); 'Print "East.." Endif If ny > 0 q.Push(nx); q.Push(ny-1);' Print "North..." Endif If ny < DeviceHeight() q.Push(nx); q.Push(ny+1); 'Print "South..." Endif Endif Wend img = CreateImage(DeviceWidth(), DeviceHeight()) img.WritePixels(trect, 0, 0, DeviceWidth(), DeviceHeight()) Return 0 End Method
Flood fill Scanline function using stacks (faster):
Method FloodFillScanlineStack:Int(x:Int, y:Int, newColor:Int, oldColor:Int) If(oldColor = newColor) Return 0 Local qx:= New IntStack Local qy:= New IntStack Local y1:Int Local spanLeft:Int, spanRight:Int qx.Push(x) qy.Push(y) Local screenBuffer:Int[] = New Int[DeviceWidth() * DeviceHeight()] ReadPixels(screenBuffer, 0, 0, DeviceWidth(), DeviceHeight()) While(qx.Length > 0) x = qx.Pop() y = qy.Pop() y1 = y While(y1 >= 0 And screenBuffer[x+(y1*DeviceWidth())] = oldColor) y1 -= 1 Wend y1 += 1 spanLeft = 0 spanRight = 0; While(y1 < DeviceHeight() And screenBuffer[x+(y1*DeviceWidth())] = oldColor ) screenBuffer[x+(y1*DeviceWidth())] = newColor; If(Not spanLeft And x > 0 And screenBuffer[(x - 1)+(y1*DeviceWidth())] = oldColor) qx.Push(x-1); qy.Push(y1) spanLeft = 1; Elseif(spanLeft And x > 0 And screenBuffer[x - 1+(y1*DeviceWidth())] <> oldColor) spanLeft = 0; Endif If(Not spanRight And x < DeviceWidth() - 1 And screenBuffer[x + 1+(y1*DeviceWidth())] = oldColor) qx.Push(x+1); qy.Push(y1) spanRight = 1; Elseif(spanRight And x < DeviceWidth() - 1 And screenBuffer[x + 1+(y1*DeviceWidth())] <> oldColor) spanRight = 0; Endif y1 += 1; Wend Wend img = CreateImage(DeviceWidth(), DeviceHeight()) img.WritePixels(screenBuffer, 0, 0, DeviceWidth(), DeviceHeight()) Return 0 End Method