Mac OS X header compatibility.
[grGL.git] / src / graph.c
1 #include <stdlib.h>
2
3 #ifdef __APPLE__
4 #include <OpenGL/gl.h>
5 #else
6 #include <GL/gl.h>
7 #endif
8
9 #include "graph.h"
10
11 /****************************
12  * Graph memory
13  ***************************/
14
15 // Free the memory for a graph and substructures
16 void grFree(grGraph *g)
17 {
18   if (g)
19   {
20     if (g->nodes)
21       free(g->nodes);
22     if (g->edges)
23       free(g->edges);
24     free(g);
25   }
26 }
27
28
29 // Allocate memory for a new graph, return NULL on any error
30 grGraph* grAlloc(int numnodes, int numedges)
31 {
32   grGraph *g;
33
34   g = malloc(sizeof(grGraph));
35   if (!g)
36     return NULL;
37
38   g->nodes = malloc(sizeof(grNode[numnodes]));
39   g->edges = malloc(sizeof(grEdge[numedges]));
40   if (!g->nodes || !g->edges)
41     goto ERR;
42
43   g->numnodes = numnodes;
44   g->numedges = numedges;
45
46   return g;
47
48   ERR:
49   grFree(g);
50   return NULL;
51 }
52
53
54
55 /****************************
56  * Graph generation
57  ***************************/
58
59 // Randomize a graph
60 void grGenRandom(grGraph *g)
61 {
62   int i;
63   int ns = g->numnodes;
64   int es = g->numedges;
65
66   for (i = 0; i < ns; i++)
67   {
68     grNode *n = &g->nodes[i];
69
70     n->x = (float)rand() / (RAND_MAX/4);
71     n->y = (float)rand() / (RAND_MAX/4);
72     n->z = (float)rand() / (RAND_MAX/4);
73     n->colour = 0.0;
74   }
75
76   for (i = 0; i < es; i++)
77   {
78     grEdge *e = &g->edges[i];
79
80     e->n1 = rand() / (RAND_MAX/ns);
81     e->n2 = rand() / (RAND_MAX/ns);
82   }
83 }
84
85
86
87 /****************************
88  * Graph drawing functions
89  ***************************/
90
91 // Draw the graph on the current OpenGL context
92 void graphDrawGL(grGraph *g)
93 {
94   int i;
95   int ns = g->numnodes;
96   int es = g->numedges;
97
98   // Draw edges
99   glColor4f(0.0, 0.0, 1.0, 0.5);
100   for (i = 0; i < es; i++)
101   {
102     grNode *n1 = &g->nodes[g->edges[i].n1];
103     grNode *n2 = &g->nodes[g->edges[i].n2];
104
105     glBegin(GL_LINE_STRIP);
106       glVertex3f(n1->x, n1->y, n1->z);
107       glVertex3f(n2->x, n2->y, n2->z);
108     glEnd();
109   }
110
111   // Draw nodes
112   glPointSize(5.0);
113   glBegin(GL_POINTS);
114     for (i = 0; i < ns; i++)
115     {
116       grNode *n = &g->nodes[i];
117       //glLoadName(i);    // Load point number into depth buffer for selection
118       glColor4f(n->colour, 1.0, 0.3, 0.7);
119       glVertex3f(n->x, n->y, n->z);
120     }
121   glEnd();
122 }