#include #include "ascii_pixmap.h" #include "pixmap_impl.h" /* This is an implementation of ascii_pixmap in which the specific * ascii_pixmap methods to get or set the background or foreground are * non-virtual. */ struct ascii_pixmap { struct pixmap pixmap; char background; char foreground; unsigned int width; unsigned int height; char * pixels; }; void ascii_pixmap_set_background(struct pixmap * this, char bg) { ((struct ascii_pixmap *)this)->background = bg; } void ascii_pixmap_set_foreground(struct pixmap * this, char fg) { ((struct ascii_pixmap *)this)->foreground = fg; } char ascii_pixmap_get_background(const struct pixmap * this) { return ((struct ascii_pixmap *)this)->background; } char ascii_pixmap_get_foreground(const struct pixmap * this) { return ((struct ascii_pixmap *)this)->foreground; } static void ascii_pixmap_clear(struct pixmap * p) { struct ascii_pixmap * this = (struct ascii_pixmap *)p; for(unsigned i = 0; i < this->width * this->height; ++i) this->pixels[i] = this->background; } static void ascii_pixmap_set_pixel(struct pixmap * p, unsigned int x, unsigned int y, int v) { struct ascii_pixmap * this = (struct ascii_pixmap *)p; if (x < this->width && y < this->height) this->pixels[y * this->width + x] = (v ? this->foreground : this->background); } static int ascii_pixmap_get_pixel(const struct pixmap * p, unsigned int x, unsigned int y) { struct ascii_pixmap * this = (struct ascii_pixmap *)p; if (x < this->width && y < this->height) return (this->pixels[y * this->width + x] == this->foreground); return 0; } static unsigned int ascii_pixmap_get_width(const struct pixmap * p) { struct ascii_pixmap * this = (struct ascii_pixmap *)p; return this->width; } static unsigned int ascii_pixmap_get_height(const struct pixmap * p) { struct ascii_pixmap * this = (struct ascii_pixmap *)p; return this->height; } static size_t ascii_pixmap_get_memory_size(const struct pixmap * p) { struct ascii_pixmap * this = (struct ascii_pixmap *)p; return this->height * this->width * sizeof(char); } static void ascii_pixmap_destroy(struct pixmap * this) { free(this); } static const char DEFAULT_FOREGROUND = '*'; static const char DEFAULT_BACKGROUND = ' '; struct pixmap * ascii_pixmap_new(unsigned int width, unsigned int height, char * map) { static const struct pixmap_vtable vtable = { .clear = ascii_pixmap_clear, .set_pixel = ascii_pixmap_set_pixel, .get_pixel = ascii_pixmap_get_pixel, .get_width = ascii_pixmap_get_width, .get_height = ascii_pixmap_get_height, .get_memory_size = ascii_pixmap_get_memory_size, .destroy = ascii_pixmap_destroy, }; struct ascii_pixmap * this = malloc(sizeof(struct ascii_pixmap)); if (this) { this->pixmap.vtable = & vtable; this->background = DEFAULT_BACKGROUND; this->foreground = DEFAULT_FOREGROUND; this->width = width; this->height = height; this->pixels = map; for(unsigned i = 0; i < width * height; ++i) this->pixels[i] = this->background; } return &(this->pixmap); }