From 6c0d96ef02ef2fa78e98d1bc644a65e15ed284a0 Mon Sep 17 00:00:00 2001
From: "Mirar (Pontus Hagland)" <pike@sort.mirar.org>
Date: Wed, 16 Oct 1996 15:10:20 +0200
Subject: [PATCH] added method: distancesq(r,g,b) quant.c: severe bug fixed

Rev: src/modules/image/image.c:1.16
Rev: src/modules/image/quant.c:1.8
---
 src/modules/image/image.c | 39 +++++++++++++++++++++++++++++++++++++++
 src/modules/image/quant.c |  9 +++++----
 2 files changed, 44 insertions(+), 4 deletions(-)

diff --git a/src/modules/image/image.c b/src/modules/image/image.c
index 714e038642..c3304167d8 100644
--- a/src/modules/image/image.c
+++ b/src/modules/image/image.c
@@ -1546,6 +1546,43 @@ void image_threshold(INT32 args)
    push_object(o);
 }
 
+void image_distancesq(INT32 args)
+{
+   INT32 i;
+   rgb_group *s,*d,rgb;
+   struct object *o;
+   struct image *img;
+
+   if (!THIS->img) error("no image\n");
+
+   getrgb(THIS,0,args,"image->threshold()");
+
+   o=clone(image_program,0);
+   img=(struct image*)o->storage;
+   *img=*THIS;
+   if (!(img->img=malloc(sizeof(rgb_group)*THIS->xsize*THIS->ysize+1)))
+   {
+      free_object(o);
+      error("Out of memory\n");
+   }
+
+   d=img->img;
+   s=THIS->img;
+   rgb=THIS->rgb;
+
+   i=img->xsize*img->ysize;
+   while (i--)
+   {
+#define DISTANCE(A,B) \
+   (sq((long)(A).r-(B).r)+sq((long)(A).g-(B).g)+sq((long)(A).b-(B).b))
+      d->r=d->g=d->b=testrange(DISTANCE(*s,rgb)/255);
+      d++; s++;
+   }
+
+   pop_n_elems(args);
+   push_object(o);
+}
+
 void image_apply_matrix(INT32 args)
 {
    int width,height,i,j;
@@ -2044,6 +2081,8 @@ void init_image_programs()
 		"function("RGB_TYPE":object)",0);
    add_function("threshold",image_threshold,
 		"function("RGB_TYPE":object)",0);
+   add_function("distancesq",image_distancesq,
+		"function("RGB_TYPE":object)",0);
 
    add_function("apply_matrix",image_apply_matrix,
                 "function(array(array(int|array(int))):object)",0);
diff --git a/src/modules/image/quant.c b/src/modules/image/quant.c
index 21884642a1..0a2a8b546e 100644
--- a/src/modules/image/quant.c
+++ b/src/modules/image/quant.c
@@ -23,8 +23,9 @@ David K
 
 /*
 #define QUANT_DEBUG
-#define QUANT_CHRONO
+#define QUANT_DEBUG_DEEP
 */
+#define QUANT_CHRONO
 
 /**********************************************************************/
 
@@ -334,9 +335,9 @@ static void sort_tbl(rgb_hashtbl *ht,
       }
 
       g1=gap>>1;
-      if (pos+1<g1) g1=pos+1;
-      else if (len-pos-1<gap-g1) g1=pos+1;
-      g2=gap-g1;
+      if (pos+1<g1) g1=pos+1,g2=gap-g1;
+      else if (len-pos-1<gap-g1) g2=(len-pos)+1,g1=gap-g2;
+      else g2=gap-g1;
 
       sort_tbl(ht,start,pos+1,
 	       level+1,idx,g1,dir,
-- 
GitLab