For my the drawing surface I created an array of byte 4 * width * height - four bytes for each enough to handle all my color information. Some initial profiling showed that looping through every pixel on every frame to clear it was taking a lot of time so I created a cached copy of background color pixels (black in this case). Copying this via System.Buffer proved to be much faster.
public class Surface
{
private const int BytesPerPixel = 4;
private readonly byte[] clearPixels;
private readonly int height;
private readonly byte[] pixels;
private readonly int size;
private readonly int width;
public Surface(int width, int height)
{
this.width = width;
this.height = height;
size = height*width*BytesPerPixel;
pixels = new byte[size];
clearPixels = new byte[size];
Clear();
}
public byte[] Pixels
{
get { return pixels; }
}
public void CreateClearPixles()
{
for (int index = 0; index < clearPixels.Length;)
{
clearPixels[index] = 0;
clearPixels[index + 1] = 0;
clearPixels[index + 2] = 0;
clearPixels[index + 3] = 255;
index += 4;
}
}
}
I added drawPoint funtcion, and a draw line function. Again profile showed that Buffer.BlockCopy is much faster than writing the four bytes one by one. For line drawing I used Bresenham's line algorithm.
public void Draw(int x, int y, byte[] color)
{
int byteOffset = BytesPerPixel*(x + y*width);
Buffer.BlockCopy(color, 0, pixels, byteOffset, 4);
}
I also added a GetBitmap function that would return a System.Drawing.Bitmap.
I'm not happy with how this is working at all, so I am going to omit it for now.
public Bitmap ToBitmap()
{
// very ugly implementation that I won't show until I fix.
Buffer.BlockCopy(clearPixels, 0, Pixels, 0, size); // reset the picture.
return null;
}
}
So we're able to draw now, but we're still stuck in the 2D world. we can draw shapes but we can only map X and Y to the screen. Z is nowhere to be found. Next up: 3-D!