#include "vertex_buffer.h"

#include "skunkworks.h"

#include <stdlib.h>
#include <string.h>

struct sw_vertex_buffer *sw_vertex_buffer_create(u32 elem_size) {
	struct sw_vertex_buffer *vb;

	vb = malloc(sizeof(struct sw_vertex_buffer));
	/* initial capacity... 8? dunno :P */
	vb->elem_capacity = 8;
	vb->data = malloc(elem_size * vb->elem_capacity);
	vb->elem_count = 0;
	vb->elem_size = elem_size;

	return vb;
}

void sw_vertex_buffer_destroy(struct sw_vertex_buffer *vb) {
	free(vb->data);
	free(vb);
}

void sw_vertex_buffer_add(struct sw_vertex_buffer *vb, void *elem) {
	if(vb->elem_count == vb->elem_capacity) {
		/* grow capacity... double for now? */
		vb->elem_capacity *= 2;
		sw_log("increase vertex buffer size to %i", vb->elem_capacity);
		vb->data = realloc(vb->data, vb->elem_size * vb->elem_capacity);
	}
	memcpy(
	    (u8 *)vb->data + vb->elem_count * vb->elem_size, elem, vb->elem_size
	);

	++vb->elem_count;
}

void sw_vertex_buffer_clear(struct sw_vertex_buffer *vb) {
	/* keep capacity */
	vb->elem_count = 0;
}
