#include #include #include "lighting.h" /* Returns a pointer to the next unused item on the heap */ void* new_from_heap(Heap* heap) { /* Grow heap if necessary */ if (heap->count == heap->capacity) { int i; heap->capacity += heap->step; heap->data = realloc(heap->data, sizeof(void*) * heap->capacity); for (i = heap->count; i < heap->capacity; i++) heap->data[i] = heap->create(); } return heap->data[heap->count++]; } /* Removes a pointer from the heap */ void delete_from_heap(Heap* heap, void* data) { int index; /* Find the index of the given data */ for (index = 0; index < heap->count; index++) if (heap->data[index] == data) break; /* Couldn't find it? */ if (index == heap->count) return; /* Remove the pointer */ heap->count--; if (index < heap->count) { void* tmp = heap->data[index]; heap->data[index] = heap->data[heap->count]; heap->data[heap->count] = tmp; } } /* Calls a function on all the data in the heap */ void _process_heap(Heap* heap, void (*proc)(void*)) { void** data = heap->data; void** data_end = data + heap->count; for (; data < data_end; data++) proc(*data); } /* Calls a function on all the data in the heap */ void process_heap_va(Heap* heap, void (*proc)(void*, va_list), ...) { va_list ap; void** data = heap->data; void** data_end = data + heap->count; for (; data < data_end; data++) { va_start(ap, proc); proc(*data, ap); va_end(ap); } } /* Empties the heap (the old pointer array will be recycled) */ void empty_heap(Heap* heap) { heap->count = 0; } /* Creates a heap */ void _create_heap(Heap* heap, int capacity, int step, void*(*create)(void), void(*destroy)(void*)) { int i; heap->data = malloc(sizeof(void*) * capacity); for (i = 0; i < capacity; i++) heap->data[i] = create(); heap->count = 0; heap->capacity = capacity; heap->step = step; heap->create = create; heap->destroy = destroy; } /* Deallocates the entire heap */ /* Doesn't deallocate things the nodes refer to */ void destroy_heap(Heap* heap) { int i; for (i = 0; i < heap->capacity; i++) heap->destroy(heap->data[i]); free(heap->data); heap->data = NULL; heap->count = 0; heap->capacity = 0; }