add support for 3d scenes, depth testing, lighting
[chaz/rasterize] / common.c
1
2 /*
3 * CS5600 University of Utah
4 * Charles McGarvey
5 * mcgarvey@eng.utah.edu
6 */
7
8 #include <assert.h>
9 #include <ctype.h>
10 #include <errno.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <sys/time.h>
15
16 #include "common.h"
17
18
19 static void* (*_mem_fn)(void*, size_t) = NULL;
20
21 static int _mem_blocks = 0;
22
23
24 /*
25 * Check the result of the allocation function and call the callback function
26 * if it failed.
27 */
28 INLINE_MAYBE
29 void* _mem_check(void* mem, void* old, size_t size)
30 {
31 if (mem == NULL && size != 0) {
32 if (_mem_fn) {
33 mem = _mem_fn(old, size);
34 if (mem != NULL) {
35 goto done;
36 }
37 }
38 fprintf(stderr, "Memory allocation failed: %s\n", strerror(errno));
39 abort();
40 }
41
42 done:
43 if (old == NULL) {
44 ++_mem_blocks;
45 }
46 return mem;
47 }
48
49
50 void* mem_alloc(size_t size)
51 {
52 void* mem = _mem_check(malloc(size), NULL, size);
53 #if MEM_TRACE
54 fprintf(stderr, "alloc %6d %18p %10zd\n", _mem_blocks - 1, mem, size);
55 #endif
56 return mem;
57 }
58
59 void* mem_realloc(void* mem, size_t size)
60 {
61 void* old = mem;
62 mem = _mem_check(realloc(mem, size), mem, size);
63 #if MEM_TRACE
64 fprintf(stderr, "realloc %6d %18p %10zd (was %p)\n", _mem_blocks - 1, mem, size, old);
65 #endif
66 return mem;
67 }
68
69 void mem_free(void* mem)
70 {
71 --_mem_blocks;
72 #if MEM_TRACE
73 fprintf(stderr, "free %6d %18p\n", _mem_blocks, mem);
74 #endif
75 free(mem);
76 }
77
78 void mem_set_fn(void* (*fn)(void*, size_t))
79 {
80 _mem_fn = fn;
81 }
82
83 int mem_blocks()
84 {
85 return _mem_blocks;
86 }
87
88
89 void rtrim(char *str)
90 {
91 char *m;
92 for (m = str + strlen(str) - 1; str <= m && isspace((int)*m); --m);
93 m[1] = '\0';
94 }
95
96 void ltrim(char *str)
97 {
98 char *m;
99 for (m = str; *m && isspace((int)*m); ++m);
100 memmove(str, m, strlen(m) + 1);
101 }
102
103
104 static struct timeval _timer = {0, 0l};
105
106 static struct timeval timer_diff(struct timeval a, struct timeval b)
107 {
108 struct timeval tv;
109 if ((b.tv_usec - a.tv_usec) < 0) {
110 tv.tv_sec = b.tv_sec - a.tv_sec - 1;
111 tv.tv_usec = 1000000l + b.tv_usec - a.tv_usec;
112 } else {
113 tv.tv_sec = b.tv_sec - a.tv_sec;
114 tv.tv_usec = b.tv_usec - a.tv_usec;
115 }
116 return tv;
117 }
118
119 void timer_start()
120 {
121 int result = gettimeofday(&_timer, NULL);
122 assert(result == 0 && "umm... gettimeofday failed!?");
123 }
124
125 long timer_stop()
126 {
127 struct timeval tv;
128 int result = gettimeofday(&tv, NULL);
129 assert(result == 0 && "umm... gettimeofday failed!?");
130 tv = timer_diff(_timer, tv);
131 return (long)tv.tv_sec * 1000000l + tv.tv_usec;
132 }
133
This page took 0.04712 seconds and 5 git commands to generate.