libpaint/painter.c
2022-08-15 22:40:28 +03:00

53 lines
1.5 KiB
C

#include "painter.h"
#include "stdio.h"
lp_pixel lp_rgb(uint8_t r, uint8_t g, uint8_t b) {
return (lp_pixel){r, g, b};
}
lp_painter *lp_painter_create(size_t width, size_t height) {
lp_painter *painter = malloc(sizeof(lp_painter));
lp_pixel *buf = malloc(width * height * sizeof(lp_pixel));
painter->buf = buf;
painter->width = width;
painter->height = height;
return painter;
}
void lp_painter_free(lp_painter *painter) {
if (painter) {
if (painter->buf) {
free(painter->buf);
}
free(painter);
}
}
void lp_painter_fill_rect(lp_painter *painter, lp_pixel fill_color, size_t pos_x, size_t pos_y, size_t width, size_t height) {
for (size_t y = pos_y; y < pos_y + height; y++) {
for (size_t x = pos_x; x < pos_x + width; x++) {
size_t index = y * painter->width + x;
painter->buf[index] = fill_color;
}
}
}
void lp_painter_save_ppm(lp_painter *painter, const char *filename) {
FILE *fp = fopen(filename, "w");
if (fp == NULL) {
fprintf(stderr, "Failed to open file");
return;
}
fprintf(fp, "P6\n%zu %zu 255\n", painter->width, painter->height);
for (size_t i = 0; i < painter->width * painter->height; i++) {
fwrite(&painter->buf[i].r, sizeof(uint8_t), 1, fp);
fwrite(&painter->buf[i].g, sizeof(uint8_t), 1, fp);
fwrite(&painter->buf[i].b, sizeof(uint8_t), 1, fp);
}
fwrite(painter->buf, sizeof(lp_pixel), painter->width * painter->height, fp);
fclose(fp);
}