]> git.sur5r.net Git - cc65/blobdiff - src/sp65/bitmap.c
Merge pull request #7 from greg-king5/config-buf
[cc65] / src / sp65 / bitmap.c
index acf3f866633ed09c449a06388b20e883d18bc387..b6270d246493afa525e6b4fa26a4340ff8d615e2 100644 (file)
@@ -64,8 +64,7 @@ Bitmap* NewBitmap (unsigned Width, unsigned Height)
     B = xmalloc (sizeof (*B) + (Size - 1) * sizeof (B->Data[0]));
 
     /* Initialize the data */
-    B->Type     = bmUnknown;
-    SB_Init (&B->Name);
+    B->Name     = EmptyStrBuf;
     B->Width    = Width;
     B->Height   = Height;
     B->Pal      = 0;
@@ -79,8 +78,13 @@ Bitmap* NewBitmap (unsigned Width, unsigned Height)
 void FreeBitmap (Bitmap* B)
 /* Free a dynamically allocated bitmap */
 {
-    /* Free the palette */
-    xfree (B->Pal);
+    /* Alloc NULL pointers */
+    if (B != 0) {
+        /* Free name, palette and then the bitmap */
+        SB_Done (&B->Name);
+        xfree (B->Pal);
+        xfree(B);
+    }
 }
 
 
@@ -97,6 +101,43 @@ int ValidBitmapSize (unsigned Width, unsigned Height)
 
 
 
+Bitmap* SliceBitmap (const Bitmap* O, unsigned OrigX, unsigned OrigY,
+                     unsigned Width, unsigned Height)
+/* Create a slice of the given bitmap. The slice starts at position X/Y of
+ * the original and has the given width and height. Location 0/0 is at the
+ * upper left corner.
+ */
+{
+    Bitmap*  B;
+    unsigned Y;
+
+
+    /* Check the coordinates and size */
+    PRECONDITION (OrigX + Width <= O->Width && OrigY + Height <= O->Height);
+
+    /* Create a new bitmap with the given size */
+    B = NewBitmap (Width, Height);
+
+    /* Copy fields from the original */
+    if (SB_GetLen (&O->Name) > 0) {
+        SB_CopyStr (&B->Name, "Slice of ");
+        SB_Append (&B->Name, &O->Name);
+    }
+    B->Pal = DupPalette (O->Pal);
+
+    /* Copy the pixel data */
+    for (Y = 0; Y < Height; ++Y) {
+        memcpy (B->Data + Y * B->Width,
+                O->Data + (OrigY + Y) * O->Width + OrigX,
+                Width * sizeof (O->Data[0]));
+    }
+
+    /* Return the slice */
+    return B;
+}
+
+
+
 Color GetPixelColor (const Bitmap* B, unsigned X, unsigned Y)
 /* Get the color for a given pixel. For indexed bitmaps, the palette entry
  * is returned.