g_template.c 195 KB
Newer Older
Miller Puckette's avatar
Miller Puckette committed
1
2
3
4
5
6
7
/* Copyright (c) 1997-1999 Miller Puckette.
* For information on usage and redistribution, and for a DISCLAIMER OF ALL
* WARRANTIES, see the file, "LICENSE.txt," in this distribution.  */

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
8
#include <math.h>  /* for matrix transforms */
Miller Puckette's avatar
Miller Puckette committed
9
10
11
12
13
14

#include "m_pd.h"
#include "s_stuff.h"    /* for sys_hostfontsize */
#include "g_canvas.h"

void array_redraw(t_array *a, t_glist *glist);
15
16
void graph_graphrect(t_gobj *z, t_glist *glist,
    int *xp1, int *yp1, int *xp2, int *yp2);
Miller Puckette's avatar
Miller Puckette committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/*
This file contains text objects you would put in a canvas to define a
template.  Templates describe objects of type "array" (g_array.c) and
"scalar" (g_scalar.c).
*/

    /* the structure of a "struct" object (also the obsolete "gtemplate"
    you get when using the name "template" in a box.) */

struct _gtemplate
{
    t_object x_obj;
    t_template *x_template;
    t_canvas *x_owner;
    t_symbol *x_sym;
    struct _gtemplate *x_next;
    int x_argc;
    t_atom *x_argv;
};

/* ---------------- forward definitions ---------------- */

static void template_conformarray(t_template *tfrom, t_template *tto,
    int *conformaction, t_array *a);
static void template_conformglist(t_template *tfrom, t_template *tto,
    t_glist *glist,  int *conformaction);

/* ---------------------- storage ------------------------- */

static t_class *gtemplate_class;
static t_class *template_class;

/* there's a pre-defined "float" template.  LATER should we bind this
to a symbol such as "pd-float"??? */

    /* return true if two dataslot definitions match */
static int dataslot_matches(t_dataslot *ds1, t_dataslot *ds2,
    int nametoo)
{
    return ((!nametoo || ds1->ds_name == ds2->ds_name) &&
        ds1->ds_type == ds2->ds_type &&
            (ds1->ds_type != DT_ARRAY ||
                ds1->ds_arraytemplate == ds2->ds_arraytemplate));
}

/* -- templates, the active ingredient in gtemplates defined below. ------- */

t_template *template_new(t_symbol *templatesym, int argc, t_atom *argv)
{
    t_template *x = (t_template *)pd_new(template_class);
    x->t_n = 0;
    x->t_vec = (t_dataslot *)t_getbytes(0);
    while (argc > 0)
    {
        int newtype, oldn, newn;
        t_symbol *newname, *newarraytemplate = &s_, *newtypesym;
        if (argc < 2 || argv[0].a_type != A_SYMBOL ||
            argv[1].a_type != A_SYMBOL)
                goto bad;
        newtypesym = argv[0].a_w.w_symbol;
        newname = argv[1].a_w.w_symbol;
        if (newtypesym == &s_float)
            newtype = DT_FLOAT;
        else if (newtypesym == &s_symbol)
            newtype = DT_SYMBOL;
        else if (newtypesym == &s_list)
            newtype = DT_LIST;
        else if (newtypesym == gensym("array"))
        {
            if (argc < 3 || argv[2].a_type != A_SYMBOL)
            {
                pd_error(x, "array lacks element template or name");
                goto bad;
            }
            newarraytemplate = canvas_makebindsym(argv[2].a_w.w_symbol);
            newtype = DT_ARRAY;
            argc--;
            argv++;
        }
        else
        {
            pd_error(x, "%s: no such type", newtypesym->s_name);
            goto bad;
        }
        newn = (oldn = x->t_n) + 1;
        x->t_vec = (t_dataslot *)t_resizebytes(x->t_vec,
            oldn * sizeof(*x->t_vec), newn * sizeof(*x->t_vec));
        x->t_n = newn;
        x->t_vec[oldn].ds_type = newtype;
        x->t_vec[oldn].ds_name = newname;
        x->t_vec[oldn].ds_arraytemplate = newarraytemplate;
    bad: 
        argc -= 2; argv += 2;
    }
111
    if (*templatesym->s_name)
Miller Puckette's avatar
Miller Puckette committed
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
    {
        x->t_sym = templatesym;
        pd_bind(&x->t_pdobj, x->t_sym);
    }
    else x->t_sym = templatesym;
    return (x);
}

int template_size(t_template *x)
{
    return (x->t_n * sizeof(t_word));
}

int template_find_field(t_template *x, t_symbol *name, int *p_onset,
    int *p_type, t_symbol **p_arraytype)
{
    t_template *t;
    int i, n;
    if (!x)
    {
        bug("template_find_field");
        return (0);
    }
    n = x->t_n;
    for (i = 0; i < n; i++)
        if (x->t_vec[i].ds_name == name)
    {
        *p_onset = i * sizeof(t_word);
        *p_type = x->t_vec[i].ds_type;
        *p_arraytype = x->t_vec[i].ds_arraytemplate;
        return (1);
    }
    return (0);
}

t_float template_getfloat(t_template *x, t_symbol *fieldname, t_word *wp,
    int loud)
{
    int onset, type;
    t_symbol *arraytype;
152
    t_float val = 0;
Miller Puckette's avatar
Miller Puckette committed
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
    if (template_find_field(x, fieldname, &onset, &type, &arraytype))
    {
        if (type == DT_FLOAT)
            val = *(t_float *)(((char *)wp) + onset);
        else if (loud) error("%s.%s: not a number",
            x->t_sym->s_name, fieldname->s_name);
    }
    else if (loud) error("%s.%s: no such field",
        x->t_sym->s_name, fieldname->s_name);
    return (val);
}

void template_setfloat(t_template *x, t_symbol *fieldname, t_word *wp, 
    t_float f, int loud)
{
    int onset, type;
    t_symbol *arraytype;
    if (template_find_field(x, fieldname, &onset, &type, &arraytype))
     {
        if (type == DT_FLOAT)
            *(t_float *)(((char *)wp) + onset) = f;
        else if (loud) error("%s.%s: not a number",
            x->t_sym->s_name, fieldname->s_name);
    }
    else if (loud) error("%s.%s: no such field",
        x->t_sym->s_name, fieldname->s_name);
}

t_symbol *template_getsymbol(t_template *x, t_symbol *fieldname, t_word *wp,
    int loud)
{
    int onset, type;
    t_symbol *arraytype;
    t_symbol *val = &s_;
    if (template_find_field(x, fieldname, &onset, &type, &arraytype))
    {
        if (type == DT_SYMBOL)
            val = *(t_symbol **)(((char *)wp) + onset);
        else if (loud) error("%s.%s: not a symbol",
            x->t_sym->s_name, fieldname->s_name);
    }
    else if (loud) error("%s.%s: no such field",
        x->t_sym->s_name, fieldname->s_name);
    return (val);
}

void template_setsymbol(t_template *x, t_symbol *fieldname, t_word *wp, 
    t_symbol *s, int loud)
{
    int onset, type;
    t_symbol *arraytype;
    if (template_find_field(x, fieldname, &onset, &type, &arraytype))
     {
        if (type == DT_SYMBOL)
            *(t_symbol **)(((char *)wp) + onset) = s;
        else if (loud) error("%s.%s: not a symbol",
            x->t_sym->s_name, fieldname->s_name);
    }
    else if (loud) error("%s.%s: no such field",
        x->t_sym->s_name, fieldname->s_name);
}

    /* stringent check to see if a "saved" template, x2, matches the current
        one (x1).  It's OK if x1 has additional scalar elements but not (yet)
        arrays or lists.  This is used for reading in "data files". */
int template_match(t_template *x1, t_template *x2)
{
    int i;
    if (x1->t_n < x2->t_n)
        return (0);
    for (i = x2->t_n; i < x1->t_n; i++)
    {
        if (x1->t_vec[i].ds_type == DT_ARRAY || 
            x1->t_vec[i].ds_type == DT_LIST)
                return (0);
    }
    if (x2->t_n > x1->t_n)
        post("add elements...");
    for (i = 0; i < x2->t_n; i++)
        if (!dataslot_matches(&x1->t_vec[i], &x2->t_vec[i], 1))
            return (0);
    return (1);
}

/* --------------- CONFORMING TO CHANGES IN A TEMPLATE ------------ */

/* the following routines handle updating scalars to agree with changes
in their template.  The old template is assumed to be the "installed" one
so we can delete old items; but making new ones we have to avoid scalar_new
which would make an old one whereas we will want a new one (but whose array
elements might still be old ones.)
    LATER deal with graphics updates too... */

    /* conform the word vector of a scalar to the new template */    
static void template_conformwords(t_template *tfrom, t_template *tto,
    int *conformaction, t_word *wfrom, t_word *wto)
{
    int nfrom = tfrom->t_n, nto = tto->t_n, i;
    for (i = 0; i < nto; i++)
    {
        if (conformaction[i] >= 0)
        {
                /* we swap the two, in case it's an array or list, so that
                when "wfrom" is deleted the old one gets cleaned up. */
            t_word wwas = wto[i];
            wto[i] = wfrom[conformaction[i]];
            wfrom[conformaction[i]] = wwas;
        }
    }
}

    /* conform a scalar, recursively conforming sublists and arrays  */
static t_scalar *template_conformscalar(t_template *tfrom, t_template *tto,
    int *conformaction, t_glist *glist, t_scalar *scfrom)
{
    t_scalar *x;
    t_gpointer gp;
    int nto = tto->t_n, nfrom = tfrom->t_n, i;
    t_template *scalartemplate;
    /* post("conform scalar"); */
        /* possibly replace the scalar */
    if (scfrom->sc_template == tfrom->t_sym)
    {
            /* see scalar_new() for comment about the gpointer. */
        gpointer_init(&gp);
        x = (t_scalar *)getbytes(sizeof(t_scalar) +
            (tto->t_n - 1) * sizeof(*x->sc_vec));
        x->sc_gobj.g_pd = scalar_class;
        x->sc_template = tfrom->t_sym;
        gpointer_setglist(&gp, glist, x);
            /* Here we initialize to the new template, but array and list
            elements will still belong to old template. */
        word_init(x->sc_vec, tto, &gp);

        template_conformwords(tfrom, tto, conformaction,
            scfrom->sc_vec, x->sc_vec);
            
            /* replace the old one with the new one in the list */
        if (glist->gl_list == &scfrom->sc_gobj)
        {
            glist->gl_list = &x->sc_gobj;
            x->sc_gobj.g_next = scfrom->sc_gobj.g_next;
        }
        else
        {
            t_gobj *y, *y2;
            for (y = glist->gl_list; y2 = y->g_next; y = y2)
                if (y2 == &scfrom->sc_gobj)
            {
                x->sc_gobj.g_next = y2->g_next;
                y->g_next = &x->sc_gobj;
                goto nobug;
            }
            bug("template_conformscalar");
        nobug: ;
        }
            /* burn the old one */
        pd_free(&scfrom->sc_gobj.g_pd);
        scalartemplate = tto;
    }
    else
    {
        x = scfrom;
        scalartemplate = template_findbyname(x->sc_template);
    }
        /* convert all array elements and sublists */
    for (i = 0; i < scalartemplate->t_n; i++)
    {
        t_dataslot *ds = scalartemplate->t_vec + i;
        if (ds->ds_type == DT_LIST)
        {
            t_glist *gl2 = x->sc_vec[i].w_list;
            template_conformglist(tfrom, tto, gl2, conformaction);
        }
        else if (ds->ds_type == DT_ARRAY)
        {
            template_conformarray(tfrom, tto, conformaction, 
                x->sc_vec[i].w_array);
        }
    }
    return (x);
}

    /* conform an array, recursively conforming sublists and arrays  */
static void template_conformarray(t_template *tfrom, t_template *tto,
    int *conformaction, t_array *a)
{
    int i, j;
    t_template *scalartemplate = 0;
    if (a->a_templatesym == tfrom->t_sym)
    {
        /* the array elements must all be conformed */
        int oldelemsize = sizeof(t_word) * tfrom->t_n,
            newelemsize = sizeof(t_word) * tto->t_n;
        char *newarray = getbytes(newelemsize * a->a_n);
        char *oldarray = a->a_vec;
        if (a->a_elemsize != oldelemsize)
            bug("template_conformarray");
        for (i = 0; i < a->a_n; i++)
        {
            t_word *wp = (t_word *)(newarray + newelemsize * i);
            word_init(wp, tto, &a->a_gp);
            template_conformwords(tfrom, tto, conformaction,
                (t_word *)(oldarray + oldelemsize * i), wp);
            word_free((t_word *)(oldarray + oldelemsize * i), tfrom);
        }
        scalartemplate = tto;
        a->a_vec = newarray;
        freebytes(oldarray, oldelemsize * a->a_n);
    }
    else scalartemplate = template_findbyname(a->a_templatesym);
        /* convert all arrays and sublist fields in each element of the array */
    for (i = 0; i < a->a_n; i++)
    {
        t_word *wp = (t_word *)(a->a_vec + sizeof(t_word) * a->a_n * i);
        for (j = 0; j < scalartemplate->t_n; j++)
        {
            t_dataslot *ds = scalartemplate->t_vec + j;
            if (ds->ds_type == DT_LIST)
            {
                t_glist *gl2 = wp[j].w_list;
                template_conformglist(tfrom, tto, gl2, conformaction);
            }
            else if (ds->ds_type == DT_ARRAY)
            {
                template_conformarray(tfrom, tto, conformaction, 
                    wp[j].w_array);
            }
        }
    }
}

    /* this routine searches for every scalar in the glist that belongs
    to the "from" template and makes it belong to the "to" template.  Descend
    glists recursively.
    We don't handle redrawing here; this is to be filled in LATER... */

t_array *garray_getarray(t_garray *x);

static void template_conformglist(t_template *tfrom, t_template *tto,
    t_glist *glist,  int *conformaction)
{
    t_gobj *g;
    /* post("conform glist %s", glist->gl_name->s_name); */
    for (g = glist->gl_list; g; g = g->g_next)
    {
        if (pd_class(&g->g_pd) == scalar_class)
            g = &template_conformscalar(tfrom, tto, conformaction,
                glist, (t_scalar *)g)->sc_gobj;
        else if (pd_class(&g->g_pd) == canvas_class)
            template_conformglist(tfrom, tto, (t_glist *)g, conformaction);
        else if (pd_class(&g->g_pd) == garray_class)
            template_conformarray(tfrom, tto, conformaction,
                garray_getarray((t_garray *)g));
    }
}

    /* globally conform all scalars from one template to another */ 
void template_conform(t_template *tfrom, t_template *tto)
{
    int nto = tto->t_n, nfrom = tfrom->t_n, i, j,
        *conformaction = (int *)getbytes(sizeof(int) * nto),
        *conformedfrom = (int *)getbytes(sizeof(int) * nfrom), doit = 0;
    for (i = 0; i < nto; i++)
        conformaction[i] = -1;
    for (i = 0; i < nfrom; i++)
        conformedfrom[i] = 0;
    for (i = 0; i < nto; i++)
    {
        t_dataslot *dataslot = &tto->t_vec[i];
        for (j = 0; j < nfrom; j++)
        {
            t_dataslot *dataslot2 = &tfrom->t_vec[j];
            if (dataslot_matches(dataslot, dataslot2, 1))
            {
                conformaction[i] = j;
                conformedfrom[j] = 1;
            }
        }
    }
    for (i = 0; i < nto; i++)
        if (conformaction[i] < 0)
    {
        t_dataslot *dataslot = &tto->t_vec[i];
        for (j = 0; j < nfrom; j++)
            if (!conformedfrom[j] &&
                dataslot_matches(dataslot, &tfrom->t_vec[j], 0))
        {
            conformaction[i] = j;
            conformedfrom[j] = 1;
        }
    }
    if (nto != nfrom)
        doit = 1;
    else for (i = 0; i < nto; i++)
        if (conformaction[i] != i)
            doit = 1;

    if (doit)
    {
        t_glist *gl;
        post("conforming template '%s' to new structure",
            tfrom->t_sym->s_name);
        for (i = 0; i < nto; i++)
            post("... %d", conformaction[i]);
        for (gl = canvas_list; gl; gl = gl->gl_next)
            template_conformglist(tfrom, tto, gl, conformaction);
    }
    freebytes(conformaction, sizeof(int) * nto);
    freebytes(conformedfrom, sizeof(int) * nfrom);
}

t_template *template_findbyname(t_symbol *s)
{
    return ((t_template *)pd_findbyclass(s, template_class));
}

t_canvas *template_findcanvas(t_template *template)
{
    t_gtemplate *gt;
473
474
    if (!template)
    {
Miller Puckette's avatar
Miller Puckette committed
475
        bug("template_findcanvas");
476
477
        return (0);
    }
Miller Puckette's avatar
Miller Puckette committed
478
479
480
481
482
483
484
485
486
487
488
489
490
491
    if (!(gt = template->t_list))
        return (0);
    return (gt->x_owner);
    /* return ((t_canvas *)pd_findbyclass(template->t_sym, canvas_class)); */
}

void template_notify(t_template *template, t_symbol *s, int argc, t_atom *argv)
{
    if (template->t_list)
        outlet_anything(template->t_list->x_obj.ob_outlet, s, argc, argv);
}

    /* bash the first of (argv) with a pointer to a scalar, and send on
    to template as a notification message */
492
void template_notifyforscalar(t_template *template, t_glist *owner,
Miller Puckette's avatar
Miller Puckette committed
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
    t_scalar *sc, t_symbol *s, int argc, t_atom *argv)
{
    t_gpointer gp;
    gpointer_init(&gp);
    gpointer_setglist(&gp, owner, sc);
    SETPOINTER(argv, &gp);
    template_notify(template, s, argc, argv);
    gpointer_unset(&gp);
}

    /* call this when reading a patch from a file to declare what templates
    we'll need.  If there's already a template, check if it matches.
    If it doesn't it's still OK as long as there are no "struct" (gtemplate)
    objects hanging from it; we just conform everyone to the new template.
    If there are still struct objects belonging to the other template, we're
    in trouble.  LATER we'll figure out how to conform the new patch's objects
    to the pre-existing struct. */
static void *template_usetemplate(void *dummy, t_symbol *s,
    int argc, t_atom *argv)
{
    t_template *x;
    t_symbol *templatesym =
        canvas_makebindsym(atom_getsymbolarg(0, argc, argv));
    if (!argc)
        return (0);
    argc--; argv++;
            /* check if there's already a template by this name. */
    if ((x = (t_template *)pd_findbyclass(templatesym, template_class)))
    {
        t_template *y = template_new(&s_, argc, argv), *y2;
            /* If the new template is the same as the old one,
            there's nothing to do.  */
        if (!template_match(x, y))
        {
                /* Are there "struct" objects upholding this template? */
            if (x->t_list)
            {
                    /* don't know what to do here! */
                error("%s: template mismatch",
                    templatesym->s_name);
            }
            else
            {
                    /* conform everyone to the new template */
                template_conform(x, y);
                pd_free(&x->t_pdobj);
                y2 = template_new(templatesym, argc, argv);
                y2->t_list = 0;
            }
        }
        pd_free(&y->t_pdobj);
    }
        /* otherwise, just make one. */
    else template_new(templatesym, argc, argv);
    return (0);
}

    /* here we assume someone has already cleaned up all instances of this. */
void template_free(t_template *x)
{
    if (*x->t_sym->s_name)
        pd_unbind(&x->t_pdobj, x->t_sym);
    t_freebytes(x->t_vec, x->t_n * sizeof(*x->t_vec));
}

static void template_setup(void)
{
    template_class = class_new(gensym("template"), 0, (t_method)template_free,
        sizeof(t_template), CLASS_PD, 0);
    class_addmethod(pd_canvasmaker, (t_method)template_usetemplate,
        gensym("struct"), A_GIMME, 0);
        
}

/* ---------------- gtemplates.  One per canvas. ----------- */

/* "Struct": an object that searches for, and if necessary creates, 
a template (above).  Other objects in the canvas then can give drawing
instructions for the template.  The template doesn't go away when the
"struct" is deleted, so that you can replace it with
another one to add new fields, for example. */

static void *gtemplate_donew(t_symbol *sym, int argc, t_atom *argv)
{
    t_gtemplate *x = (t_gtemplate *)pd_new(gtemplate_class);
    t_template *t = template_findbyname(sym);
    int i;
    t_symbol *sx = gensym("x");
    x->x_owner = canvas_getcurrent();
    x->x_next = 0;
    x->x_sym = sym;
    x->x_argc = argc;
    x->x_argv = (t_atom *)getbytes(argc * sizeof(t_atom));
    for (i = 0; i < argc; i++)
        x->x_argv[i] = argv[i];

        /* already have a template by this name? */
    if (t)
    {
        x->x_template = t;
            /* if it's already got a "struct" object we
            just tack this one to the end of the list and leave it
            there. */
        if (t->t_list)
        {
            t_gtemplate *x2, *x3;
            for (x2 = x->x_template->t_list; x3 = x2->x_next; x2 = x3)
                ;
            x2->x_next = x;
            post("template %s: warning: already exists.", sym->s_name);
        }
        else
        {
                /* if there's none, we just replace the template with
                our own and conform it. */
            t_template *y = template_new(&s_, argc, argv);
            canvas_redrawallfortemplate(t, 2);
                /* Unless the new template is different from the old one,
                there's nothing to do.  */
            if (!template_match(t, y))
            {
                    /* conform everyone to the new template */
                template_conform(t, y);
                pd_free(&t->t_pdobj);
                t = template_new(sym, argc, argv);
            }
            pd_free(&y->t_pdobj);
            t->t_list = x;
            canvas_redrawallfortemplate(t, 1);
        }
    }
    else
    {
            /* otherwise make a new one and we're the only struct on it. */
        x->x_template = t = template_new(sym, argc, argv);
        t->t_list = x;
    }
    outlet_new(&x->x_obj, 0);
    return (x);
}

static void *gtemplate_new(t_symbol *s, int argc, t_atom *argv)
{
    t_symbol *sym = atom_getsymbolarg(0, argc, argv);
    if (argc >= 1)
        argc--; argv++;
    return (gtemplate_donew(canvas_makebindsym(sym), argc, argv));
}

    /* old version (0.34) -- delete 2003 or so */
static void *gtemplate_new_old(t_symbol *s, int argc, t_atom *argv)
{
    t_symbol *sym = canvas_makebindsym(canvas_getcurrent()->gl_name);
    static int warned;
    if (!warned)
    {
        post("warning -- 'template' (%s) is obsolete; replace with 'struct'",
            sym->s_name);
        warned = 1;
    }
    return (gtemplate_donew(sym, argc, argv));
}

t_template *gtemplate_get(t_gtemplate *x)
{
    return (x->x_template);
}

static void gtemplate_free(t_gtemplate *x)
{
        /* get off the template's list */
    t_template *t = x->x_template;
    t_gtemplate *y;
    if (x == t->t_list)
    {
        canvas_redrawallfortemplate(t, 2);
        if (x->x_next)
        {
                /* if we were first on the list, and there are others on
                the list, make a new template corresponding to the new
                first-on-list and replace the existing template with it. */
            t_template *z = template_new(&s_,
                x->x_next->x_argc, x->x_next->x_argv);
            template_conform(t, z);
            pd_free(&t->t_pdobj);
            pd_free(&z->t_pdobj);
            z = template_new(x->x_sym, x->x_next->x_argc, x->x_next->x_argv);
            z->t_list = x->x_next;
            for (y = z->t_list; y ; y = y->x_next)
                y->x_template = z;
        }
        else t->t_list = 0;
        canvas_redrawallfortemplate(t, 1);
    }
    else
    {
        t_gtemplate *x2, *x3;
        for (x2 = t->t_list; x3 = x2->x_next; x2 = x3)
        {
            if (x == x3)
            {
                x2->x_next = x3->x_next;
                break;
            }
        }
    }
    freebytes(x->x_argv, sizeof(t_atom) * x->x_argc);
}

static void gtemplate_setup(void)
{
    gtemplate_class = class_new(gensym("struct"),
        (t_newmethod)gtemplate_new, (t_method)gtemplate_free,
        sizeof(t_gtemplate), CLASS_NOINLET, A_GIMME, 0);
    class_addcreator((t_newmethod)gtemplate_new_old, gensym("template"),
        A_GIMME, 0);
}

/* ---------------  FIELD DESCRIPTORS ---------------------- */

/* a field descriptor can hold a constant or a variable; if a variable,
it's the name of a field in the template we belong to.  LATER, we might
want to cache the offset of the field so we don't have to search for it
every single time we draw the object.
*/

struct _fielddesc
{
    char fd_type;       /* LATER consider removing this? */
    char fd_var;
    union
    {
        t_float fd_float;       /* the field is a constant float */
        t_symbol *fd_symbol;    /* the field is a constant symbol */
        t_symbol *fd_varsym;    /* the field is variable and this is the name */
    } fd_un;
729
730
731
732
733
    float fd_v1;        /* min and max values */
    float fd_v2;
    float fd_screen1;   /* min and max screen values */
    float fd_screen2;
    float fd_quantum;   /* quantization in value */ 
Miller Puckette's avatar
Miller Puckette committed
734
735
};

736
static void fielddesc_setfloat_const(t_fielddesc *fd, t_float f)
Miller Puckette's avatar
Miller Puckette committed
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
{
    fd->fd_type = A_FLOAT;
    fd->fd_var = 0;
    fd->fd_un.fd_float = f;
    fd->fd_v1 = fd->fd_v2 = fd->fd_screen1 = fd->fd_screen2 =
        fd->fd_quantum = 0;
}

static void fielddesc_setsymbol_const(t_fielddesc *fd, t_symbol *s)
{
    fd->fd_type = A_SYMBOL;
    fd->fd_var = 0;
    fd->fd_un.fd_symbol = s;
    fd->fd_v1 = fd->fd_v2 = fd->fd_screen1 = fd->fd_screen2 =
        fd->fd_quantum = 0;
}

static void fielddesc_setfloat_var(t_fielddesc *fd, t_symbol *s)
{
    char *s1, *s2, *s3, strbuf[MAXPDSTRING];
    int i;
    fd->fd_type = A_FLOAT;
    fd->fd_var = 1;
    if (!(s1 = strchr(s->s_name, '(')) || !(s2 = strchr(s->s_name, ')'))
        || (s1 > s2))
    {
        fd->fd_un.fd_varsym = s;
        fd->fd_v1 = fd->fd_v2 = fd->fd_screen1 = fd->fd_screen2 =
            fd->fd_quantum = 0;
    }
    else
    {
        int cpy = s1 - s->s_name, got;
        if (cpy > MAXPDSTRING-5)
            cpy = MAXPDSTRING-5;
        strncpy(strbuf, s->s_name, cpy);
        strbuf[cpy] = 0;
        fd->fd_un.fd_varsym = gensym(strbuf);
        got = sscanf(s1, "(%f:%f)(%f:%f)(%f)",
            &fd->fd_v1, &fd->fd_v2, &fd->fd_screen1, &fd->fd_screen2,
                &fd->fd_quantum);
        if (got < 2)
            goto fail;
        if (got == 3 || (got < 4 && strchr(s2, '(')))
            goto fail;
        if (got < 5 && (s3 = strchr(s2, '(')) && strchr(s3+1, '('))
            goto fail;
        if (got == 4)
            fd->fd_quantum = 0;
        else if (got == 2)
        {
            fd->fd_quantum = 0;
            fd->fd_screen1 = fd->fd_v1;
            fd->fd_screen2 = fd->fd_v2;
        }
        return;
    fail:
        post("parse error: %s", s->s_name);
        fd->fd_v1 = fd->fd_screen1 = fd->fd_v2 = fd->fd_screen2 =
            fd->fd_quantum = 0;
    }
}

#define CLOSED 1
#define BEZ 2
#define NOMOUSE 4
803
#define BBOX 8          /* pair of coords for rectangles and ellipses */
Miller Puckette's avatar
Miller Puckette committed
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
#define A_ARRAY 55      /* LATER decide whether to enshrine this in m_pd.h */

static void fielddesc_setfloatarg(t_fielddesc *fd, int argc, t_atom *argv)
{
        if (argc <= 0) fielddesc_setfloat_const(fd, 0);
        else if (argv->a_type == A_SYMBOL)
            fielddesc_setfloat_var(fd, argv->a_w.w_symbol);
        else fielddesc_setfloat_const(fd, argv->a_w.w_float);
}

static void fielddesc_setsymbolarg(t_fielddesc *fd, int argc, t_atom *argv)
{
        if (argc <= 0) fielddesc_setsymbol_const(fd, &s_);
        else if (argv->a_type == A_SYMBOL)
        {
            fd->fd_type = A_SYMBOL;
            fd->fd_var = 1;
            fd->fd_un.fd_varsym = argv->a_w.w_symbol;
            fd->fd_v1 = fd->fd_v2 = fd->fd_screen1 = fd->fd_screen2 =
                fd->fd_quantum = 0;
        }
        else fielddesc_setsymbol_const(fd, &s_);
}

static void fielddesc_setarrayarg(t_fielddesc *fd, int argc, t_atom *argv)
{
        if (argc <= 0) fielddesc_setfloat_const(fd, 0);
        else if (argv->a_type == A_SYMBOL)
        {
            fd->fd_type = A_ARRAY;
            fd->fd_var = 1;
            fd->fd_un.fd_varsym = argv->a_w.w_symbol;
        }
        else fielddesc_setfloat_const(fd, argv->a_w.w_float);
}

    /* getting and setting values via fielddescs -- note confusing names;
    the above are setting up the fielddesc itself. */
static t_float fielddesc_getfloat(t_fielddesc *f, t_template *template,
    t_word *wp, int loud)
{
    if (f->fd_type == A_FLOAT)
    {
        if (f->fd_var)
            return (template_getfloat(template, f->fd_un.fd_varsym, wp, loud));
        else return (f->fd_un.fd_float);
    }
    else
    {
        if (loud)
            error("symbolic data field used as number");
        return (0);
    }
}

    /* convert a variable's value to a screen coordinate via its fielddesc */
860
t_float fielddesc_cvttocoord(t_fielddesc *f, t_float val)
Miller Puckette's avatar
Miller Puckette committed
861
{
862
    t_float coord, pix, extreme, div;
Miller Puckette's avatar
Miller Puckette committed
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
    if (f->fd_v2 == f->fd_v1)
        return (val);
    div = (f->fd_screen2 - f->fd_screen1)/(f->fd_v2 - f->fd_v1);
    coord = f->fd_screen1 + (val - f->fd_v1) * div;
    extreme = (f->fd_screen1 < f->fd_screen2 ?
        f->fd_screen1 : f->fd_screen2);
    if (coord < extreme)
        coord = extreme;
    extreme = (f->fd_screen1 > f->fd_screen2 ? 
        f->fd_screen1 : f->fd_screen2);
    if (coord > extreme)
        coord = extreme;
    return (coord);
}

    /* read a variable via fielddesc and convert to screen coordinate */
t_float fielddesc_getcoord(t_fielddesc *f, t_template *template,
    t_word *wp, int loud)
{
    if (f->fd_type == A_FLOAT)
    {
        if (f->fd_var)
        {
886
            t_float val = template_getfloat(template,
Miller Puckette's avatar
Miller Puckette committed
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
                f->fd_un.fd_varsym, wp, loud);
            return (fielddesc_cvttocoord(f, val));
        }
        else return (f->fd_un.fd_float);
    }
    else
    {
        if (loud)
            error("symbolic data field used as number");
        return (0);
    }
}

static t_symbol *fielddesc_getsymbol(t_fielddesc *f, t_template *template,
    t_word *wp, int loud)
{
    if (f->fd_type == A_SYMBOL)
    {
        if (f->fd_var)
            return(template_getsymbol(template, f->fd_un.fd_varsym, wp, loud));
        else return (f->fd_un.fd_symbol);
    }
    else
    {
        if (loud)
            error("numeric data field used as symbol");
        return (&s_);
    }
}

    /* convert from a screen coordinate to a variable value */
918
t_float fielddesc_cvtfromcoord(t_fielddesc *f, t_float coord)
Miller Puckette's avatar
Miller Puckette committed
919
{
920
    t_float val;
Miller Puckette's avatar
Miller Puckette committed
921
922
923
924
    if (f->fd_screen2 == f->fd_screen1)
        val = coord;
    else
    {
925
926
        t_float div = (f->fd_v2 - f->fd_v1)/(f->fd_screen2 - f->fd_screen1);
        t_float extreme;
Miller Puckette's avatar
Miller Puckette committed
927
928
929
930
931
932
933
934
935
936
937
938
939
940
        val = f->fd_v1 + (coord - f->fd_screen1) * div;
        if (f->fd_quantum != 0)
            val = ((int)((val/f->fd_quantum) + 0.5)) *  f->fd_quantum;
        extreme = (f->fd_v1 < f->fd_v2 ?
            f->fd_v1 : f->fd_v2);
        if (val < extreme) val = extreme;
        extreme = (f->fd_v1 > f->fd_v2 ?
            f->fd_v1 : f->fd_v2);
        if (val > extreme) val = extreme;
    }
    return (val);
 }

void fielddesc_setcoord(t_fielddesc *f, t_template *template,
941
    t_word *wp, t_float coord, int loud)
Miller Puckette's avatar
Miller Puckette committed
942
943
944
{
    if (f->fd_type == A_FLOAT && f->fd_var)
    {
945
        t_float val = fielddesc_cvtfromcoord(f, coord);
Miller Puckette's avatar
Miller Puckette committed
946
947
948
949
950
951
952
953
954
955
        template_setfloat(template,
                f->fd_un.fd_varsym, wp, val, loud);
    }
    else
    {
        if (loud)
            error("attempt to set constant or symbolic data field to a number");
    }
}

956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
/* ---------------- draw svg shapes and paths ---------------- */

/*
draws belong to templates and describe how the data in the template are to
be drawn.  The coordinates of the draw (and other display features) can
be attached to fields in the template.

todo: draw_click doesn't work with paths yet
todo: some better way than drawcurve for defining click widgetbehaviors (just
      checking for field variables and moving joints is too simplistic)
*/

t_class *draw_class;

typedef struct _draw
{
    t_object x_obj;
    int x_flags;            /* CLOSED and/or BEZ and/or NOMOUSE */
    t_symbol *x_drawtype;
    t_symbol *x_fill;
    t_fielddesc x_fill_r;
    t_fielddesc x_fill_g;
    t_fielddesc x_fill_b;
    t_fielddesc x_fillopacity;
    t_fielddesc x_fillrule;
    t_symbol *x_stroke;
    t_fielddesc x_stroke_r;
    t_fielddesc x_stroke_g;
    t_fielddesc x_stroke_b;
    int x_ndash;
    t_fielddesc *x_strokedasharray; /* array of lengths */
    t_fielddesc x_strokelinecap;
    t_fielddesc x_strokelinejoin;
    t_fielddesc x_strokemiterlimit;
    t_fielddesc x_strokeopacity;
    t_fielddesc x_strokewidth;
    t_fielddesc x_rx; /* for rounded rectangles */
    t_fielddesc x_ry;
    int x_transform_n;
    t_fielddesc *x_transform;
    t_fielddesc x_width;
    t_fielddesc x_vis;
    int x_pathrect_cache; /* 0 to recalc on next draw_getrect call
                             1 for cached
                            -1 to turn off caching */
    int x_x1; /* use these for caching path bbox */
    int x_y1;
    int x_x2;
    int x_y2;
    int x_nargs;
    t_fielddesc *x_vec;
    int *x_nargs_per_cmd;      /* points per each path command */
    int x_npathcmds;
    char *x_pathcmds; /* for path commands */
    t_canvas *x_canvas;
} t_draw;

static int is_svgpath_cmd(t_symbol *s)
{
    /* 1 for absolute cmd, 2 for relative */
    if (s == gensym("M") || s == gensym("Z") || s == gensym("L") ||
        s == gensym("H") || s == gensym("V") || s == gensym("C") ||
        s == gensym("S") || s == gensym("Q") || s == gensym("T") ||
        s == gensym("A"))
        return 1;
    else if (s == gensym("m") || s == gensym("z") || s == gensym("l") ||
        s == gensym("h") || s == gensym("v") || s == gensym("c") ||
        s == gensym("s") || s == gensym("q") || s == gensym("t") ||
        s == gensym("a"))
        return 2;
    else return 0;
}

static int path_ncmds(int argc, t_atom *argv)
{
    int i, j = 0;
    for(i = 0; i < argc; i++)
    {
        if (argv[i].a_type == A_SYMBOL && is_svgpath_cmd(atom_getsymbol(argv+i)))
            j++;
    }
    return j;
}

t_draw *draw_getgroup(t_draw *x)
{
    t_gobj *g;
    t_draw *dgroup = 0;
    t_template *templ;
    t_symbol *s1 = gensym("draw");
    t_symbol *s2 = gensym("group");
    for(g = x->x_canvas->gl_list; g; g = g->g_next)
    {
        t_object *ob = pd_checkobject(&g->g_pd);
        t_atom *argv;
        if (!ob || ob->te_type != T_OBJECT ||
            binbuf_getnatom(ob->te_binbuf) < 2)
            continue;
        argv = binbuf_getvec(ob->te_binbuf);
        if (argv[0].a_type != A_SYMBOL || argv[1].a_type != A_SYMBOL
            || argv[0].a_w.w_symbol != s1 || argv[1].a_w.w_symbol != s2)
            continue;
        dgroup = (t_draw *)g;
        break;
    }
    return (dgroup);
}

static void *draw_new(t_symbol *classsym, t_int argc, t_atom *argv)
{
    t_draw *x = (t_draw *)pd_new(draw_class);
   /* not sure about classname here... */
    if (argc && argv->a_type == A_SYMBOL)
        x->x_drawtype = atom_getsymbolarg(0, argc--, argv++);
    else
    {
        pd_error(x, "draw: need an svg shape (rect, circle, path, etc.)");
    }
    int flags = 0;
    int nxy, i;
    t_fielddesc *fd;
    x->x_canvas = canvas_getcurrent();
    fielddesc_setfloat_const(&x->x_vis, 1);
    while (1)
    {
        t_symbol *firstarg = atom_getsymbolarg(0, argc, argv);
        if (!strcmp(firstarg->s_name, "-v") && argc > 1)
        {
            fielddesc_setfloatarg(&x->x_vis, 1, argv+1);
            argc -= 2; argv += 2;
        }
        else if (!strcmp(firstarg->s_name, "-x"))
        {
            flags |= NOMOUSE;
            argc -= 1; argv += 1;
        }
        else break;
    }
    x->x_flags = flags;
    if (argc < 0) argc = 0;
    if (x->x_drawtype == gensym("path"))
    {
        int ncmds = x->x_npathcmds = path_ncmds(argc, argv);
        x->x_pathcmds = (char *)t_getbytes(ncmds * sizeof(char));
        x->x_nargs_per_cmd = (int *)t_getbytes(ncmds * sizeof(int));
        for (i = 0; i < ncmds; i++) x->x_nargs_per_cmd[i] = 0;
        nxy = x->x_nargs = argc - ncmds;
    }
    else if (x->x_drawtype == gensym("group"))
    {
        nxy = 0;
        x->x_nargs = 0;
        x->x_vec = 0;
        t_draw *dgroup = draw_getgroup(x);
        if (dgroup)
        {
            pd_error(x, "draw group: only one group per canvas allowed");
            return (0);
        }
    }
    else /* all other shapes */
    {
        nxy =  (argc + (argc & 1));
        x->x_nargs = nxy;
    }
    x->x_vec = (t_fielddesc *)t_getbytes(nxy * sizeof(t_fielddesc));

    if (argc && x->x_drawtype == gensym("path"))
    {
        if (argv->a_type != A_SYMBOL ||
1126
1127
            (atom_getsymbol(argv) != gensym("M") &&
             atom_getsymbol(argv) != gensym("m")))
1128
1129
        {
            pd_error(x, "draw path: path data must start "
1130
                        "with a moveto command (M or m)");
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
            return 0;
        }
    }

    int cmdn = -1; /* hack */
    for (i = 0, fd = x->x_vec; i < argc; i++, argv++)
    {
        if (x->x_drawtype == gensym("path") &&
            argv->a_type == A_SYMBOL &&
            is_svgpath_cmd(atom_getsymbol(argv)))
        {
                x->x_pathcmds[++cmdn] = *(atom_getsymbol(argv)->s_name);
        }
        else
        {
            fielddesc_setfloatarg(fd++, 1, argv);
            /* post("got a coord"); */
            if (x->x_drawtype == gensym("path"))
            {
                (x->x_nargs_per_cmd[cmdn])++;
                /* if we get a field variable, just
                   turn off the get_rect caching */
                if (argv->a_type == A_SYMBOL)
                    x->x_pathrect_cache = -1;
            }
        }
    }
    if (argc & 1 && x->x_drawtype != gensym("path")) fielddesc_setfloat_const(fd, 0);
    x->x_fill = gensym("\"\"");
    fielddesc_setfloat_const(&x->x_fillopacity, 1);
    fielddesc_setfloat_const(&x->x_fillrule, 0);
    x->x_stroke = gensym("black");
    fielddesc_setfloat_const(&x->x_strokelinecap, 0);
    fielddesc_setfloat_const(&x->x_strokelinejoin, 0);
    fielddesc_setfloat_const(&x->x_strokemiterlimit, 0);
    fielddesc_setfloat_const(&x->x_strokeopacity, 1);
    fielddesc_setfloat_const(&x->x_strokewidth, 1);
    x->x_x1 = 0;
    x->x_x2 = 0;
    x->x_y1 = 0;
    x->x_y2 = 0;

    x->x_ndash = 0;
    x->x_strokedasharray = (t_fielddesc *)t_getbytes(1 * sizeof(t_fielddesc));
    x->x_transform_n = 0;
    x->x_transform = (t_fielddesc *)t_getbytes(1 * sizeof(t_fielddesc));

    char buf[50];
    sprintf(buf, ".x%lx", (long unsigned int)x);

    pd_bind(&x->x_obj.ob_pd, gensym(buf));
    
    return (x);
}

void draw_float(t_draw *x, t_floatarg f)
{
    int viswas;
    if (x->x_vis.fd_type != A_FLOAT || x->x_vis.fd_var)
    {
        pd_error(x, "global vis/invis for a template with variable visibility");
        return;
    }
    viswas = (x->x_vis.fd_un.fd_float != 0);

    if ((f != 0 && viswas) || (f == 0 && !viswas))
        return;
    canvas_redrawallfortemplatecanvas(x->x_canvas, 2);
    fielddesc_setfloat_const(&x->x_vis, (f != 0));
    canvas_redrawallfortemplatecanvas(x->x_canvas, 1);
}

static char *rgb_to_hex(int r, int g, int b)
{
    static char hexc[10];
    int r1 = r < 0 ? 0 : r;
    if (r1 > 255) r1 = 255;
    int g1 = g < 0 ? 0 : g;
    if (g1 > 255) g1 = 255;
    int b1 = b < 0 ? 0 : b;
    if (b1 > 255) b1 = 255;
    sprintf(hexc, "#%.6x", (r1 << 16) + (g1 << 8) + b1);
    return hexc;
}

char *get_strokelinecap(int a)
{
1218
    static char strokelinecap[15];
1219
1220
    if (a == 0) sprintf(strokelinecap, "butt");
    else if (a == 1) sprintf(strokelinecap, "round");
1221
    else if (a == 2) sprintf(strokelinecap, "projecting");
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
    else sprintf(strokelinecap, "butt");
    return (strokelinecap);
}

char *get_strokelinejoin(int a)
{
    static char strokelinejoin[8];
    if (a == 0) sprintf(strokelinejoin, "miter");
    else if (a == 1) sprintf(strokelinejoin, "round");
    else if (a == 2) sprintf(strokelinejoin, "bevel");
    else sprintf(strokelinejoin, "miter");
    return (strokelinejoin);
}

void draw_doupdate(t_draw *x, t_canvas *c, t_symbol *s)
{
    t_gobj *g;
    t_template *template;
1240
1241
1242
    t_canvas *visible = c;
    while(visible->gl_isgraph && visible->gl_owner)
        visible = visible->gl_owner;
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
    int isgroup = (x->x_drawtype == gensym("group"));
    for (g = c->gl_list; g; g = g->g_next)
    {
        if (glist_isvisible(c) && g->g_pd == scalar_class &&
            x->x_canvas ==
            template_findcanvas(template = (template_findbyname(
                (((t_scalar *)g)->sc_template))))
           )
        {
            t_word *data = ((t_scalar *)g)->sc_vec;
            char str[MAXPDSTRING];
            if (s == gensym("fill"))
            {
                char *fill;
                if (x->x_fill)
                    fill = x->x_fill->s_name;
                else
                {
                    fill = rgb_to_hex(
                        (int)fielddesc_getfloat(&x->x_fill_r,
                            template, data, 1),
                        (int)fielddesc_getfloat(&x->x_fill_g,
                            template, data, 1),
                        (int)fielddesc_getfloat(&x->x_fill_b,
                            template, data, 1));
                }
                sprintf(str, "-fill %s", fill);
            }
            else if (s == gensym("stroke"))
            {
                char *stroke;
                if (x->x_stroke)
                    stroke = x->x_stroke->s_name;
                else
                {
                    stroke = rgb_to_hex(
                        (int)fielddesc_getfloat(&x->x_stroke_r,
                            template, data, 1),
                        (int)fielddesc_getfloat(&x->x_stroke_g,
                            template, data, 1),
                        (int)fielddesc_getfloat(&x->x_stroke_b,
                            template, data, 1));
                }
                sprintf(str, "-stroke %s", stroke);
            }
            else if (s == gensym("fill-opacity"))
                sprintf(str, "-fillopacity %g",
                    fielddesc_getcoord(&x->x_fillopacity, template, data, 1));
            else if (s == gensym("fill-rule"))
                sprintf(str, "-fillrule %s", (int)fielddesc_getcoord(
                    &x->x_fillrule, template, data, 1) ?
                       "evenodd" : "nonzero");
            else if (s == gensym("stroke-linecap"))
                sprintf(str, "-strokelinecap %s", get_strokelinecap(
                    (int)fielddesc_getcoord(&x->x_strokelinecap,
                        template, data, 1)));
            else if (s == gensym("stroke-linejoin"))
                sprintf(str, "-strokelinejoin %s", get_strokelinejoin(
                    (int)fielddesc_getcoord(&x->x_strokelinejoin,
                        template, data, 1)));
            else if (s == gensym("stroke-miterlimit"))
                sprintf(str, "-strokemiterlimit %g", fielddesc_getcoord(
                    &x->x_strokemiterlimit, template, data, 1));
            else if (s == gensym("stroke-opacity"))
                sprintf(str, "-strokeopacity %g", fielddesc_getcoord(
                    &x->x_strokeopacity, template, data, 1));
            else if (s == gensym("stroke-width"))
                sprintf(str, "-strokewidth %g", fielddesc_getcoord(
                    &x->x_strokewidth, template, data, 1));
            else if (s == gensym("rx"))
                sprintf(str, "-rx %g", fielddesc_getcoord(
                    &x->x_rx, template, data, 1));
            else if (s == gensym("ry"))
                sprintf(str, "-ry %g", fielddesc_getcoord(
                    &x->x_ry, template, data, 1));
            else if (s == gensym("stroke-dasharray"))
            {
                if (x->x_ndash)
                {
                    t_fielddesc *fd = x->x_strokedasharray;
                    int i;
                    char *cur = str, * const end = str + sizeof str;
                    cur += snprintf(cur, end-cur, "-strokedasharray {");
                    for (i = 0; i < x->x_ndash; i++)
                        if (cur < end)
                            cur += snprintf(cur, end-cur, " %g ",
                                fielddesc_getcoord(fd+i, template, data, 1));
                    cur += snprintf(cur, end-cur, "}\n");
                }
                else return;
            }
            if (x->x_drawtype == gensym("group"))
            {
                sys_vgui(".x%lx.c itemconfigure .dgroup%lx %s\n",
                   visible, data, str);
            }
            else
            {
                sys_vgui(".x%lx.c itemconfigure .draw%lx.%lx %s\n",
                   visible, x, data, str);
            }
1344
            sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", visible);
1345
        }
1346
1347
        if (g->g_pd == canvas_class)
        {
1348
            draw_doupdate(x, (t_glist *)g, s);
1349
        }
1350
1351
1352
1353
1354
1355
1356
1357
1358
    }
}

extern t_canvas *canvas_list;
void draw_update(t_draw *x, t_symbol *s)
{
    t_canvas *c;
    for (c = canvas_list; c; c = c->gl_next)
        draw_doupdate(x, c, s);
1359

1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
}

void draw_fillopacity(t_draw *x, t_symbol *s, t_int argc, t_atom *argv)
{
    if (argv[0].a_type == A_FLOAT || argv[0].a_type == A_SYMBOL)
    {
        fielddesc_setfloatarg(&x->x_fillopacity, argc, argv);
        draw_update(x, s);
    }
}

void draw_strokeopacity(t_draw *x, t_symbol *s, t_int argc, t_atom *argv)
{
    if (argv[0].a_type == A_FLOAT || argv[0].a_type == A_SYMBOL)
    {
        fielddesc_setfloatarg(&x->x_strokeopacity, argc, argv);
        draw_update(x, s);
    }
}

void draw_strokedasharray(t_draw *x, t_symbol *s, int argc, t_atom *argv)
{
    t_fielddesc *fd;
    x->x_strokedasharray = (t_fielddesc *)t_resizebytes(x->x_strokedasharray,
        x->x_ndash * sizeof(*x->x_strokedasharray),
        argc * sizeof(*x->x_strokedasharray));
    x->x_ndash = argc;
    fd = x->x_strokedasharray;
    while (argc)
        fielddesc_setfloatarg(fd++, argc--, argv++);
    draw_update(x, s);
}

void draw_fill(t_draw *x, t_symbol *s, t_int argc, t_atom *argv)
{
    if (argc == 1 && argv->a_type == A_SYMBOL)
        x->x_fill = atom_getsymbolarg(0, argc, argv);
    else if (argc > 2)
    {
        int i, var = 0;
        /* if there's a color variable field we have to recalculate
           it each redraw in draw_vis */
        for(i = 0; i < argc; i++)
            var = (argv[i].a_type == A_SYMBOL) ? 1 : var;
        if (var)
        {
            fielddesc_setfloatarg(&x->x_fill_r, argc--, argv++);
            fielddesc_setfloatarg(&x->x_fill_g, argc--, argv++);
            fielddesc_setfloatarg(&x->x_fill_b, argc--, argv++);
            x->x_fill = 0;
        }
        else
        {
            int r = (int)atom_getfloatarg(0, argc--, argv++);
            int g = (int)atom_getfloatarg(0, argc--, argv++);
            int b = (int)atom_getfloatarg(0, argc--, argv++);
            x->x_fill = gensym(rgb_to_hex(r, g, b));
        }
        if (argc && (argv->a_type == A_FLOAT || argv->a_type == A_SYMBOL))
        {
1420
            draw_fillopacity(x, gensym("fill-opacity"), argc, argv);
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
        }
    }
    draw_update(x, s);
}

void draw_stroke(t_draw *x, t_symbol *s, t_int argc, t_atom *argv)
{
    if (argc == 1 && argv->a_type == A_SYMBOL)
        x->x_stroke = atom_getsymbolarg(0, argc, argv);
    else if (argc > 2)
    {
        int var = 0, i;
        for(i = 0; i < argc; i++)
            var = (argv[i].a_type == A_SYMBOL) ? 1 : var;
        if (var)
        {
            fielddesc_setfloatarg(&x->x_stroke_r, argc--, argv++);
            fielddesc_setfloatarg(&x->x_stroke_g, argc--, argv++);
            fielddesc_setfloatarg(&x->x_stroke_b, argc--, argv++);
            x->x_stroke = 0;
        }
        else
        {
            /* if no variables, then precompute x_stroke so it doesn't
               have to happen every call to draw_vis */
            int r = (int)atom_getfloatarg(0, argc--, argv++);
            int g = (int)atom_getfloatarg(0, argc--, argv++);
            int b = (int)atom_getfloatarg(0, argc--, argv++);
            x->x_stroke = gensym(rgb_to_hex(r, g, b));
        }
        if (argc && (argv->a_type == A_FLOAT || argv->a_type == A_SYMBOL))
        {
            draw_strokeopacity(x, s, argc, argv);
            return;
        }
    }
    draw_update(x, s);
}

void draw_strokelinecap(t_draw *x, t_symbol *s, t_int argc, t_atom *argv)
{
    if (argv[0].a_type == A_FLOAT || argv[0].a_type == A_SYMBOL)
    {
        fielddesc_setfloatarg(&x->x_strokelinecap, argc, argv);
        draw_update(x, s);
    }
}

void draw_strokelinejoin(t_draw *x, t_symbol *s, t_int argc, t_atom *argv)
{
    if (argv[0].a_type == A_FLOAT || argv[0].a_type == A_SYMBOL)
    {
        fielddesc_setfloatarg(&x->x_strokelinejoin, argc, argv);
        draw_update(x, s);
    }
}

void draw_strokemiterlimit(t_draw *x, t_symbol *s, t_int argc, t_atom *argv)
{
    if (argv[0].a_type == A_FLOAT || argv[0].a_type == A_SYMBOL)
    {
        fielddesc_setfloatarg(&x->x_strokemiterlimit, argc, argv);
        draw_update(x, s);
    }
}

void draw_strokewidth(t_draw *x, t_symbol *s, t_int argc, t_atom *argv)
{
    if (argv[0].a_type == A_FLOAT || argv[0].a_type == A_SYMBOL)
    {
        fielddesc_setfloatarg(&x->x_strokewidth, argc, argv);
        draw_update(x, s);
    }
}

void draw_fillrule(t_draw *x, t_symbol *s, t_int argc, t_atom *argv)
{
    if (argv[0].a_type == A_FLOAT || argv[0].a_type == A_SYMBOL)
    {
        fielddesc_setfloatarg(&x->x_fillrule, argc, argv);
        draw_update(x, s);
    }
}

void draw_rx(t_draw *x, t_symbol *s, int argc, t_atom *argv)
{
    if (x->x_drawtype != gensym("rect"))
    {
        pd_error(x, "draw: %s: no method for 'rx'", x->x_drawtype->s_name);
        return;
    }
    if (!argc || argv->a_type != A_FLOAT)
    {
        pd_error(x, "draw: rect: bad arguments for method 'rx'");
        return;
    }
    fielddesc_setfloatarg(&x->x_rx, argc, argv);
    draw_update(x, s);
}

void draw_ry(t_draw *x, t_symbol *s, int argc, t_atom *argv)
{
    if (x->x_drawtype != gensym("rect"))
    {
        pd_error(x, "draw: %s: no method for 'ry'", x->x_drawtype->s_name);
        return;
    }
    if (!argc || argv->a_type != A_FLOAT)
    {
        pd_error(x, "draw: rect: bad arguments for method 'ry'");
        return;
    }
    fielddesc_setfloatarg(&x->x_ry, argc, argv);
    draw_update(x, s);
}

static int draw_minv(t_float a[][3], t_float b[][3])
{
    t_float tmp[3][3], determinant = 0;
    int i, j;
    for(i = 0; i < 3; i++)
        determinant = determinant +
            (a[0][i]*(a[1][(i+1)%3]*a[2][(i+2)%3] -
            a[1][(i+2)%3]*a[2][(i+1)%3]));
    if (!determinant) return 0;
    for(i = 0; i < 3; i++)
    {
      for(j=0;j<3;j++)
           tmp[j][i] = ((a[(i+1)%3][(j+1)%3] * a[(i+2)%3][(j+2)%3]) - (a[(i+1)%3][(j+2)%3]*a[(i+2)%3][(j+1)%3]))/ determinant;
    }
    for(i = 0; i < 3; i++)
        for (j = 0; j < 3; j++)
            b[i][j] = tmp[i][j];
    return 1;
}

/* multiply matrix a by b and put result in c. if desired, c
   can point to a or b. */
void draw_mmult(t_float a[][3], t_float b[][3], t_float c[][3])
{
    t_float tmp[3][3] = { {0, 0, 0}, {0, 0, 0}, {0, 0, 0} };
    int i, j, k;
    for(i = 0; i < 3; i++)
        for(j = 0; j < 3; j++)
        {
            t_float sum = 0;
            for(k = 0; k < 3; k++)
                sum = sum + a[i][k] * b[k][j];
            tmp[i][j] = sum;
        }
    for(i = 0; i < 3; i++)
        for(j = 0; j < 3; j++)
            c[i][j] = tmp[i][j];
}

void draw_mset(t_float mtx[][3], t_float m1, t_float m2, t_float m3,
    t_float m4, t_float m5, t_float m6)
{
    mtx[0][0] = m1; mtx[1][0] = m2; mtx[0][1] = m3;
    mtx[1][1] = m4; mtx[0][2] = m5; mtx[1][2] = m6;
    mtx[2][0] = 0;  mtx[2][1] = 0;  mtx[2][2] = 1;
}

/* not sure if this is useful... */
void draw_mget(t_float mtx[][3], t_float *mp1, t_float *mp2, t_float *mp3,
    t_float *mp4, t_float *mp5, t_float *mp6)
{
    *mp1 = mtx[0][0]; *mp2 = mtx[1][0]; *mp3 = mtx[0][1];
    *mp4 = mtx[1][1]; *mp5 = mtx[0][2]; *mp6 = mtx[1][2];
}

void draw_parsetransform(t_draw *x, t_template *template, t_word *data,
    t_float *mp1, t_float *mp2, t_float *mp3,
    t_float *mp4, t_float *mp5, t_float *mp6)
{
    /* parse the args */
    t_symbol *type;
    int i, j;
    t_float m[3][3];
    t_float m2[3][3];
    draw_mset(m, 1, 0, 0, 1, 0, 0); /* init to the identity matrix... */
    draw_mset(m2, 0, 0, 0, 0, 0, 0);
    int argc = x->x_transform_n;
    t_fielddesc *fd = x->x_transform;
    /* should probably change this to argc > 0 since a screwup
       could land us in negativeland */
    while (argc)
    {
        if (fd->fd_un.fd_varsym)
            type = fd->fd_un.fd_varsym;
        else
        {
            pd_error(x, "draw: bad args to 'transform' method");
            return;
        }
        fd++;
        argc --;
        if (type == gensym("translate"))
        {
           t_float tx = fielddesc_getfloat(fd++, template, data, 0);
           argc--;
           t_float ty = fielddesc_getfloat(fd++, template, data, 0);
           argc--;
           draw_mset(m2, 1, 0, 0, 1, tx, ty);
           draw_mmult(m, m2, m);
        }
        else if (type == gensym("scale"))
        {
           t_float sx = fielddesc_getfloat(fd++, template, data, 0);
           argc--;
           t_float sy = sx;
           if (argc && fd->fd_type == A_FLOAT)
           {
               sy = fielddesc_getfloat(fd++, template, data, 0);
               argc--;
           }
           draw_mset(m2, sx, 0, 0, sy, 0, 0);
           draw_mmult(m, m2, m);
        }
        /* cx and cy are optional */
        /* this doesn't jibe with glist_xtopixels, ytopixels, etc. */
        else if (type == gensym("rotate"))
        {
            t_float a = fielddesc_getfloat(fd++, template, data, 0);
            argc--;
            t_float cx = 0, cy = 0;
            if (argc && fd->fd_type == A_FLOAT)
            {
                cx = fielddesc_getfloat(fd++, template, data, 0);
                argc--;
            }
            if (argc && fd->fd_type == A_FLOAT)
            {
                cy = fielddesc_getfloat(fd++, template, data, 0);
                argc--;
            }
            draw_mset(m2, cos(a), sin(a), sin(a) * -1, cos(a),
                      sin(a) * cy + cx * -1 * cos(a) + cx,
                      sin(a) * cx * -1 + cos(a) * cy * -1 + cy);
            draw_mmult(m, m2, m);
        }
        else if (type == gensym("skewx"))
        {
            t_float a = fielddesc_getfloat(fd++, template, data, 0);
            argc--;
            draw_mset(m2, 1, 0, tan(a), 1, 0, 0);
            draw_mmult(m, m2, m);
        }
        else if (type == gensym("skewy"))
        {
            t_float a = fielddesc_getfloat(fd++, template, data, 0);
            argc--;
            draw_mset(m2, 1, tan(a), 0, 1, 0, 0);
            draw_mmult(m, m2, m);
        }
        else if (type == gensym("matrix"))
        {
            t_float a, b, c, d, e, f;
            a = fielddesc_getfloat(fd++, template, data, 0); argc--;
            b = fielddesc_getfloat(fd++, template, data, 0); argc--;
            c = fielddesc_getfloat(fd++, template, data, 0); argc--;
            d = fielddesc_getfloat(fd++, template, data, 0); argc--;
            e = fielddesc_getfloat(fd++, template, data, 0); argc--;
            f = fielddesc_getfloat(fd++, template, data, 0); argc--;
            draw_mset(m2, a, b, c, d, e, f);
            draw_mmult(m, m2, m);
        }
    }
    t_float a1, a2, a3, a4, a5, a6;
    draw_mget(m, &a1, &a2, &a3, &a4, &a5, &a6);
    *mp1 = a1;
    *mp2 = a2;
    *mp3 = a3;
    *mp4 = a4;
    *mp5 = a5;
    *mp6 = a6;
}

void draw_group_pathrect_cache(t_draw *x, int state)
{
    t_gobj *y;
    for (y = x->x_canvas->gl_list; y; y = y->g_next)
    {
        if (pd_class(&y->g_pd) == draw_class &&
            ((t_draw *)y)->x_pathrect_cache != -1)
                ((t_draw *)y)->x_pathrect_cache = state;
    } 
}

extern void scalar_select(t_gobj *z, t_glist *owner, int state);
extern void scalar_drawselectrect(t_scalar *x, t_glist *glist, int state);
void draw_doupdatetransform(t_draw *x, t_canvas *c)
{
    t_float mtx1[3][3];
    t_float mtx2[3][3];
    t_float mtx3[3][3];
    draw_mset(mtx1, 0, 0, 0, 0, 0, 0);
    draw_mset(mtx2, 0, 0, 0, 0, 0, 0);
    t_gobj *g;
    t_template *template;
1721
1722
1723
    t_canvas *visible = c;
    while(visible->gl_isgraph && visible->gl_owner)
        visible = visible->gl_owner;
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744

    /* we'll probably get a different bbox now, so we
       will calculate a new one the next time we call
       draw_getrect for this draw command. For groups
       we need to do it for all of the draw commands.
    */
    if (x->x_drawtype == gensym("group"))
        draw_group_pathrect_cache(x, 0);
    else if (x->x_pathrect_cache != -1)
        x->x_pathrect_cache = 0;
    for (g = c->gl_list; g; g = g->g_next)
    {
        if (glist_isvisible(c) && g->g_pd == scalar_class &&
            x->x_canvas ==
            template_findcanvas((template = template_findbyname(
                (((t_scalar *)g)->sc_template))))
           )
        {
            t_float m1, m2, m3, m4, m5, m6;
            draw_parsetransform(x, template, ((t_scalar *)g)->sc_vec,
                &m1, &m2, &m3, &m4, &m5, &m6);
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
            if (x->x_drawtype == gensym("group"))
                sys_vgui(".x%lx.c itemconfigure .dgroup%lx -matrix "
                    "{ {%g %g} {%g %g} {%g %g} }\n",
                    visible, ((t_scalar *)g)->sc_vec, m1, m2, m3, m4, m5, m6);
            else
                sys_vgui(".x%lx.c itemconfigure .draw%lx.%lx -matrix "
                    "{ {%g %g} {%g %g} {%g %g} }\n",
                    visible, x, ((t_scalar*)g)->sc_vec,
                    m1, m2, m3, m4, m5, m6);
            /* uncache the scalar's bbox */
            ((t_scalar *)g)->sc_bboxcache = 0;
            if (glist_isselected(c, &((t_scalar *)g)->sc_gobj))
            {
1758
                //scalar_select(g, c, 1);
1759
1760
1761
                scalar_drawselectrect((t_scalar *)g, c, 0);
                scalar_drawselectrect((t_scalar *)g, c, 1);
            }
1762
            sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", visible);
1763
        }
1764
1765
        if (g->g_pd == canvas_class)
        {
1766
            draw_doupdatetransform(x, (t_glist *)g);
1767
        }
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
    }
}

void draw_queueupdatetransform(t_gobj *g, t_glist *glist)
{
    t_draw *x = (t_draw *)g;
    draw_doupdatetransform(x, glist);
}

extern t_canvas *canvas_list;
void draw_updatetransform(t_draw *x)
{
    t_canvas *c;
    int i;
    for (c = canvas_list; c; c = c->gl_next)
        draw_doupdatetransform(x, c);
    /* Attempted to use sys_queuegui above, but
       it actually ended up being slightly less
       efficient. Maybe I was using it wrong...
       sys_queuegui((t_gobj *)x, c, draw_queueupdatetransform);
    */
}

void draw_transform(t_draw *x, t_symbol *s, int argc, t_atom *argv)
{
    /* probably need to do error checking here */
    t_fielddesc *fd;
    x->x_transform = (t_fielddesc *)t_resizebytes(x->x_transform,
        x->x_ndash * sizeof(*x->x_transform), argc * sizeof(*x->x_transform));
    x->x_transform_n = argc;
    fd = x->x_transform;
    while (argc)
    {
        if (argv->a_type == A_SYMBOL
            && (argv->a_w.w_symbol == gensym("translate")
                || argv->a_w.w_symbol == gensym("rotate")
                || argv->a_w.w_symbol == gensym("scale")
                || argv->a_w.w_symbol == gensym("skewx")
                || argv->a_w.w_symbol == gensym("skewy")))
        {
            fielddesc_setsymbolarg(fd++, argc--, argv++);
        }
        else
        {
            if (argv->a_type == A_SYMBOL &&
                x->x_drawtype == gensym("path"))
                    x->x_pathrect_cache = -1;
            fielddesc_setfloatarg(fd++, argc--, argv++);
        }
    }
    draw_updatetransform(x);
}

/* -------------------- widget behavior for draw ------------ */

/* from Raphael.js lib */
static void draw_q2c(t_float x1, t_float y1, t_float *cx1, t_float *cy1,
    t_float *cx2, t_float *cy2, t_float *cx, t_float *cy)
{
    t_float _13 = 1.0 / 3.0;
    t_float _23 = 2.0 / 3.0;
    t_float ax = *cx1, ay = *cy1, x2 = *cx2, y2 = *cy2;

    *cx1 = _13 * x1 + _23 * ax;
    *cy1 = _13 * y1 + _23 * ay;
    *cx2 = _13 * x2 + _23 * ax;
    *cy2 = _13 * y2 + _23 * ay;
    *cx = x2;
    *cy = y2;
}

/* from Raphael.js lib */
static void draw_findDotAtSegment(t_float p1x, t_float p1y,
    t_float c1x, t_float c1y, t_float c2x, t_float c2y,
    t_float p2x, t_float p2y, t_float t, t_float *dotx, t_float *doty)
{
    t_float t1 = 1 - t;
    *dotx = pow(t1, 3) * p1x +
        pow(t1, 2) * 3 * t * c1x +
        t1 * 3 * t * t * c2x +
        pow(t, 3) * p2x;
    *doty = pow(t1, 3) * p1y +
        pow(t1, 2) * 3 * t * c1y +
        t1 * 3 * t * t * c2y +
        pow(t, 3) * p2y;
}

/* from Raphael.js lib */
static void draw_curvedim(t_float p1x, t_float p1y,
    t_float c1x, t_float c1y, t_float c2x, t_float c2y,
    t_float p2x, t_float p2y, t_float *xmin, t_float *ymin,
    t_float *xmax, t_float *ymax, t_float mtx1[][3])
{
    t_float mtx2[3][3];
    int i;
    t_float a = (c2x - 2 * c1x + p1x) - (p2x - 2 * c2x + c1x);
    t_float        b = 2 * (c1x - p1x) - 2 * (c2x - c1x),
            c = p1x - c1x;
    t_float        syntax_sanity_check = 42,
            t1 = (a ? ((-b + sqrt(abs(b * b - 4 * a * c))) / 2.0 / a) : 0),
            t2 = (a ? ((-b - sqrt(abs(b * b - 4 * a * c))) / 2.0 / a) : 0);
    t_float xy[12];
    xy[0] = p1x; xy[1] = p1y; xy[2] = p2x; xy[3] = p2y;

1872
    /* mtx mult */
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
    draw_mset(mtx2, p1x, p1y, p2x, p2y, 0, 0);
    mtx2[2][0] = 1; mtx2[2][1] = 1;
    draw_mmult(mtx1, mtx2, mtx2);
    xy[0] = mtx2[0][0]; xy[1] = mtx2[1][0]; xy[2] = mtx2[0][1]; xy[3] = mtx2[1][1];
    int xyc = 4;
    t_float dotx, doty;
    t_float dot;
    if (abs(t1) > 1e12) t1 = 0.5;
    if (abs(t2) > 1e12) t2 = 0.5;
    if (t1 > 0 && t1 < 1)
    {
        draw_findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1, &dotx, &doty);
        draw_mset(mtx2, dotx, doty, 0, 0, 0, 0);
        mtx2[2][0] = 1;
        draw_mmult(mtx1, mtx2, mtx2);
        dotx = mtx2[0][0];
        doty = mtx2[1][0];
        xy[xyc++] = dotx;
        xy[xyc++] = doty;
    }
    if (t2 > 0 && t2 < 1)
    {
        draw_findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2, &dotx, &doty);
        draw_mset(mtx2, dotx, doty, 0, 0, 0, 0);
        mtx2[2][0] = 1;
        draw_mmult(mtx1, mtx2, mtx2);
        dotx = mtx2[0][0];
        doty = mtx2[1][0];
        xy[xyc++] = dotx;
        xy[xyc++] = doty;
    }
    a = (c2y - 2 * c1y + p1y) - (p2y - 2 * c2y + c1y);
    b = 2 * (c1y - p1y) - 2 * (c2y - c1y);
    c = p1y - c1y;
    t1 = (a ? ((-b + sqrt(abs(b * b - 4 * a * c))) / 2.0 / a) : 0);
    t2 = (a ? ((-b - sqrt(abs(b * b - 4 * a * c))) / 2.0 / a) : 0);
    if (abs(t1) > 1e12) t1 = 0.5;
    if (abs(t2) > 1e12) t2 = 0.5;
    if (t1 > 0 && t1 < 1)
    {
        draw_findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1, &dotx, &doty);
        draw_mset(mtx2, dotx, doty, 0, 0, 0, 0);
        mtx2[2][0] = 1;
        draw_mmult(mtx1, mtx2, mtx2);
        dotx = mtx2[0][0];
        doty = mtx2[1][0];
        xy[xyc++] = dotx;
        xy[xyc++] = doty;
    }
    if (t2 > 0 && t2 < 1)
    {
        draw_findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2, &dotx, &doty);
        draw_mset(mtx2, dotx, doty, 0, 0, 0, 0);
        mtx2[2][0] = 1;
        draw_mmult(mtx1, mtx2, mtx2);
        dotx = mtx2[0][0];
        doty = mtx2[1][0];
        xy[xyc++] = dotx;
        xy[xyc++] = doty;
    }

    *xmin = *ymin = 0x7fffffff;
    *xmax = *ymax = -0x7fffffff;
    for (i = 0; i < xyc; i+=2)
    {
        if (xy[i] < *xmin) *xmin = xy[i];
        if (xy[i] > *xmax) *xmax = xy[i];
        if (xy[i+1] < *ymin) *ymin = xy[i+1];
        if (xy[i+1] > *ymax) *ymax = xy[i+1];
    }
}

static t_float draw_getangle(t_float bx, t_float by)
{
  t_float pi = (t_float)3.14159265358979323846;
  t_float divisor = sqrt(bx * bx + by * by);
  return fmod(2*pi + (by > 0.0 ? 1.0 : -1.0) *
              acos( divisor? (bx / divisor) : 0 ), 2*pi);
}

void draw_arc2bbox(t_float x1, t_float y1, t_float rx, t_float ry,
   t_float phi, t_float large_arc, t_float sweep,
   t_float x2, t_float y2, t_float *xmin, t_float *ymin,
   t_float *xmax, t_float *ymax)
{
    t_float pi = (t_float)3.14159265358979323846;
    if (rx == 0 || ry == 0)
    {
        *xmin = (x1 < x2 ? x1 : x2);
        *xmax = (x1 > x2 ? x1 : x2);
        *ymin = (y1 < y2 ? y1 : y2);
        *ymax = (y1 > y2 ? y1 : y2);
        return;
    }
    if (rx < 0) rx *= -1;
    if (ry < 0) ry *= -1;
    const double x1prime = cos(phi)*(x1 - x2)/2 + sin(phi)*(y1 - y2)/2;
    const double y1prime = -sin(phi)*(x1 - x2)/2 + cos(phi)*(y1 - y2)/2;
1971
1972
    double radicant = (rx*rx*ry*ry - rx*rx*y1prime*y1prime -
        ry*ry*x1prime*x1prime);
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
    double divisor = (rx*rx*y1prime*y1prime + ry*ry*x1prime*x1prime);
    radicant = divisor ? radicant / divisor : 0;
    t_float cxprime = 0.0;
    t_float cyprime = 0.0;
    if (radicant < 0.0)
    {
        t_float ratio =  (ry ? rx/ry : 0);
        t_float radicant = y1prime*y1prime +
            (ratio ? x1prime*x1prime/(ratio*ratio) : 0);
        if (radicant < 0.0)
        {
            *xmin = (x1 < x2 ? x1 : x2);
            *xmax = (x1 > x2 ? x1 : x2);
            *ymin = (y1 < y2 ? y1 : y2);
            *ymax = (y1 > y2 ? y1 : y2);
            return;
        }
        ry = sqrt(radicant);
        rx = ratio * ry;
    }
    else
    {
        t_float factor = (large_arc==sweep ? -1.0 : 1.0)*sqrt(radicant);
        cxprime = factor*rx*y1prime/ry;
        cyprime = -factor*ry*x1prime/rx;
    }
    t_float cx = cxprime*cos(phi) - cyprime*sin(phi) + (x1 + x2)/2;
    t_float cy = cxprime*sin(phi) + cyprime*cos(phi) + (y1 + y2)/2;
    t_float txmin, txmax, tymin, tymax;
    if (phi == 0 || phi == pi)
    {
        *xmin = cx - rx;
        txmin = draw_getangle(-rx, 0);
        *xmax = cx + rx;
        txmax = draw_getangle(rx, 0);
        *ymin = cy - ry;
        tymin = draw_getangle(0, -ry);
        *ymax = cy + ry;
        tymax = draw_getangle(0, ry);
    }
    else if (phi == pi / 2.0 || phi == 3.0*pi/2.0)
    {
        *xmin = cx - ry;
        txmin = draw_getangle(-ry, 0);
        *xmax = cx + ry;
        txmax = draw_getangle(ry, 0);
        *ymin = cy - rx;
        tymin = draw_getangle(0, -rx);
        *ymax = cy + rx;
        tymax = draw_getangle(0, rx);
    }
    else
    {
        txmin = -atan(ry*tan(phi)/rx);
        txmax = pi - atan (ry*tan(phi)/rx);
        *xmin = cx + rx*cos(txmin)*cos(phi) - ry*sin(txmin)*sin(phi);
        *xmax = cx + rx*cos(txmax)*cos(phi) - ry*sin(txmax)*sin(phi);
        if (*xmin > *xmax)
        {
            t_float tmp = *xmax;
            *xmax = *xmin;
            *xmin = tmp;
            tmp = txmax;
            txmax = txmin;
            txmin = tmp;
        }
        t_float tmpY = cy + rx*cos(txmin)*sin(phi) + ry*sin(txmin)*cos(phi);
        txmin = draw_getangle(*xmin - cx, tmpY - cy);
        tmpY = cy + rx*cos(txmax)*sin(phi) + ry*sin(txmax)*cos(phi);
        txmax = draw_getangle(*xmax - cx, tmpY - cy);
        tymin = atan(ry/(tan(phi)*rx));
        tymax = atan(ry/(tan(phi)*rx))+pi;
        *ymin = cy + rx*cos(tymin)*sin(phi) + ry*sin(tymin)*cos(phi);
        *ymax = cy + rx*cos(tymax)*sin(phi) + ry*sin(tymax)*cos(phi);
        if (*ymin > *ymax)
        {
            t_float tmp = *ymax;
            *ymax = *ymin;
            *ymin = tmp;
            tmp = tymax;
            tymax = tymin;
            tymin = tmp;
        }
        t_float tmpX = cx + rx*cos(tymin)*cos(phi) - ry*sin(tymin)*sin(phi);
        tymin = draw_getangle(tmpX - cx, *ymin - cy);
        tmpX = cx + rx*cos(tymax)*cos(phi) - ry*sin(tymax)*sin(phi);
        tymax = draw_getangle(tmpX - cx, *ymax - cy);
    }
    t_float angle1 = draw_getangle(x1 - cx, y1 - cy);
    t_float angle2 = draw_getangle(x2 - cx, y2 - cy);
    if (!sweep)
    {
        t_float tmp = angle1;
        angle1 = angle2;
        angle2 = tmp;
    }
    int other_arc = 0;
    if (angle1 > angle2)
    {
        t_float tmp = angle1;
        angle1 = angle2;
        angle2 = tmp;
        other_arc = 1;
    }
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
    if ((!other_arc && (angle1 > txmin || angle2 < txmin)) ||
        (other_arc && !(angle1 > txmin || angle2 < txmin)))
        *xmin = x1 < x2 ? x1 : x2;
    if ((!other_arc && (angle1 > txmax || angle2 < txmax)) ||
        (other_arc && !(angle1 > txmax || angle2 < txmax)))
        *xmax = x1 > x2 ? x1 : x2;
    if ((!other_arc && (angle1 > tymin || angle2 < tymin))
        || (other_arc && !(angle1 > tymin || angle2 < tymin)))
        *ymin = y1 < y2 ? y1 : y2;
    if ((!other_arc && (angle1 > tymax || angle2 < tymax)) ||
        (other_arc && !(angle1 > tymax || angle2 < tymax)))
        *ymax = y1 > y2 ? y1 : y2;
}

    /* get bbox for a path, based very roughly on
       Raphael.js "pathbbox" function.  Too complex to finish
       here, but maybe this could eventually get merged in to
       tkpath-- it will probably give a more accurate result... */
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
static void draw_getpathrect(t_draw *x, t_glist *glist,
    t_word *data, t_template *template, t_float basex, t_float basey,
    int *xp1, int *yp1, int *xp2, int *yp2)
{
    /* todo: revisit the attr from Raphael for processPath. */ 

    t_float path2_vec[x->x_nargs];
    char path2cmds[x->x_npathcmds];
    t_float mtx1[3][3];
    t_float mtx2[3][3];
    t_float m1, m2, m3, m4, m5, m6;
    t_draw *dgroup = draw_getgroup(x);
    if (dgroup)
    {
        draw_parsetransform(dgroup, template, data, &m1, &m2, &m3,
            &m4, &m5, &m6);
        draw_mset(mtx1, m1, m2, m3, m4, m5, m6);
    }
    else
        draw_mset(mtx1, 1, 0, 0, 1, 0, 0);
    draw_parsetransform(x, template, data, &m1, &m2, &m3,
        &m4, &m5, &m6);
    draw_mset(mtx2, m1, m2, m3, m4, m5, m6);
    draw_mmult(mtx1, mtx2, mtx1);
    
    /* first let's get absolute path */

    /* check if we even have path data-- if not just return with
       some default bbox */
    /* to be filled in ... */ 
    t_float xx = 0, yy = 0, mx = 0, my = 0;
    int start = 0, tally = 0;
    if (x->x_pathcmds[0] == 'M' && x->x_nargs_per_cmd[0] == 2)
    {
        xx = fielddesc_getcoord(x->x_vec, template, data, 1);
        yy = fielddesc_getcoord((x->x_vec+1), template, data, 1);
        mx = xx;
        my = yy;
        start++;
        tally = 2;
        path2cmds[0] = 'M';
        path2_vec[0] = xx;
        path2_vec[1] = yy;
    }
    
2140
2141
2142
2143
    /* loop through and get absolute values. This is more
       complicated than it needs to be. If there were explicit
       single-letter cmds for each subset of path data then I
       could just use the default below for C, S, Q, T, and L. */
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
    int i = 0;
    for(i = start; i < x->x_npathcmds; i++)
    {
        int j;
        char cmd = x->x_pathcmds[i];
        t_float *ia = path2_vec+tally;
        t_fielddesc *fd = x->x_vec + tally;
        int rel = cmd > 96 && cmd < 123;
        if (rel) cmd -= 32;
        path2cmds[i] = cmd;
        switch (cmd)
        {
        case 'A':
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
            for (j = 0; j < x->x_nargs_per_cmd[i]; j += 7)
            {
                *ia = fielddesc_getcoord(fd, template, data, 1);
                *(ia+1) = fielddesc_getcoord(fd+1, template, data, 1);
                *(ia+2) = fielddesc_getfloat(fd+2, template, data, 1);
                *(ia+3) = fielddesc_getfloat(fd+3, template, data, 1);
                *(ia+4) = fielddesc_getfloat(fd+4, template, data, 1);
                xx = *(ia+5) = fielddesc_getcoord(fd+5, template, data, 1)
                    + (rel? xx : 0);
                yy = *(ia+6) = fielddesc_getcoord(fd+6, template, data, 1)
                    + (rel? yy : 0);
            }
2169
2170
            break;
        case 'V':
2171
2172
2173
            for (j = 0; j < x->x_nargs_per_cmd[i]; j++)
                yy = *ia = fielddesc_getcoord(fd, template, data, 1)
                    + (rel? yy : 0);
2174
2175
            break;
        case 'H':
2176
2177
2178
            for (j = 0; j < x->x_nargs_per_cmd[i]; j++)
                xx = *ia = fielddesc_getcoord(fd, template, data, 1)
                    + (rel? xx : 0);
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
            break;
        case 'L':
            for (j = 0; j < x->x_nargs_per_cmd[i]; j++)
            {
                if (j%2 == 0)
                    xx = *(ia+j) = fielddesc_getcoord(fd+j, template, data, 1)
                        + (rel? xx : 0);
                else
                    yy = *(ia+j) = fielddesc_getcoord(fd+j, template, data, 1)
                        + (rel? yy : 0);
            }      
            break;