* Added bezier routines.
[scdataviz] / graph.c
diff --git a/graph.c b/graph.c
index 4c75464..423ff84 100644 (file)
--- a/graph.c
+++ b/graph.c
@@ -31,6 +31,7 @@ along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 #include <graph.h>
 #include <stdlib.h>
+#include <stdio.h>
 
 G_DEFINE_TYPE(Graph, graph, G_TYPE_OBJECT);
 
@@ -81,8 +82,11 @@ int graph_add_point(Graph* graph, double x, double y, const GString *label) {
 }
 
 int graph_add_line(Graph* graph, double p0_x, double p0_y, double p1_x, double p1_y, double p2_x, double p2_y, double p3_x, double p3_y) {
+  #ifdef DEBUG
+  fprintf(stderr, "graph_add_line(%d, p0_x=%g, p0_y=%g, p1_x=%g, p1_y=%g, p2_x=%g, p2_y=%g, p3_x=%g, p3_y=%g\n", (unsigned int) graph, p0_x, p0_y, p1_x, p1_y, p2_x, p2_y, p3_x, p3_y);
+  #endif
   if(graph->lines == NULL) {
-    if((graph->points = g_ptr_array_new()) == NULL) return 1;
+    if((graph->lines = g_ptr_array_new()) == NULL) return 1;
   }
   struct graph_line *l;
   if((l=(struct graph_line*)malloc(sizeof(struct graph_line))) == NULL) return 2;
@@ -95,7 +99,8 @@ int graph_add_line(Graph* graph, double p0_x, double p0_y, double p1_x, double p
   l->p3_x=p3_x;
   l->p3_y=p3_y;
   g_ptr_array_add(graph->lines, l);
-  if((graph->points->len == 0) && (graph->lines->len == 1)) {
+  if((graph->points->len == 0) && 
+     (graph->lines->len == 1)) {
     graph->maxx = graph->minx = p0_x;
     graph->maxy = graph->miny = p0_y;
   }else{
@@ -120,10 +125,10 @@ static void linear_interpolate(gpointer data, gpointer user_data) {
   struct cxt *cxt = user_data;
   struct graph_point *p3 = data;
   if(cxt->p0 != NULL) {
-    double p1_x = (p3->x - cxt->p0->x)/3.0;
-    double p1_y = (p3->y - cxt->p0->y)/3.0;
-    double p2_x = (p3->x + 2*cxt->p0->x)/3.0;
-    double p2_y = (p3->y + 2*cxt->p0->y)/3.0;
+    double p1_x = (p3->x + 2*cxt->p0->x)/3.0;
+    double p1_y = (p3->y + 2*cxt->p0->y)/3.0;
+    double p2_x = (2*p3->x + cxt->p0->x)/3.0;
+    double p2_y = (2*p3->y + cxt->p0->y)/3.0;
     graph_add_line(cxt->graph, cxt->p0->x, cxt->p0->y, p1_x, p1_y, p2_x, p2_y, p3->x, p3->y);
   }
   cxt->p0 = p3;
@@ -135,3 +140,13 @@ void graph_add_linear_connectors(Graph* graph) {
   cxt.p0 = NULL;
   g_ptr_array_foreach(graph->points, &linear_interpolate, &cxt);
 }
+
+void graph_bezier_linear_to_cubic(double x0, double x3, double *x1, double *x2) {
+  *x1 = (x3 + 2.0*x0)/3.0;
+  *x2 = (2.0*x3 + x0)/3.0;
+}
+
+void graph_bezier_qudratic_to_cubic(double x0, double x3, double *x1, double *x2) {
+  *x2 = (x3 - x0)/3.0 + (*x1);
+  *x1 = (x0 - 3.0*(*x1))/2.0;
+}