Merge branch 'master' into blender2.8
[blender.git] / source / blender / blenkernel / intern / curve.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/curve.c
29  *  \ingroup bke
30  */
31
32
33 #include <math.h>  // floor
34 #include <string.h>
35 #include <stdlib.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "BLI_blenlib.h"
40 #include "BLI_math.h"
41 #include "BLI_utildefines.h"
42 #include "BLI_ghash.h"
43
44 #include "DNA_anim_types.h"
45 #include "DNA_curve_types.h"
46 #include "DNA_material_types.h"
47
48 /* for dereferencing pointers */
49 #include "DNA_key_types.h"
50 #include "DNA_scene_types.h"
51 #include "DNA_vfont_types.h"
52 #include "DNA_object_types.h"
53
54 #include "BKE_animsys.h"
55 #include "BKE_curve.h"
56 #include "BKE_displist.h"
57 #include "BKE_font.h"
58 #include "BKE_global.h"
59 #include "BKE_key.h"
60 #include "BKE_library.h"
61 #include "BKE_library_query.h"
62 #include "BKE_library_remap.h"
63 #include "BKE_main.h"
64 #include "BKE_object.h"
65 #include "BKE_material.h"
66
67 #include "DEG_depsgraph.h"
68
69 /* globals */
70
71 /* local */
72 static int cu_isectLL(const float v1[3], const float v2[3], const float v3[3], const float v4[3],
73                       short cox, short coy,
74                       float *lambda, float *mu, float vec[3]);
75
76 /* frees editcurve entirely */
77 void BKE_curve_editfont_free(Curve *cu)
78 {
79         if (cu->editfont) {
80                 EditFont *ef = cu->editfont;
81
82                 if (ef->textbuf)
83                         MEM_freeN(ef->textbuf);
84                 if (ef->textbufinfo)
85                         MEM_freeN(ef->textbufinfo);
86                 if (ef->selboxes)
87                         MEM_freeN(ef->selboxes);
88
89                 MEM_freeN(ef);
90                 cu->editfont = NULL;
91         }
92 }
93
94 static void curve_editNurb_keyIndex_cv_free_cb(void *val)
95 {
96         CVKeyIndex *index = val;
97         MEM_freeN(index->orig_cv);
98         MEM_freeN(val);
99 }
100
101 void BKE_curve_editNurb_keyIndex_delCV(GHash *keyindex, const void *cv)
102 {
103         BLI_assert(keyindex != NULL);
104         BLI_ghash_remove(keyindex, cv, NULL, curve_editNurb_keyIndex_cv_free_cb);
105 }
106
107 void BKE_curve_editNurb_keyIndex_free(GHash **keyindex)
108 {
109         if (!(*keyindex)) {
110                 return;
111         }
112         BLI_ghash_free(*keyindex, NULL, curve_editNurb_keyIndex_cv_free_cb);
113         *keyindex = NULL;
114 }
115
116 void BKE_curve_editNurb_free(Curve *cu)
117 {
118         if (cu->editnurb) {
119                 BKE_nurbList_free(&cu->editnurb->nurbs);
120                 BKE_curve_editNurb_keyIndex_free(&cu->editnurb->keyindex);
121                 MEM_freeN(cu->editnurb);
122                 cu->editnurb = NULL;
123         }
124 }
125
126 /** Free (or release) any data used by this curve (does not free the curve itself). */
127 void BKE_curve_free(Curve *cu)
128 {
129         BKE_animdata_free((ID *)cu, false);
130
131         BKE_curve_batch_cache_free(cu);
132
133         BKE_nurbList_free(&cu->nurb);
134         BKE_curve_editfont_free(cu);
135
136         BKE_curve_editNurb_free(cu);
137
138         MEM_SAFE_FREE(cu->mat);
139         MEM_SAFE_FREE(cu->str);
140         MEM_SAFE_FREE(cu->strinfo);
141         MEM_SAFE_FREE(cu->bb);
142         MEM_SAFE_FREE(cu->tb);
143 }
144
145 void BKE_curve_init(Curve *cu)
146 {
147         /* BLI_assert(MEMCMP_STRUCT_OFS_IS_ZERO(cu, id)); */  /* cu->type is already initialized... */
148
149         copy_v3_fl(cu->size, 1.0f);
150         cu->flag = CU_FRONT | CU_BACK | CU_DEFORM_BOUNDS_OFF | CU_PATH_RADIUS;
151         cu->pathlen = 100;
152         cu->resolu = cu->resolv = (cu->type == OB_SURF) ? 4 : 12;
153         cu->width = 1.0;
154         cu->wordspace = 1.0;
155         cu->spacing = cu->linedist = 1.0;
156         cu->fsize = 1.0;
157         cu->ulheight = 0.05;
158         cu->texflag = CU_AUTOSPACE;
159         cu->smallcaps_scale = 0.75f;
160         /* XXX: this one seems to be the best one in most cases, at least for curve deform... */
161         cu->twist_mode = CU_TWIST_MINIMUM;
162         cu->bevfac1 = 0.0f;
163         cu->bevfac2 = 1.0f;
164         cu->bevfac1_mapping = CU_BEVFAC_MAP_RESOLU;
165         cu->bevfac2_mapping = CU_BEVFAC_MAP_RESOLU;
166
167         cu->bb = BKE_boundbox_alloc_unit();
168
169         if (cu->type == OB_FONT) {
170                 cu->vfont = cu->vfontb = cu->vfonti = cu->vfontbi = BKE_vfont_builtin_get();
171                 cu->vfont->id.us += 4;
172                 cu->str = MEM_malloc_arrayN(12, sizeof(unsigned char), "str");
173                 BLI_strncpy(cu->str, "Text", 12);
174                 cu->len = cu->len_wchar = cu->pos = 4;
175                 cu->strinfo = MEM_calloc_arrayN(12, sizeof(CharInfo), "strinfo new");
176                 cu->totbox = cu->actbox = 1;
177                 cu->tb = MEM_calloc_arrayN(MAXTEXTBOX, sizeof(TextBox), "textbox");
178                 cu->tb[0].w = cu->tb[0].h = 0.0;
179         }
180 }
181
182 Curve *BKE_curve_add(Main *bmain, const char *name, int type)
183 {
184         Curve *cu;
185
186         cu = BKE_libblock_alloc(bmain, ID_CU, name, 0);
187         cu->type = type;
188
189         BKE_curve_init(cu);
190
191         return cu;
192 }
193
194 /**
195  * Only copy internal data of Curve ID from source to already allocated/initialized destination.
196  * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
197  *
198  * WARNING! This function will not handle ID user count!
199  *
200  * \param flag: Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
201  */
202 void BKE_curve_copy_data(Main *bmain, Curve *cu_dst, const Curve *cu_src, const int flag)
203 {
204         BLI_listbase_clear(&cu_dst->nurb);
205         BKE_nurbList_duplicate(&(cu_dst->nurb), &(cu_src->nurb));
206
207         cu_dst->mat = MEM_dupallocN(cu_src->mat);
208
209         cu_dst->str = MEM_dupallocN(cu_src->str);
210         cu_dst->strinfo = MEM_dupallocN(cu_src->strinfo);
211         cu_dst->tb = MEM_dupallocN(cu_src->tb);
212         cu_dst->bb = MEM_dupallocN(cu_src->bb);
213         cu_dst->batch_cache = NULL;
214
215         if (cu_src->key && (flag & LIB_ID_COPY_SHAPEKEY)) {
216                 BKE_id_copy_ex(bmain, &cu_src->key->id, (ID **)&cu_dst->key, flag, false);
217         }
218
219         cu_dst->editnurb = NULL;
220         cu_dst->editfont = NULL;
221 }
222
223 Curve *BKE_curve_copy(Main *bmain, const Curve *cu)
224 {
225         Curve *cu_copy;
226         BKE_id_copy_ex(bmain, &cu->id, (ID **)&cu_copy, LIB_ID_COPY_SHAPEKEY, false);
227         return cu_copy;
228 }
229
230 void BKE_curve_make_local(Main *bmain, Curve *cu, const bool lib_local)
231 {
232         BKE_id_make_local_generic(bmain, &cu->id, true, lib_local);
233 }
234
235 /* Get list of nurbs from editnurbs structure */
236 ListBase *BKE_curve_editNurbs_get(Curve *cu)
237 {
238         if (cu->editnurb) {
239                 return &cu->editnurb->nurbs;
240         }
241
242         return NULL;
243 }
244
245 short BKE_curve_type_get(Curve *cu)
246 {
247         Nurb *nu;
248         int type = cu->type;
249
250         if (cu->vfont) {
251                 return OB_FONT;
252         }
253
254         if (!cu->type) {
255                 type = OB_CURVE;
256
257                 for (nu = cu->nurb.first; nu; nu = nu->next) {
258                         if (nu->pntsv > 1) {
259                                 type = OB_SURF;
260                         }
261                 }
262         }
263
264         return type;
265 }
266
267 void BKE_curve_curve_dimension_update(Curve *cu)
268 {
269         ListBase *nurbs = BKE_curve_nurbs_get(cu);
270         Nurb *nu = nurbs->first;
271
272         if (cu->flag & CU_3D) {
273                 for (; nu; nu = nu->next) {
274                         nu->flag &= ~CU_2D;
275                 }
276         }
277         else {
278                 for (; nu; nu = nu->next) {
279                         nu->flag |= CU_2D;
280                         BKE_nurb_test_2d(nu);
281
282                         /* since the handles are moved they need to be auto-located again */
283                         if (nu->type == CU_BEZIER)
284                                 BKE_nurb_handles_calc(nu);
285                 }
286         }
287 }
288
289 void BKE_curve_type_test(Object *ob)
290 {
291         ob->type = BKE_curve_type_get(ob->data);
292
293         if (ob->type == OB_CURVE)
294                 BKE_curve_curve_dimension_update((Curve *)ob->data);
295 }
296
297 void BKE_curve_boundbox_calc(Curve *cu, float r_loc[3], float r_size[3])
298 {
299         BoundBox *bb;
300         float min[3], max[3];
301         float mloc[3], msize[3];
302
303         if (cu->bb == NULL) cu->bb = MEM_callocN(sizeof(BoundBox), "boundbox");
304         bb = cu->bb;
305
306         if (!r_loc) r_loc = mloc;
307         if (!r_size) r_size = msize;
308
309         INIT_MINMAX(min, max);
310         if (!BKE_curve_minmax(cu, true, min, max)) {
311                 min[0] = min[1] = min[2] = -1.0f;
312                 max[0] = max[1] = max[2] = 1.0f;
313         }
314
315         mid_v3_v3v3(r_loc, min, max);
316
317         r_size[0] = (max[0] - min[0]) / 2.0f;
318         r_size[1] = (max[1] - min[1]) / 2.0f;
319         r_size[2] = (max[2] - min[2]) / 2.0f;
320
321         BKE_boundbox_init_from_minmax(bb, min, max);
322
323         bb->flag &= ~BOUNDBOX_DIRTY;
324 }
325
326 BoundBox *BKE_curve_boundbox_get(Object *ob)
327 {
328         /* This is Object-level data access, DO NOT touch to Mesh's bb, would be totally thread-unsafe. */
329         if (ob->bb == NULL || ob->bb->flag & BOUNDBOX_DIRTY) {
330                 Curve *cu = ob->data;
331                 float min[3], max[3];
332
333                 INIT_MINMAX(min, max);
334                 BKE_curve_minmax(cu, true, min, max);
335
336                 if (ob->bb == NULL) {
337                         ob->bb = MEM_mallocN(sizeof(*ob->bb), __func__);
338                 }
339                 BKE_boundbox_init_from_minmax(ob->bb, min, max);
340                 ob->bb->flag &= ~BOUNDBOX_DIRTY;
341         }
342
343         return ob->bb;
344 }
345
346 void BKE_curve_texspace_calc(Curve *cu)
347 {
348         float loc[3], size[3];
349         int a;
350
351         BKE_curve_boundbox_calc(cu, loc, size);
352
353         if (cu->texflag & CU_AUTOSPACE) {
354                 for (a = 0; a < 3; a++) {
355                         if (size[a] == 0.0f) size[a] = 1.0f;
356                         else if (size[a] > 0.0f && size[a] < 0.00001f) size[a] = 0.00001f;
357                         else if (size[a] < 0.0f && size[a] > -0.00001f) size[a] = -0.00001f;
358                 }
359
360                 copy_v3_v3(cu->loc, loc);
361                 copy_v3_v3(cu->size, size);
362                 zero_v3(cu->rot);
363         }
364 }
365
366 BoundBox *BKE_curve_texspace_get(Curve *cu, float r_loc[3], float r_rot[3], float r_size[3])
367 {
368         if (cu->bb == NULL || (cu->bb->flag & BOUNDBOX_DIRTY)) {
369                 BKE_curve_texspace_calc(cu);
370         }
371
372         if (r_loc) copy_v3_v3(r_loc,  cu->loc);
373         if (r_rot) copy_v3_v3(r_rot,  cu->rot);
374         if (r_size) copy_v3_v3(r_size, cu->size);
375
376         return cu->bb;
377 }
378
379 bool BKE_nurbList_index_get_co(ListBase *nurb, const int index, float r_co[3])
380 {
381         Nurb *nu;
382         int tot = 0;
383
384         for (nu = nurb->first; nu; nu = nu->next) {
385                 int tot_nu;
386                 if (nu->type == CU_BEZIER) {
387                         tot_nu = nu->pntsu;
388                         if (index - tot < tot_nu) {
389                                 copy_v3_v3(r_co, nu->bezt[index - tot].vec[1]);
390                                 return true;
391                         }
392                 }
393                 else {
394                         tot_nu = nu->pntsu * nu->pntsv;
395                         if (index - tot < tot_nu) {
396                                 copy_v3_v3(r_co, nu->bp[index - tot].vec);
397                                 return true;
398                         }
399                 }
400                 tot += tot_nu;
401         }
402
403         return false;
404 }
405
406 int BKE_nurbList_verts_count(ListBase *nurb)
407 {
408         Nurb *nu;
409         int tot = 0;
410
411         nu = nurb->first;
412         while (nu) {
413                 if (nu->bezt)
414                         tot += 3 * nu->pntsu;
415                 else if (nu->bp)
416                         tot += nu->pntsu * nu->pntsv;
417
418                 nu = nu->next;
419         }
420         return tot;
421 }
422
423 int BKE_nurbList_verts_count_without_handles(ListBase *nurb)
424 {
425         Nurb *nu;
426         int tot = 0;
427
428         nu = nurb->first;
429         while (nu) {
430                 if (nu->bezt)
431                         tot += nu->pntsu;
432                 else if (nu->bp)
433                         tot += nu->pntsu * nu->pntsv;
434
435                 nu = nu->next;
436         }
437         return tot;
438 }
439
440 /* **************** NURBS ROUTINES ******************** */
441
442 void BKE_nurb_free(Nurb *nu)
443 {
444
445         if (nu == NULL) return;
446
447         if (nu->bezt)
448                 MEM_freeN(nu->bezt);
449         nu->bezt = NULL;
450         if (nu->bp)
451                 MEM_freeN(nu->bp);
452         nu->bp = NULL;
453         if (nu->knotsu)
454                 MEM_freeN(nu->knotsu);
455         nu->knotsu = NULL;
456         if (nu->knotsv)
457                 MEM_freeN(nu->knotsv);
458         nu->knotsv = NULL;
459         /* if (nu->trim.first) freeNurblist(&(nu->trim)); */
460
461         MEM_freeN(nu);
462
463 }
464
465
466 void BKE_nurbList_free(ListBase *lb)
467 {
468         Nurb *nu, *next;
469
470         if (lb == NULL) return;
471
472         nu = lb->first;
473         while (nu) {
474                 next = nu->next;
475                 BKE_nurb_free(nu);
476                 nu = next;
477         }
478         BLI_listbase_clear(lb);
479 }
480
481 Nurb *BKE_nurb_duplicate(const Nurb *nu)
482 {
483         Nurb *newnu;
484         int len;
485
486         newnu = (Nurb *)MEM_mallocN(sizeof(Nurb), "duplicateNurb");
487         if (newnu == NULL) return NULL;
488         memcpy(newnu, nu, sizeof(Nurb));
489
490         if (nu->bezt) {
491                 newnu->bezt =
492                     (BezTriple *)MEM_malloc_arrayN(nu->pntsu, sizeof(BezTriple), "duplicateNurb2");
493                 memcpy(newnu->bezt, nu->bezt, nu->pntsu * sizeof(BezTriple));
494         }
495         else {
496                 len = nu->pntsu * nu->pntsv;
497                 newnu->bp =
498                     (BPoint *)MEM_malloc_arrayN(len, sizeof(BPoint), "duplicateNurb3");
499                 memcpy(newnu->bp, nu->bp, len * sizeof(BPoint));
500
501                 newnu->knotsu = newnu->knotsv = NULL;
502
503                 if (nu->knotsu) {
504                         len = KNOTSU(nu);
505                         if (len) {
506                                 newnu->knotsu = MEM_malloc_arrayN(len, sizeof(float), "duplicateNurb4");
507                                 memcpy(newnu->knotsu, nu->knotsu, sizeof(float) * len);
508                         }
509                 }
510                 if (nu->pntsv > 1 && nu->knotsv) {
511                         len = KNOTSV(nu);
512                         if (len) {
513                                 newnu->knotsv = MEM_malloc_arrayN(len, sizeof(float), "duplicateNurb5");
514                                 memcpy(newnu->knotsv, nu->knotsv, sizeof(float) * len);
515                         }
516                 }
517         }
518         return newnu;
519 }
520
521 /* copy the nurb but allow for different number of points (to be copied after this) */
522 Nurb *BKE_nurb_copy(Nurb *src, int pntsu, int pntsv)
523 {
524         Nurb *newnu = (Nurb *)MEM_mallocN(sizeof(Nurb), "copyNurb");
525         memcpy(newnu, src, sizeof(Nurb));
526
527         if (pntsu == 1) SWAP(int, pntsu, pntsv);
528         newnu->pntsu = pntsu;
529         newnu->pntsv = pntsv;
530
531         /* caller can manually handle these arrays */
532         newnu->knotsu = NULL;
533         newnu->knotsv = NULL;
534
535         if (src->bezt) {
536                 newnu->bezt = (BezTriple *)MEM_malloc_arrayN(pntsu * pntsv, sizeof(BezTriple), "copyNurb2");
537         }
538         else {
539                 newnu->bp = (BPoint *)MEM_malloc_arrayN(pntsu * pntsv, sizeof(BPoint), "copyNurb3");
540         }
541
542         return newnu;
543 }
544
545 void BKE_nurbList_duplicate(ListBase *lb1, const ListBase *lb2)
546 {
547         Nurb *nu, *nun;
548
549         BKE_nurbList_free(lb1);
550
551         nu = lb2->first;
552         while (nu) {
553                 nun = BKE_nurb_duplicate(nu);
554                 BLI_addtail(lb1, nun);
555
556                 nu = nu->next;
557         }
558 }
559
560 void BKE_nurb_test_2d(Nurb *nu)
561 {
562         BezTriple *bezt;
563         BPoint *bp;
564         int a;
565
566         if ((nu->flag & CU_2D) == 0)
567                 return;
568
569         if (nu->type == CU_BEZIER) {
570                 a = nu->pntsu;
571                 bezt = nu->bezt;
572                 while (a--) {
573                         bezt->vec[0][2] = 0.0;
574                         bezt->vec[1][2] = 0.0;
575                         bezt->vec[2][2] = 0.0;
576                         bezt++;
577                 }
578         }
579         else {
580                 a = nu->pntsu * nu->pntsv;
581                 bp = nu->bp;
582                 while (a--) {
583                         bp->vec[2] = 0.0;
584                         bp++;
585                 }
586         }
587 }
588
589 /**
590  * if use_radius is truth, minmax will take points' radius into account,
591  * which will make boundbox closer to beveled curve.
592  */
593 void BKE_nurb_minmax(Nurb *nu, bool use_radius, float min[3], float max[3])
594 {
595         BezTriple *bezt;
596         BPoint *bp;
597         int a;
598         float point[3];
599
600         if (nu->type == CU_BEZIER) {
601                 a = nu->pntsu;
602                 bezt = nu->bezt;
603                 while (a--) {
604                         if (use_radius) {
605                                 float radius_vector[3];
606                                 radius_vector[0] = radius_vector[1] = radius_vector[2] = bezt->radius;
607
608                                 add_v3_v3v3(point, bezt->vec[1], radius_vector);
609                                 minmax_v3v3_v3(min, max, point);
610
611                                 sub_v3_v3v3(point, bezt->vec[1], radius_vector);
612                                 minmax_v3v3_v3(min, max, point);
613                         }
614                         else {
615                                 minmax_v3v3_v3(min, max, bezt->vec[1]);
616                         }
617                         minmax_v3v3_v3(min, max, bezt->vec[0]);
618                         minmax_v3v3_v3(min, max, bezt->vec[2]);
619                         bezt++;
620                 }
621         }
622         else {
623                 a = nu->pntsu * nu->pntsv;
624                 bp = nu->bp;
625                 while (a--) {
626                         if (nu->pntsv == 1 && use_radius) {
627                                 float radius_vector[3];
628                                 radius_vector[0] = radius_vector[1] = radius_vector[2] = bp->radius;
629
630                                 add_v3_v3v3(point, bp->vec, radius_vector);
631                                 minmax_v3v3_v3(min, max, point);
632
633                                 sub_v3_v3v3(point, bp->vec, radius_vector);
634                                 minmax_v3v3_v3(min, max, point);
635                         }
636                         else {
637                                 /* Surfaces doesn't use bevel, so no need to take radius into account. */
638                                 minmax_v3v3_v3(min, max, bp->vec);
639                         }
640                         bp++;
641                 }
642         }
643 }
644
645 float BKE_nurb_calc_length(const Nurb *nu, int resolution)
646 {
647         BezTriple *bezt, *prevbezt;
648         BPoint *bp, *prevbp;
649         int a, b;
650         float length = 0.0f;
651         int resolu = resolution ? resolution : nu->resolu;
652         int pntsu = nu->pntsu;
653         float *points, *pntsit, *prevpntsit;
654
655         if (nu->type == CU_POLY) {
656                 a = nu->pntsu - 1;
657                 bp = nu->bp;
658                 if (nu->flagu & CU_NURB_CYCLIC) {
659                         ++a;
660                         prevbp = nu->bp + (nu->pntsu - 1);
661                 }
662                 else {
663                         prevbp = bp;
664                         bp++;
665                 }
666
667                 while (a--) {
668                         length += len_v3v3(prevbp->vec, bp->vec);
669                         prevbp = bp;
670                         ++bp;
671                 }
672         }
673         else if (nu->type == CU_BEZIER) {
674                 points = MEM_mallocN(sizeof(float[3]) * (resolu + 1), "getLength_bezier");
675                 a = nu->pntsu - 1;
676                 bezt = nu->bezt;
677                 if (nu->flagu & CU_NURB_CYCLIC) {
678                         ++a;
679                         prevbezt = nu->bezt + (nu->pntsu - 1);
680                 }
681                 else {
682                         prevbezt = bezt;
683                         ++bezt;
684                 }
685
686                 while (a--) {
687                         if (prevbezt->h2 == HD_VECT && bezt->h1 == HD_VECT) {
688                                 length += len_v3v3(prevbezt->vec[1], bezt->vec[1]);
689                         }
690                         else {
691                                 for (int j = 0; j < 3; j++) {
692                                         BKE_curve_forward_diff_bezier(
693                                                 prevbezt->vec[1][j], prevbezt->vec[2][j],
694                                                 bezt->vec[0][j], bezt->vec[1][j],
695                                                 points + j, resolu, 3 * sizeof(float));
696                                 }
697
698                                 prevpntsit = pntsit = points;
699                                 b = resolu;
700                                 while (b--) {
701                                         pntsit += 3;
702                                         length += len_v3v3(prevpntsit, pntsit);
703                                         prevpntsit = pntsit;
704                                 }
705                         }
706                         prevbezt = bezt;
707                         ++bezt;
708                 }
709
710                 MEM_freeN(points);
711         }
712         else if (nu->type == CU_NURBS) {
713                 if (nu->pntsv == 1) {
714                         /* important to zero for BKE_nurb_makeCurve. */
715                         points = MEM_callocN(sizeof(float[3]) * pntsu * resolu, "getLength_nurbs");
716
717                         BKE_nurb_makeCurve(
718                                 nu, points,
719                                 NULL, NULL, NULL,
720                                 resolu, sizeof(float[3]));
721
722                         if (nu->flagu & CU_NURB_CYCLIC) {
723                                 b = pntsu * resolu + 1;
724                                 prevpntsit = points + 3 * (pntsu * resolu - 1);
725                                 pntsit = points;
726                         }
727                         else {
728                                 b = (pntsu - 1) * resolu;
729                                 prevpntsit = points;
730                                 pntsit = points + 3;
731                         }
732
733                         while (--b) {
734                                 length += len_v3v3(prevpntsit, pntsit);
735                                 prevpntsit = pntsit;
736                                 pntsit += 3;
737                         }
738
739                         MEM_freeN(points);
740                 }
741         }
742
743         return length;
744 }
745
746 /* be sure to call makeknots after this */
747 void BKE_nurb_points_add(Nurb *nu, int number)
748 {
749         BPoint *bp;
750         int i;
751
752         nu->bp = MEM_recallocN(nu->bp, (nu->pntsu + number) * sizeof(BPoint));
753
754         for (i = 0, bp = &nu->bp[nu->pntsu]; i < number; i++, bp++) {
755                 bp->radius = 1.0f;
756         }
757
758         nu->pntsu += number;
759 }
760
761 void BKE_nurb_bezierPoints_add(Nurb *nu, int number)
762 {
763         BezTriple *bezt;
764         int i;
765
766         nu->bezt = MEM_recallocN(nu->bezt, (nu->pntsu + number) * sizeof(BezTriple));
767
768         for (i = 0, bezt = &nu->bezt[nu->pntsu]; i < number; i++, bezt++) {
769                 bezt->radius = 1.0f;
770         }
771
772         nu->pntsu += number;
773 }
774
775
776 int BKE_nurb_index_from_uv(
777         Nurb *nu,
778         int u, int v)
779 {
780         const int totu = nu->pntsu;
781         const int totv = nu->pntsv;
782
783         if (nu->flagu & CU_NURB_CYCLIC) {
784                 u = mod_i(u, totu);
785         }
786         else if (u < 0 || u >= totu) {
787                 return -1;
788         }
789
790         if (nu->flagv & CU_NURB_CYCLIC) {
791                 v = mod_i(v, totv);
792         }
793         else if (v < 0 || v >= totv) {
794                 return -1;
795         }
796
797         return (v * totu) + u;
798 }
799
800 void BKE_nurb_index_to_uv(
801         Nurb *nu, int index,
802         int *r_u, int *r_v)
803 {
804         const int totu = nu->pntsu;
805         const int totv = nu->pntsv;
806         BLI_assert(index >= 0 && index < (nu->pntsu * nu->pntsv));
807         *r_u = (index % totu);
808         *r_v = (index / totu) % totv;
809 }
810
811 BezTriple *BKE_nurb_bezt_get_next(Nurb *nu, BezTriple *bezt)
812 {
813         BezTriple *bezt_next;
814
815         BLI_assert(ARRAY_HAS_ITEM(bezt, nu->bezt, nu->pntsu));
816
817         if (bezt == &nu->bezt[nu->pntsu - 1]) {
818                 if (nu->flagu & CU_NURB_CYCLIC) {
819                         bezt_next = nu->bezt;
820                 }
821                 else {
822                         bezt_next = NULL;
823                 }
824         }
825         else {
826                 bezt_next = bezt + 1;
827         }
828
829         return bezt_next;
830 }
831
832 BPoint *BKE_nurb_bpoint_get_next(Nurb *nu, BPoint *bp)
833 {
834         BPoint *bp_next;
835
836         BLI_assert(ARRAY_HAS_ITEM(bp, nu->bp, nu->pntsu));
837
838         if (bp == &nu->bp[nu->pntsu - 1]) {
839                 if (nu->flagu & CU_NURB_CYCLIC) {
840                         bp_next = nu->bp;
841                 }
842                 else {
843                         bp_next = NULL;
844                 }
845         }
846         else {
847                 bp_next = bp + 1;
848         }
849
850         return bp_next;
851 }
852
853 BezTriple *BKE_nurb_bezt_get_prev(Nurb *nu, BezTriple *bezt)
854 {
855         BezTriple *bezt_prev;
856
857         BLI_assert(ARRAY_HAS_ITEM(bezt, nu->bezt, nu->pntsu));
858         BLI_assert(nu->pntsv <= 1);
859
860         if (bezt == nu->bezt) {
861                 if (nu->flagu & CU_NURB_CYCLIC) {
862                         bezt_prev = &nu->bezt[nu->pntsu - 1];
863                 }
864                 else {
865                         bezt_prev = NULL;
866                 }
867         }
868         else {
869                 bezt_prev = bezt - 1;
870         }
871
872         return bezt_prev;
873 }
874
875 BPoint *BKE_nurb_bpoint_get_prev(Nurb *nu, BPoint *bp)
876 {
877         BPoint *bp_prev;
878
879         BLI_assert(ARRAY_HAS_ITEM(bp, nu->bp, nu->pntsu));
880         BLI_assert(nu->pntsv == 1);
881
882         if (bp == nu->bp) {
883                 if (nu->flagu & CU_NURB_CYCLIC) {
884                         bp_prev = &nu->bp[nu->pntsu - 1];
885                 }
886                 else {
887                         bp_prev = NULL;
888                 }
889         }
890         else {
891                 bp_prev = bp - 1;
892         }
893
894         return bp_prev;
895 }
896
897 void BKE_nurb_bezt_calc_normal(struct Nurb *UNUSED(nu), BezTriple *bezt, float r_normal[3])
898 {
899         /* calculate the axis matrix from the spline */
900         float dir_prev[3], dir_next[3];
901
902         sub_v3_v3v3(dir_prev, bezt->vec[0], bezt->vec[1]);
903         sub_v3_v3v3(dir_next, bezt->vec[1], bezt->vec[2]);
904
905         normalize_v3(dir_prev);
906         normalize_v3(dir_next);
907
908         add_v3_v3v3(r_normal, dir_prev, dir_next);
909         normalize_v3(r_normal);
910 }
911
912 void BKE_nurb_bezt_calc_plane(struct Nurb *nu, BezTriple *bezt, float r_plane[3])
913 {
914         float dir_prev[3], dir_next[3];
915
916         sub_v3_v3v3(dir_prev, bezt->vec[0], bezt->vec[1]);
917         sub_v3_v3v3(dir_next, bezt->vec[1], bezt->vec[2]);
918
919         normalize_v3(dir_prev);
920         normalize_v3(dir_next);
921
922         cross_v3_v3v3(r_plane, dir_prev, dir_next);
923         if (normalize_v3(r_plane) < FLT_EPSILON) {
924                 BezTriple *bezt_prev = BKE_nurb_bezt_get_prev(nu, bezt);
925                 BezTriple *bezt_next = BKE_nurb_bezt_get_next(nu, bezt);
926
927                 if (bezt_prev) {
928                         sub_v3_v3v3(dir_prev, bezt_prev->vec[1], bezt->vec[1]);
929                         normalize_v3(dir_prev);
930                 }
931                 if (bezt_next) {
932                         sub_v3_v3v3(dir_next, bezt->vec[1], bezt_next->vec[1]);
933                         normalize_v3(dir_next);
934                 }
935                 cross_v3_v3v3(r_plane, dir_prev, dir_next);
936         }
937
938         /* matches with bones more closely */
939         {
940                 float dir_mid[3], tvec[3];
941                 add_v3_v3v3(dir_mid, dir_prev, dir_next);
942                 cross_v3_v3v3(tvec, r_plane, dir_mid);
943                 copy_v3_v3(r_plane, tvec);
944         }
945
946         normalize_v3(r_plane);
947 }
948
949 void BKE_nurb_bpoint_calc_normal(struct Nurb *nu, BPoint *bp, float r_normal[3])
950 {
951         BPoint *bp_prev = BKE_nurb_bpoint_get_prev(nu, bp);
952         BPoint *bp_next = BKE_nurb_bpoint_get_next(nu, bp);
953
954         zero_v3(r_normal);
955
956         if (bp_prev) {
957                 float dir_prev[3];
958                 sub_v3_v3v3(dir_prev, bp_prev->vec, bp->vec);
959                 normalize_v3(dir_prev);
960                 add_v3_v3(r_normal, dir_prev);
961         }
962         if (bp_next) {
963                 float dir_next[3];
964                 sub_v3_v3v3(dir_next, bp->vec, bp_next->vec);
965                 normalize_v3(dir_next);
966                 add_v3_v3(r_normal, dir_next);
967         }
968
969         normalize_v3(r_normal);
970 }
971
972 void BKE_nurb_bpoint_calc_plane(struct Nurb *nu, BPoint *bp, float r_plane[3])
973 {
974         BPoint *bp_prev = BKE_nurb_bpoint_get_prev(nu, bp);
975         BPoint *bp_next = BKE_nurb_bpoint_get_next(nu, bp);
976
977         float dir_prev[3] = {0.0f}, dir_next[3] = {0.0f};
978
979         if (bp_prev) {
980                 sub_v3_v3v3(dir_prev, bp_prev->vec, bp->vec);
981                 normalize_v3(dir_prev);
982         }
983         if (bp_next) {
984                 sub_v3_v3v3(dir_next, bp->vec, bp_next->vec);
985                 normalize_v3(dir_next);
986         }
987         cross_v3_v3v3(r_plane, dir_prev, dir_next);
988
989         /* matches with bones more closely */
990         {
991                 float dir_mid[3], tvec[3];
992                 add_v3_v3v3(dir_mid, dir_prev, dir_next);
993                 cross_v3_v3v3(tvec, r_plane, dir_mid);
994                 copy_v3_v3(r_plane, tvec);
995         }
996
997         normalize_v3(r_plane);
998 }
999
1000 /* ~~~~~~~~~~~~~~~~~~~~Non Uniform Rational B Spline calculations ~~~~~~~~~~~ */
1001
1002
1003 static void calcknots(float *knots, const int pnts, const short order, const short flag)
1004 {
1005         /* knots: number of pnts NOT corrected for cyclic */
1006         const int pnts_order = pnts + order;
1007         float k;
1008         int a;
1009
1010         switch (flag & (CU_NURB_ENDPOINT | CU_NURB_BEZIER)) {
1011                 case CU_NURB_ENDPOINT:
1012                         k = 0.0;
1013                         for (a = 1; a <= pnts_order; a++) {
1014                                 knots[a - 1] = k;
1015                                 if (a >= order && a <= pnts)
1016                                         k += 1.0f;
1017                         }
1018                         break;
1019                 case CU_NURB_BEZIER:
1020                         /* Warning, the order MUST be 2 or 4,
1021                          * if this is not enforced, the displist will be corrupt */
1022                         if (order == 4) {
1023                                 k = 0.34;
1024                                 for (a = 0; a < pnts_order; a++) {
1025                                         knots[a] = floorf(k);
1026                                         k += (1.0f / 3.0f);
1027                                 }
1028                         }
1029                         else if (order == 3) {
1030                                 k = 0.6f;
1031                                 for (a = 0; a < pnts_order; a++) {
1032                                         if (a >= order && a <= pnts)
1033                                                 k += 0.5f;
1034                                         knots[a] = floorf(k);
1035                                 }
1036                         }
1037                         else {
1038                                 printf("bez nurb curve order is not 3 or 4, should never happen\n");
1039                         }
1040                         break;
1041                 default:
1042                         for (a = 0; a < pnts_order; a++) {
1043                                 knots[a] = (float)a;
1044                         }
1045                         break;
1046         }
1047 }
1048
1049 static void makecyclicknots(float *knots, int pnts, short order)
1050 /* pnts, order: number of pnts NOT corrected for cyclic */
1051 {
1052         int a, b, order2, c;
1053
1054         if (knots == NULL)
1055                 return;
1056
1057         order2 = order - 1;
1058
1059         /* do first long rows (order -1), remove identical knots at endpoints */
1060         if (order > 2) {
1061                 b = pnts + order2;
1062                 for (a = 1; a < order2; a++) {
1063                         if (knots[b] != knots[b - a])
1064                                 break;
1065                 }
1066                 if (a == order2)
1067                         knots[pnts + order - 2] += 1.0f;
1068         }
1069
1070         b = order;
1071         c = pnts + order + order2;
1072         for (a = pnts + order2; a < c; a++) {
1073                 knots[a] = knots[a - 1] + (knots[b] - knots[b - 1]);
1074                 b--;
1075         }
1076 }
1077
1078
1079
1080 static void makeknots(Nurb *nu, short uv)
1081 {
1082         if (nu->type == CU_NURBS) {
1083                 if (uv == 1) {
1084                         if (nu->knotsu)
1085                                 MEM_freeN(nu->knotsu);
1086                         if (BKE_nurb_check_valid_u(nu)) {
1087                                 nu->knotsu = MEM_calloc_arrayN(KNOTSU(nu) + 1, sizeof(float), "makeknots");
1088                                 if (nu->flagu & CU_NURB_CYCLIC) {
1089                                         calcknots(nu->knotsu, nu->pntsu, nu->orderu, 0);  /* cyclic should be uniform */
1090                                         makecyclicknots(nu->knotsu, nu->pntsu, nu->orderu);
1091                                 }
1092                                 else {
1093                                         calcknots(nu->knotsu, nu->pntsu, nu->orderu, nu->flagu);
1094                                 }
1095                         }
1096                         else
1097                                 nu->knotsu = NULL;
1098                 }
1099                 else if (uv == 2) {
1100                         if (nu->knotsv)
1101                                 MEM_freeN(nu->knotsv);
1102                         if (BKE_nurb_check_valid_v(nu)) {
1103                                 nu->knotsv = MEM_calloc_arrayN(KNOTSV(nu) + 1, sizeof(float), "makeknots");
1104                                 if (nu->flagv & CU_NURB_CYCLIC) {
1105                                         calcknots(nu->knotsv, nu->pntsv, nu->orderv, 0);  /* cyclic should be uniform */
1106                                         makecyclicknots(nu->knotsv, nu->pntsv, nu->orderv);
1107                                 }
1108                                 else {
1109                                         calcknots(nu->knotsv, nu->pntsv, nu->orderv, nu->flagv);
1110                                 }
1111                         }
1112                         else {
1113                                 nu->knotsv = NULL;
1114                         }
1115                 }
1116         }
1117 }
1118
1119 void BKE_nurb_knot_calc_u(Nurb *nu)
1120 {
1121         makeknots(nu, 1);
1122 }
1123
1124 void BKE_nurb_knot_calc_v(Nurb *nu)
1125 {
1126         makeknots(nu, 2);
1127 }
1128
1129 static void basisNurb(float t, short order, int pnts, float *knots, float *basis, int *start, int *end)
1130 {
1131         float d, e;
1132         int i, i1 = 0, i2 = 0, j, orderpluspnts, opp2, o2;
1133
1134         orderpluspnts = order + pnts;
1135         opp2 = orderpluspnts - 1;
1136
1137         /* this is for float inaccuracy */
1138         if (t < knots[0])
1139                 t = knots[0];
1140         else if (t > knots[opp2])
1141                 t = knots[opp2];
1142
1143         /* this part is order '1' */
1144         o2 = order + 1;
1145         for (i = 0; i < opp2; i++) {
1146                 if (knots[i] != knots[i + 1] && t >= knots[i] && t <= knots[i + 1]) {
1147                         basis[i] = 1.0;
1148                         i1 = i - o2;
1149                         if (i1 < 0) i1 = 0;
1150                         i2 = i;
1151                         i++;
1152                         while (i < opp2) {
1153                                 basis[i] = 0.0;
1154                                 i++;
1155                         }
1156                         break;
1157                 }
1158                 else
1159                         basis[i] = 0.0;
1160         }
1161         basis[i] = 0.0;
1162
1163         /* this is order 2, 3, ... */
1164         for (j = 2; j <= order; j++) {
1165
1166                 if (i2 + j >= orderpluspnts) i2 = opp2 - j;
1167
1168                 for (i = i1; i <= i2; i++) {
1169                         if (basis[i] != 0.0f)
1170                                 d = ((t - knots[i]) * basis[i]) / (knots[i + j - 1] - knots[i]);
1171                         else
1172                                 d = 0.0f;
1173
1174                         if (basis[i + 1] != 0.0f)
1175                                 e = ((knots[i + j] - t) * basis[i + 1]) / (knots[i + j] - knots[i + 1]);
1176                         else
1177                                 e = 0.0;
1178
1179                         basis[i] = d + e;
1180                 }
1181         }
1182
1183         *start = 1000;
1184         *end = 0;
1185
1186         for (i = i1; i <= i2; i++) {
1187                 if (basis[i] > 0.0f) {
1188                         *end = i;
1189                         if (*start == 1000) *start = i;
1190                 }
1191         }
1192 }
1193
1194 /**
1195  * \param coord_array: has to be (3 * 4 * resolu * resolv) in size, and zero-ed.
1196  */
1197 void BKE_nurb_makeFaces(const Nurb *nu, float *coord_array, int rowstride, int resolu, int resolv)
1198 {
1199         BPoint *bp;
1200         float *basisu, *basis, *basisv, *sum, *fp, *in;
1201         float u, v, ustart, uend, ustep, vstart, vend, vstep, sumdiv;
1202         int i, j, iofs, jofs, cycl, len, curu, curv;
1203         int istart, iend, jsta, jen, *jstart, *jend, ratcomp;
1204
1205         int totu = nu->pntsu * resolu, totv = nu->pntsv * resolv;
1206
1207         if (nu->knotsu == NULL || nu->knotsv == NULL)
1208                 return;
1209         if (nu->orderu > nu->pntsu)
1210                 return;
1211         if (nu->orderv > nu->pntsv)
1212                 return;
1213         if (coord_array == NULL)
1214                 return;
1215
1216         /* allocate and initialize */
1217         len = totu * totv;
1218         if (len == 0)
1219                 return;
1220
1221         sum = (float *)MEM_calloc_arrayN(len, sizeof(float), "makeNurbfaces1");
1222
1223         bp = nu->bp;
1224         i = nu->pntsu * nu->pntsv;
1225         ratcomp = 0;
1226         while (i--) {
1227                 if (bp->vec[3] != 1.0f) {
1228                         ratcomp = 1;
1229                         break;
1230                 }
1231                 bp++;
1232         }
1233
1234         fp = nu->knotsu;
1235         ustart = fp[nu->orderu - 1];
1236         if (nu->flagu & CU_NURB_CYCLIC)
1237                 uend = fp[nu->pntsu + nu->orderu - 1];
1238         else
1239                 uend = fp[nu->pntsu];
1240         ustep = (uend - ustart) / ((nu->flagu & CU_NURB_CYCLIC) ? totu : totu - 1);
1241
1242         basisu = (float *)MEM_malloc_arrayN(KNOTSU(nu), sizeof(float), "makeNurbfaces3");
1243
1244         fp = nu->knotsv;
1245         vstart = fp[nu->orderv - 1];
1246
1247         if (nu->flagv & CU_NURB_CYCLIC)
1248                 vend = fp[nu->pntsv + nu->orderv - 1];
1249         else
1250                 vend = fp[nu->pntsv];
1251         vstep = (vend - vstart) / ((nu->flagv & CU_NURB_CYCLIC) ? totv : totv - 1);
1252
1253         len = KNOTSV(nu);
1254         basisv = (float *)MEM_malloc_arrayN(len * totv, sizeof(float), "makeNurbfaces3");
1255         jstart = (int *)MEM_malloc_arrayN(totv, sizeof(float), "makeNurbfaces4");
1256         jend = (int *)MEM_malloc_arrayN(totv, sizeof(float), "makeNurbfaces5");
1257
1258         /* precalculation of basisv and jstart, jend */
1259         if (nu->flagv & CU_NURB_CYCLIC)
1260                 cycl = nu->orderv - 1;
1261         else cycl = 0;
1262         v = vstart;
1263         basis = basisv;
1264         curv = totv;
1265         while (curv--) {
1266                 basisNurb(v, nu->orderv, nu->pntsv + cycl, nu->knotsv, basis, jstart + curv, jend + curv);
1267                 basis += KNOTSV(nu);
1268                 v += vstep;
1269         }
1270
1271         if (nu->flagu & CU_NURB_CYCLIC)
1272                 cycl = nu->orderu - 1;
1273         else
1274                 cycl = 0;
1275         in = coord_array;
1276         u = ustart;
1277         curu = totu;
1278         while (curu--) {
1279                 basisNurb(u, nu->orderu, nu->pntsu + cycl, nu->knotsu, basisu, &istart, &iend);
1280
1281                 basis = basisv;
1282                 curv = totv;
1283                 while (curv--) {
1284                         jsta = jstart[curv];
1285                         jen = jend[curv];
1286
1287                         /* calculate sum */
1288                         sumdiv = 0.0;
1289                         fp = sum;
1290
1291                         for (j = jsta; j <= jen; j++) {
1292
1293                                 if (j >= nu->pntsv)
1294                                         jofs = (j - nu->pntsv);
1295                                 else
1296                                         jofs = j;
1297                                 bp = nu->bp + nu->pntsu * jofs + istart - 1;
1298
1299                                 for (i = istart; i <= iend; i++, fp++) {
1300                                         if (i >= nu->pntsu) {
1301                                                 iofs = i - nu->pntsu;
1302                                                 bp = nu->bp + nu->pntsu * jofs + iofs;
1303                                         }
1304                                         else
1305                                                 bp++;
1306
1307                                         if (ratcomp) {
1308                                                 *fp = basisu[i] * basis[j] * bp->vec[3];
1309                                                 sumdiv += *fp;
1310                                         }
1311                                         else
1312                                                 *fp = basisu[i] * basis[j];
1313                                 }
1314                         }
1315
1316                         if (ratcomp) {
1317                                 fp = sum;
1318                                 for (j = jsta; j <= jen; j++) {
1319                                         for (i = istart; i <= iend; i++, fp++) {
1320                                                 *fp /= sumdiv;
1321                                         }
1322                                 }
1323                         }
1324
1325                         zero_v3(in);
1326
1327                         /* one! (1.0) real point now */
1328                         fp = sum;
1329                         for (j = jsta; j <= jen; j++) {
1330
1331                                 if (j >= nu->pntsv)
1332                                         jofs = (j - nu->pntsv);
1333                                 else
1334                                         jofs = j;
1335                                 bp = nu->bp + nu->pntsu * jofs + istart - 1;
1336
1337                                 for (i = istart; i <= iend; i++, fp++) {
1338                                         if (i >= nu->pntsu) {
1339                                                 iofs = i - nu->pntsu;
1340                                                 bp = nu->bp + nu->pntsu * jofs + iofs;
1341                                         }
1342                                         else
1343                                                 bp++;
1344
1345                                         if (*fp != 0.0f) {
1346                                                 madd_v3_v3fl(in, bp->vec, *fp);
1347                                         }
1348                                 }
1349                         }
1350
1351                         in += 3;
1352                         basis += KNOTSV(nu);
1353                 }
1354                 u += ustep;
1355                 if (rowstride != 0) {
1356                         in = (float *)(((unsigned char *)in) + (rowstride - 3 * totv * sizeof(*in)));
1357                 }
1358         }
1359
1360         /* free */
1361         MEM_freeN(sum);
1362         MEM_freeN(basisu);
1363         MEM_freeN(basisv);
1364         MEM_freeN(jstart);
1365         MEM_freeN(jend);
1366 }
1367
1368 /**
1369  * \param coord_array: Has to be 3 * 4 * pntsu * resolu in size and zero-ed
1370  * \param tilt_array: set when non-NULL
1371  * \param radius_array: set when non-NULL
1372  */
1373 void BKE_nurb_makeCurve(
1374         const Nurb *nu, float *coord_array, float *tilt_array, float *radius_array, float *weight_array,
1375         int resolu, int stride)
1376 {
1377         const float eps = 1e-6f;
1378         BPoint *bp;
1379         float u, ustart, uend, ustep, sumdiv;
1380         float *basisu, *sum, *fp;
1381         float *coord_fp = coord_array, *tilt_fp = tilt_array, *radius_fp = radius_array, *weight_fp = weight_array;
1382         int i, len, istart, iend, cycl;
1383
1384         if (nu->knotsu == NULL)
1385                 return;
1386         if (nu->orderu > nu->pntsu)
1387                 return;
1388         if (coord_array == NULL)
1389                 return;
1390
1391         /* allocate and initialize */
1392         len = nu->pntsu;
1393         if (len == 0)
1394                 return;
1395         sum = (float *)MEM_calloc_arrayN(len, sizeof(float), "makeNurbcurve1");
1396
1397         resolu = (resolu * SEGMENTSU(nu));
1398
1399         if (resolu == 0) {
1400                 MEM_freeN(sum);
1401                 return;
1402         }
1403
1404         fp = nu->knotsu;
1405         ustart = fp[nu->orderu - 1];
1406         if (nu->flagu & CU_NURB_CYCLIC)
1407                 uend = fp[nu->pntsu + nu->orderu - 1];
1408         else
1409                 uend = fp[nu->pntsu];
1410         ustep = (uend - ustart) / (resolu - ((nu->flagu & CU_NURB_CYCLIC) ? 0 : 1));
1411
1412         basisu = (float *)MEM_malloc_arrayN(KNOTSU(nu), sizeof(float), "makeNurbcurve3");
1413
1414         if (nu->flagu & CU_NURB_CYCLIC)
1415                 cycl = nu->orderu - 1;
1416         else
1417                 cycl = 0;
1418
1419         u = ustart;
1420         while (resolu--) {
1421                 basisNurb(u, nu->orderu, nu->pntsu + cycl, nu->knotsu, basisu, &istart, &iend);
1422
1423                 /* calc sum */
1424                 sumdiv = 0.0;
1425                 fp = sum;
1426                 bp = nu->bp + istart - 1;
1427                 for (i = istart; i <= iend; i++, fp++) {
1428                         if (i >= nu->pntsu)
1429                                 bp = nu->bp + (i - nu->pntsu);
1430                         else
1431                                 bp++;
1432
1433                         *fp = basisu[i] * bp->vec[3];
1434                         sumdiv += *fp;
1435                 }
1436                 if ((sumdiv != 0.0f) && (sumdiv < 1.0f - eps || sumdiv > 1.0f + eps)) {
1437                         /* is normalizing needed? */
1438                         fp = sum;
1439                         for (i = istart; i <= iend; i++, fp++) {
1440                                 *fp /= sumdiv;
1441                         }
1442                 }
1443
1444                 zero_v3(coord_fp);
1445
1446                 /* one! (1.0) real point */
1447                 fp = sum;
1448                 bp = nu->bp + istart - 1;
1449                 for (i = istart; i <= iend; i++, fp++) {
1450                         if (i >= nu->pntsu)
1451                                 bp = nu->bp + (i - nu->pntsu);
1452                         else
1453                                 bp++;
1454
1455                         if (*fp != 0.0f) {
1456                                 madd_v3_v3fl(coord_fp, bp->vec, *fp);
1457
1458                                 if (tilt_fp)
1459                                         (*tilt_fp) += (*fp) * bp->alfa;
1460
1461                                 if (radius_fp)
1462                                         (*radius_fp) += (*fp) * bp->radius;
1463
1464                                 if (weight_fp)
1465                                         (*weight_fp) += (*fp) * bp->weight;
1466                         }
1467                 }
1468
1469                 coord_fp = POINTER_OFFSET(coord_fp, stride);
1470
1471                 if (tilt_fp)
1472                         tilt_fp = POINTER_OFFSET(tilt_fp, stride);
1473                 if (radius_fp)
1474                         radius_fp = POINTER_OFFSET(radius_fp, stride);
1475                 if (weight_fp)
1476                         weight_fp = POINTER_OFFSET(weight_fp, stride);
1477
1478                 u += ustep;
1479         }
1480
1481         /* free */
1482         MEM_freeN(sum);
1483         MEM_freeN(basisu);
1484 }
1485
1486 /**
1487  * Calculate the length for arrays filled in by #BKE_curve_calc_coords_axis.
1488  */
1489 unsigned int BKE_curve_calc_coords_axis_len(
1490         const unsigned int bezt_array_len, const unsigned int resolu,
1491         const bool is_cyclic, const bool use_cyclic_duplicate_endpoint)
1492 {
1493         const unsigned int segments = bezt_array_len - (is_cyclic ?  0 : 1);
1494         const unsigned int points_len = (segments * resolu) + (is_cyclic ? (use_cyclic_duplicate_endpoint) : 1);
1495         return points_len;
1496 }
1497
1498 /**
1499  * Calculate an array for the entire curve (cyclic or non-cyclic).
1500  * \note Call for each axis.
1501  *
1502  * \param use_cyclic_duplicate_endpoint: Duplicate values at the beginning & end of the array.
1503  */
1504 void BKE_curve_calc_coords_axis(
1505         const BezTriple *bezt_array, const unsigned int bezt_array_len, const unsigned int resolu,
1506         const bool is_cyclic, const bool use_cyclic_duplicate_endpoint,
1507         /* array params */
1508         const unsigned int axis, const unsigned int stride,
1509         float *r_points)
1510 {
1511         const unsigned int points_len = BKE_curve_calc_coords_axis_len(
1512                 bezt_array_len, resolu, is_cyclic, use_cyclic_duplicate_endpoint);
1513         float *r_points_offset = r_points;
1514
1515         const unsigned int resolu_stride = resolu * stride;
1516         const unsigned int bezt_array_last = bezt_array_len - 1;
1517
1518         for (unsigned int i = 0; i < bezt_array_last; i++) {
1519                 const BezTriple *bezt_curr = &bezt_array[i];
1520                 const BezTriple *bezt_next = &bezt_array[i + 1];
1521                 BKE_curve_forward_diff_bezier(
1522                         bezt_curr->vec[1][axis], bezt_curr->vec[2][axis],
1523                         bezt_next->vec[0][axis], bezt_next->vec[1][axis],
1524                         r_points_offset, (int)resolu, stride);
1525                 r_points_offset = POINTER_OFFSET(r_points_offset, resolu_stride);
1526         }
1527
1528         if (is_cyclic) {
1529                 const BezTriple *bezt_curr = &bezt_array[bezt_array_last];
1530                 const BezTriple *bezt_next = &bezt_array[0];
1531                 BKE_curve_forward_diff_bezier(
1532                         bezt_curr->vec[1][axis], bezt_curr->vec[2][axis],
1533                         bezt_next->vec[0][axis], bezt_next->vec[1][axis],
1534                         r_points_offset, (int)resolu, stride);
1535                 r_points_offset = POINTER_OFFSET(r_points_offset, resolu_stride);
1536                 if (use_cyclic_duplicate_endpoint) {
1537                         *r_points_offset = *r_points;
1538                         r_points_offset = POINTER_OFFSET(r_points_offset, stride);
1539                 }
1540         }
1541         else {
1542                 float *r_points_last = POINTER_OFFSET(r_points, bezt_array_last * resolu_stride);
1543                 *r_points_last = bezt_array[bezt_array_last].vec[1][axis];
1544                 r_points_offset = POINTER_OFFSET(r_points_offset, stride);
1545         }
1546
1547         BLI_assert(POINTER_OFFSET(r_points, points_len * stride) == r_points_offset);
1548         UNUSED_VARS_NDEBUG(points_len);
1549 }
1550
1551 /* forward differencing method for bezier curve */
1552 void BKE_curve_forward_diff_bezier(float q0, float q1, float q2, float q3, float *p, int it, int stride)
1553 {
1554         float rt0, rt1, rt2, rt3, f;
1555         int a;
1556
1557         f = (float)it;
1558         rt0 = q0;
1559         rt1 = 3.0f * (q1 - q0) / f;
1560         f *= f;
1561         rt2 = 3.0f * (q0 - 2.0f * q1 + q2) / f;
1562         f *= it;
1563         rt3 = (q3 - q0 + 3.0f * (q1 - q2)) / f;
1564
1565         q0 = rt0;
1566         q1 = rt1 + rt2 + rt3;
1567         q2 = 2 * rt2 + 6 * rt3;
1568         q3 = 6 * rt3;
1569
1570         for (a = 0; a <= it; a++) {
1571                 *p = q0;
1572                 p = POINTER_OFFSET(p, stride);
1573                 q0 += q1;
1574                 q1 += q2;
1575                 q2 += q3;
1576         }
1577 }
1578
1579 /* forward differencing method for first derivative of cubic bezier curve */
1580 void BKE_curve_forward_diff_tangent_bezier(float q0, float q1, float q2, float q3, float *p, int it, int stride)
1581 {
1582         float rt0, rt1, rt2, f;
1583         int a;
1584
1585         f = 1.0f / (float)it;
1586
1587         rt0 = 3.0f * (q1 - q0);
1588         rt1 = f * (3.0f * (q3 - q0) + 9.0f * (q1 - q2));
1589         rt2 = 6.0f * (q0 + q2) - 12.0f * q1;
1590
1591         q0 = rt0;
1592         q1 = f * (rt1 + rt2);
1593         q2 = 2.0f * f * rt1;
1594
1595         for (a = 0; a <= it; a++) {
1596                 *p = q0;
1597                 p = POINTER_OFFSET(p, stride);
1598                 q0 += q1;
1599                 q1 += q2;
1600         }
1601 }
1602
1603 static void forward_diff_bezier_cotangent(const float p0[3], const float p1[3], const float p2[3], const float p3[3],
1604                                           float p[3], int it, int stride)
1605 {
1606         /* note that these are not perpendicular to the curve
1607          * they need to be rotated for this,
1608          *
1609          * This could also be optimized like BKE_curve_forward_diff_bezier */
1610         int a;
1611         for (a = 0; a <= it; a++) {
1612                 float t = (float)a / (float)it;
1613
1614                 int i;
1615                 for (i = 0; i < 3; i++) {
1616                         p[i] = (-6.0f  * t +  6.0f) * p0[i] +
1617                                ( 18.0f * t - 12.0f) * p1[i] +
1618                                (-18.0f * t +  6.0f) * p2[i] +
1619                                ( 6.0f  * t)         * p3[i];
1620                 }
1621                 normalize_v3(p);
1622                 p = POINTER_OFFSET(p, stride);
1623         }
1624 }
1625
1626 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
1627
1628 float *BKE_curve_surf_make_orco(Object *ob)
1629 {
1630         /* Note: this function is used in convertblender only atm, so
1631          * suppose nonzero curve's render resolution should always be used */
1632         Curve *cu = ob->data;
1633         Nurb *nu;
1634         int a, b, tot = 0;
1635         int sizeu, sizev;
1636         int resolu, resolv;
1637         float *fp, *coord_array;
1638
1639         /* first calculate the size of the datablock */
1640         nu = cu->nurb.first;
1641         while (nu) {
1642                 /* as we want to avoid the seam in a cyclic nurbs
1643                  * texture wrapping, reserve extra orco data space to save these extra needed
1644                  * vertex based UV coordinates for the meridian vertices.
1645                  * Vertices on the 0/2pi boundary are not duplicated inside the displist but later in
1646                  * the renderface/vert construction.
1647                  *
1648                  * See also convertblender.c: init_render_surf()
1649                  */
1650
1651                 resolu = cu->resolu_ren ? cu->resolu_ren : nu->resolu;
1652                 resolv = cu->resolv_ren ? cu->resolv_ren : nu->resolv;
1653
1654                 sizeu = nu->pntsu * resolu;
1655                 sizev = nu->pntsv * resolv;
1656                 if (nu->flagu & CU_NURB_CYCLIC) sizeu++;
1657                 if (nu->flagv & CU_NURB_CYCLIC) sizev++;
1658                 if (nu->pntsv > 1) tot += sizeu * sizev;
1659
1660                 nu = nu->next;
1661         }
1662         /* makeNurbfaces wants zeros */
1663         fp = coord_array = MEM_calloc_arrayN(tot, 3 * sizeof(float), "make_orco");
1664
1665         nu = cu->nurb.first;
1666         while (nu) {
1667                 resolu = cu->resolu_ren ? cu->resolu_ren : nu->resolu;
1668                 resolv = cu->resolv_ren ? cu->resolv_ren : nu->resolv;
1669
1670                 if (nu->pntsv > 1) {
1671                         sizeu = nu->pntsu * resolu;
1672                         sizev = nu->pntsv * resolv;
1673
1674                         if (nu->flagu & CU_NURB_CYCLIC)
1675                                 sizeu++;
1676                         if (nu->flagv & CU_NURB_CYCLIC)
1677                                 sizev++;
1678
1679                         if (cu->flag & CU_UV_ORCO) {
1680                                 for (b = 0; b < sizeu; b++) {
1681                                         for (a = 0; a < sizev; a++) {
1682
1683                                                 if (sizev < 2)
1684                                                         fp[0] = 0.0f;
1685                                                 else
1686                                                         fp[0] = -1.0f + 2.0f * ((float)a) / (sizev - 1);
1687
1688                                                 if (sizeu < 2)
1689                                                         fp[1] = 0.0f;
1690                                                 else
1691                                                         fp[1] = -1.0f + 2.0f * ((float)b) / (sizeu - 1);
1692
1693                                                 fp[2] = 0.0;
1694
1695                                                 fp += 3;
1696                                         }
1697                                 }
1698                         }
1699                         else {
1700                                 int size = (nu->pntsu * resolu) * (nu->pntsv * resolv) * 3 * sizeof(float);
1701                                 float *_tdata = MEM_mallocN(size, "temp data");
1702                                 float *tdata = _tdata;
1703
1704                                 BKE_nurb_makeFaces(nu, tdata, 0, resolu, resolv);
1705
1706                                 for (b = 0; b < sizeu; b++) {
1707                                         int use_b = b;
1708                                         if (b == sizeu - 1 && (nu->flagu & CU_NURB_CYCLIC))
1709                                                 use_b = false;
1710
1711                                         for (a = 0; a < sizev; a++) {
1712                                                 int use_a = a;
1713                                                 if (a == sizev - 1 && (nu->flagv & CU_NURB_CYCLIC))
1714                                                         use_a = false;
1715
1716                                                 tdata = _tdata + 3 * (use_b * (nu->pntsv * resolv) + use_a);
1717
1718                                                 fp[0] = (tdata[0] - cu->loc[0]) / cu->size[0];
1719                                                 fp[1] = (tdata[1] - cu->loc[1]) / cu->size[1];
1720                                                 fp[2] = (tdata[2] - cu->loc[2]) / cu->size[2];
1721                                                 fp += 3;
1722                                         }
1723                                 }
1724
1725                                 MEM_freeN(_tdata);
1726                         }
1727                 }
1728                 nu = nu->next;
1729         }
1730
1731         return coord_array;
1732 }
1733
1734
1735 /* NOTE: This routine is tied to the order of vertex
1736  * built by displist and as passed to the renderer.
1737  */
1738 float *BKE_curve_make_orco(Depsgraph *depsgraph, Scene *scene, Object *ob, int *r_numVerts)
1739 {
1740         Curve *cu = ob->data;
1741         DispList *dl;
1742         int u, v, numVerts;
1743         float *fp, *coord_array;
1744         ListBase disp = {NULL, NULL};
1745
1746         BKE_displist_make_curveTypes_forOrco(depsgraph, scene, ob, &disp);
1747
1748         numVerts = 0;
1749         for (dl = disp.first; dl; dl = dl->next) {
1750                 if (dl->type == DL_INDEX3) {
1751                         numVerts += dl->nr;
1752                 }
1753                 else if (dl->type == DL_SURF) {
1754                         /* convertblender.c uses the Surface code for creating renderfaces when cyclic U only
1755                          * (closed circle beveling)
1756                          */
1757                         if (dl->flag & DL_CYCL_U) {
1758                                 if (dl->flag & DL_CYCL_V)
1759                                         numVerts += (dl->parts + 1) * (dl->nr + 1);
1760                                 else
1761                                         numVerts += dl->parts * (dl->nr + 1);
1762                         }
1763                         else if (dl->flag & DL_CYCL_V) {
1764                                 numVerts += (dl->parts + 1) * dl->nr;
1765                         }
1766                         else
1767                                 numVerts += dl->parts * dl->nr;
1768                 }
1769         }
1770
1771         if (r_numVerts)
1772                 *r_numVerts = numVerts;
1773
1774         fp = coord_array = MEM_malloc_arrayN(numVerts, 3 * sizeof(float), "cu_orco");
1775         for (dl = disp.first; dl; dl = dl->next) {
1776                 if (dl->type == DL_INDEX3) {
1777                         for (u = 0; u < dl->nr; u++, fp += 3) {
1778                                 if (cu->flag & CU_UV_ORCO) {
1779                                         fp[0] = 2.0f * u / (dl->nr - 1) - 1.0f;
1780                                         fp[1] = 0.0;
1781                                         fp[2] = 0.0;
1782                                 }
1783                                 else {
1784                                         copy_v3_v3(fp, &dl->verts[u * 3]);
1785
1786                                         fp[0] = (fp[0] - cu->loc[0]) / cu->size[0];
1787                                         fp[1] = (fp[1] - cu->loc[1]) / cu->size[1];
1788                                         fp[2] = (fp[2] - cu->loc[2]) / cu->size[2];
1789                                 }
1790                         }
1791                 }
1792                 else if (dl->type == DL_SURF) {
1793                         int sizeu = dl->nr, sizev = dl->parts;
1794
1795                         /* exception as handled in convertblender.c too */
1796                         if (dl->flag & DL_CYCL_U) {
1797                                 sizeu++;
1798                                 if (dl->flag & DL_CYCL_V)
1799                                         sizev++;
1800                         }
1801                         else if (dl->flag & DL_CYCL_V) {
1802                                 sizev++;
1803                         }
1804
1805                         for (u = 0; u < sizev; u++) {
1806                                 for (v = 0; v < sizeu; v++, fp += 3) {
1807                                         if (cu->flag & CU_UV_ORCO) {
1808                                                 fp[0] = 2.0f * u / (sizev - 1) - 1.0f;
1809                                                 fp[1] = 2.0f * v / (sizeu - 1) - 1.0f;
1810                                                 fp[2] = 0.0;
1811                                         }
1812                                         else {
1813                                                 const float *vert;
1814                                                 int realv = v % dl->nr;
1815                                                 int realu = u % dl->parts;
1816
1817                                                 vert = dl->verts + 3 * (dl->nr * realu + realv);
1818                                                 copy_v3_v3(fp, vert);
1819
1820                                                 fp[0] = (fp[0] - cu->loc[0]) / cu->size[0];
1821                                                 fp[1] = (fp[1] - cu->loc[1]) / cu->size[1];
1822                                                 fp[2] = (fp[2] - cu->loc[2]) / cu->size[2];
1823                                         }
1824                                 }
1825                         }
1826                 }
1827         }
1828
1829         BKE_displist_free(&disp);
1830
1831         return coord_array;
1832 }
1833
1834
1835 /* ***************** BEVEL ****************** */
1836
1837 void BKE_curve_bevel_make(
1838         Depsgraph *depsgraph, Scene *scene, Object *ob, ListBase *disp,
1839         const bool for_render, const bool use_render_resolution)
1840 {
1841         DispList *dl, *dlnew;
1842         Curve *bevcu, *cu;
1843         float *fp, facx, facy, angle, dangle;
1844         int nr, a;
1845
1846         cu = ob->data;
1847         BLI_listbase_clear(disp);
1848
1849         /* if a font object is being edited, then do nothing */
1850 // XXX  if ( ob == obedit && ob->type == OB_FONT ) return;
1851
1852         if (cu->bevobj) {
1853                 if (cu->bevobj->type != OB_CURVE)
1854                         return;
1855
1856                 bevcu = cu->bevobj->data;
1857                 if (bevcu->ext1 == 0.0f && bevcu->ext2 == 0.0f) {
1858                         ListBase bevdisp = {NULL, NULL};
1859                         facx = cu->bevobj->size[0];
1860                         facy = cu->bevobj->size[1];
1861
1862                         if (for_render) {
1863                                 BKE_displist_make_curveTypes_forRender(depsgraph, scene, cu->bevobj, &bevdisp, NULL, false, use_render_resolution);
1864                                 dl = bevdisp.first;
1865                         }
1866                         else if (cu->bevobj->runtime.curve_cache) {
1867                                 dl = cu->bevobj->runtime.curve_cache->disp.first;
1868                         }
1869                         else {
1870                                 BLI_assert(cu->bevobj->runtime.curve_cache != NULL);
1871                                 dl = NULL;
1872                         }
1873
1874                         while (dl) {
1875                                 if (ELEM(dl->type, DL_POLY, DL_SEGM)) {
1876                                         dlnew = MEM_mallocN(sizeof(DispList), "makebevelcurve1");
1877                                         *dlnew = *dl;
1878                                         dlnew->verts = MEM_malloc_arrayN(dl->parts * dl->nr, 3 * sizeof(float), "makebevelcurve1");
1879                                         memcpy(dlnew->verts, dl->verts, 3 * sizeof(float) * dl->parts * dl->nr);
1880
1881                                         if (dlnew->type == DL_SEGM)
1882                                                 dlnew->flag |= (DL_FRONT_CURVE | DL_BACK_CURVE);
1883
1884                                         BLI_addtail(disp, dlnew);
1885                                         fp = dlnew->verts;
1886                                         nr = dlnew->parts * dlnew->nr;
1887                                         while (nr--) {
1888                                                 fp[2] = fp[1] * facy;
1889                                                 fp[1] = -fp[0] * facx;
1890                                                 fp[0] = 0.0;
1891                                                 fp += 3;
1892                                         }
1893                                 }
1894                                 dl = dl->next;
1895                         }
1896
1897                         BKE_displist_free(&bevdisp);
1898                 }
1899         }
1900         else if (cu->ext1 == 0.0f && cu->ext2 == 0.0f) {
1901                 /* pass */
1902         }
1903         else if (cu->ext2 == 0.0f) {
1904                 dl = MEM_callocN(sizeof(DispList), "makebevelcurve2");
1905                 dl->verts = MEM_malloc_arrayN(2, sizeof(float[3]), "makebevelcurve2");
1906                 BLI_addtail(disp, dl);
1907                 dl->type = DL_SEGM;
1908                 dl->parts = 1;
1909                 dl->flag = DL_FRONT_CURVE | DL_BACK_CURVE;
1910                 dl->nr = 2;
1911
1912                 fp = dl->verts;
1913                 fp[0] = fp[1] = 0.0;
1914                 fp[2] = -cu->ext1;
1915                 fp[3] = fp[4] = 0.0;
1916                 fp[5] = cu->ext1;
1917         }
1918         else if ((cu->flag & (CU_FRONT | CU_BACK)) == 0 && cu->ext1 == 0.0f) {  /* we make a full round bevel in that case */
1919                 nr = 4 + 2 * cu->bevresol;
1920
1921                 dl = MEM_callocN(sizeof(DispList), "makebevelcurve p1");
1922                 dl->verts = MEM_malloc_arrayN(nr, sizeof(float[3]), "makebevelcurve p1");
1923                 BLI_addtail(disp, dl);
1924                 dl->type = DL_POLY;
1925                 dl->parts = 1;
1926                 dl->flag = DL_BACK_CURVE;
1927                 dl->nr = nr;
1928
1929                 /* a circle */
1930                 fp = dl->verts;
1931                 dangle = (2.0f * (float)M_PI / (nr));
1932                 angle = -(nr - 1) * dangle;
1933
1934                 for (a = 0; a < nr; a++) {
1935                         fp[0] = 0.0;
1936                         fp[1] = (cosf(angle) * (cu->ext2));
1937                         fp[2] = (sinf(angle) * (cu->ext2)) - cu->ext1;
1938                         angle += dangle;
1939                         fp += 3;
1940                 }
1941         }
1942         else {
1943                 short dnr;
1944
1945                 /* bevel now in three parts, for proper vertex normals */
1946                 /* part 1, back */
1947
1948                 if ((cu->flag & CU_BACK) || !(cu->flag & CU_FRONT)) {
1949                         dnr = nr = 2 + cu->bevresol;
1950                         if ((cu->flag & (CU_FRONT | CU_BACK)) == 0) {
1951                                 nr = 3 + 2 * cu->bevresol;
1952                         }
1953                         dl = MEM_callocN(sizeof(DispList), "makebevelcurve p1");
1954                         dl->verts = MEM_malloc_arrayN(nr, sizeof(float[3]), "makebevelcurve p1");
1955                         BLI_addtail(disp, dl);
1956                         dl->type = DL_SEGM;
1957                         dl->parts = 1;
1958                         dl->flag = DL_BACK_CURVE;
1959                         dl->nr = nr;
1960
1961                         /* half a circle */
1962                         fp = dl->verts;
1963                         dangle = ((float)M_PI_2 / (dnr - 1));
1964                         angle = -(nr - 1) * dangle;
1965
1966                         for (a = 0; a < nr; a++) {
1967                                 fp[0] = 0.0;
1968                                 fp[1] = (float)(cosf(angle) * (cu->ext2));
1969                                 fp[2] = (float)(sinf(angle) * (cu->ext2)) - cu->ext1;
1970                                 angle += dangle;
1971                                 fp += 3;
1972                         }
1973                 }
1974
1975                 /* part 2, sidefaces */
1976                 if (cu->ext1 != 0.0f) {
1977                         nr = 2;
1978
1979                         dl = MEM_callocN(sizeof(DispList), "makebevelcurve p2");
1980                         dl->verts = MEM_malloc_arrayN(nr, sizeof(float[3]), "makebevelcurve p2");
1981                         BLI_addtail(disp, dl);
1982                         dl->type = DL_SEGM;
1983                         dl->parts = 1;
1984                         dl->nr = nr;
1985
1986                         fp = dl->verts;
1987                         fp[1] = cu->ext2;
1988                         fp[2] = -cu->ext1;
1989                         fp[4] = cu->ext2;
1990                         fp[5] = cu->ext1;
1991
1992                         if ((cu->flag & (CU_FRONT | CU_BACK)) == 0) {
1993                                 dl = MEM_dupallocN(dl);
1994                                 dl->verts = MEM_dupallocN(dl->verts);
1995                                 BLI_addtail(disp, dl);
1996
1997                                 fp = dl->verts;
1998                                 fp[1] = -fp[1];
1999                                 fp[2] = -fp[2];
2000                                 fp[4] = -fp[4];
2001                                 fp[5] = -fp[5];
2002                         }
2003                 }
2004
2005                 /* part 3, front */
2006                 if ((cu->flag & CU_FRONT) || !(cu->flag & CU_BACK)) {
2007                         dnr = nr = 2 + cu->bevresol;
2008                         if ((cu->flag & (CU_FRONT | CU_BACK)) == 0) {
2009                                 nr = 3 + 2 * cu->bevresol;
2010                         }
2011                         dl = MEM_callocN(sizeof(DispList), "makebevelcurve p3");
2012                         dl->verts = MEM_malloc_arrayN(nr, sizeof(float[3]), "makebevelcurve p3");
2013                         BLI_addtail(disp, dl);
2014                         dl->type = DL_SEGM;
2015                         dl->flag = DL_FRONT_CURVE;
2016                         dl->parts = 1;
2017                         dl->nr = nr;
2018
2019                         /* half a circle */
2020                         fp = dl->verts;
2021                         angle = 0.0;
2022                         dangle = ((float)M_PI_2 / (dnr - 1));
2023
2024                         for (a = 0; a < nr; a++) {
2025                                 fp[0] = 0.0;
2026                                 fp[1] = (float)(cosf(angle) * (cu->ext2));
2027                                 fp[2] = (float)(sinf(angle) * (cu->ext2)) + cu->ext1;
2028                                 angle += dangle;
2029                                 fp += 3;
2030                         }
2031                 }
2032         }
2033 }
2034
2035 static int cu_isectLL(const float v1[3], const float v2[3], const float v3[3], const float v4[3],
2036                       short cox, short coy,
2037                       float *lambda, float *mu, float vec[3])
2038 {
2039         /* return:
2040          * -1: collinear
2041          *  0: no intersection of segments
2042          *  1: exact intersection of segments
2043          *  2: cross-intersection of segments
2044          */
2045         float deler;
2046
2047         deler = (v1[cox] - v2[cox]) * (v3[coy] - v4[coy]) - (v3[cox] - v4[cox]) * (v1[coy] - v2[coy]);
2048         if (deler == 0.0f)
2049                 return -1;
2050
2051         *lambda = (v1[coy] - v3[coy]) * (v3[cox] - v4[cox]) - (v1[cox] - v3[cox]) * (v3[coy] - v4[coy]);
2052         *lambda = -(*lambda / deler);
2053
2054         deler = v3[coy] - v4[coy];
2055         if (deler == 0) {
2056                 deler = v3[cox] - v4[cox];
2057                 *mu = -(*lambda * (v2[cox] - v1[cox]) + v1[cox] - v3[cox]) / deler;
2058         }
2059         else {
2060                 *mu = -(*lambda * (v2[coy] - v1[coy]) + v1[coy] - v3[coy]) / deler;
2061         }
2062         vec[cox] = *lambda * (v2[cox] - v1[cox]) + v1[cox];
2063         vec[coy] = *lambda * (v2[coy] - v1[coy]) + v1[coy];
2064
2065         if (*lambda >= 0.0f && *lambda <= 1.0f && *mu >= 0.0f && *mu <= 1.0f) {
2066                 if (*lambda == 0.0f || *lambda == 1.0f || *mu == 0.0f || *mu == 1.0f)
2067                         return 1;
2068                 return 2;
2069         }
2070         return 0;
2071 }
2072
2073
2074 static bool bevelinside(BevList *bl1, BevList *bl2)
2075 {
2076         /* is bl2 INSIDE bl1 ? with left-right method and "lambda's" */
2077         /* returns '1' if correct hole  */
2078         BevPoint *bevp, *prevbevp;
2079         float min, max, vec[3], hvec1[3], hvec2[3], lab, mu;
2080         int nr, links = 0, rechts = 0, mode;
2081
2082         /* take first vertex of possible hole */
2083
2084         bevp = bl2->bevpoints;
2085         hvec1[0] = bevp->vec[0];
2086         hvec1[1] = bevp->vec[1];
2087         hvec1[2] = 0.0;
2088         copy_v3_v3(hvec2, hvec1);
2089         hvec2[0] += 1000;
2090
2091         /* test it with all edges of potential surrounding poly */
2092         /* count number of transitions left-right  */
2093
2094         bevp = bl1->bevpoints;
2095         nr = bl1->nr;
2096         prevbevp = bevp + (nr - 1);
2097
2098         while (nr--) {
2099                 min = prevbevp->vec[1];
2100                 max = bevp->vec[1];
2101                 if (max < min) {
2102                         min = max;
2103                         max = prevbevp->vec[1];
2104                 }
2105                 if (min != max) {
2106                         if (min <= hvec1[1] && max >= hvec1[1]) {
2107                                 /* there's a transition, calc intersection point */
2108                                 mode = cu_isectLL(prevbevp->vec, bevp->vec, hvec1, hvec2, 0, 1, &lab, &mu, vec);
2109                                 /* if lab==0.0 or lab==1.0 then the edge intersects exactly a transition
2110                                  * only allow for one situation: we choose lab= 1.0
2111                                  */
2112                                 if (mode >= 0 && lab != 0.0f) {
2113                                         if (vec[0] < hvec1[0]) links++;
2114                                         else rechts++;
2115                                 }
2116                         }
2117                 }
2118                 prevbevp = bevp;
2119                 bevp++;
2120         }
2121
2122         return (links & 1) && (rechts & 1);
2123 }
2124
2125
2126 struct BevelSort {
2127         BevList *bl;
2128         float left;
2129         int dir;
2130 };
2131
2132 static int vergxcobev(const void *a1, const void *a2)
2133 {
2134         const struct BevelSort *x1 = a1, *x2 = a2;
2135
2136         if (x1->left > x2->left)
2137                 return 1;
2138         else if (x1->left < x2->left)
2139                 return -1;
2140         return 0;
2141 }
2142
2143 /* this function cannot be replaced with atan2, but why? */
2144
2145 static void calc_bevel_sin_cos(float x1, float y1, float x2, float y2,
2146                                float *r_sina, float *r_cosa)
2147 {
2148         float t01, t02, x3, y3;
2149
2150         t01 = sqrtf(x1 * x1 + y1 * y1);
2151         t02 = sqrtf(x2 * x2 + y2 * y2);
2152         if (t01 == 0.0f)
2153                 t01 = 1.0f;
2154         if (t02 == 0.0f)
2155                 t02 = 1.0f;
2156
2157         x1 /= t01;
2158         y1 /= t01;
2159         x2 /= t02;
2160         y2 /= t02;
2161
2162         t02 = x1 * x2 + y1 * y2;
2163         if (fabsf(t02) >= 1.0f)
2164                 t02 = M_PI_2;
2165         else
2166                 t02 = (saacos(t02)) / 2.0f;
2167
2168         t02 = sinf(t02);
2169         if (t02 == 0.0f)
2170                 t02 = 1.0f;
2171
2172         x3 = x1 - x2;
2173         y3 = y1 - y2;
2174         if (x3 == 0 && y3 == 0) {
2175                 x3 = y1;
2176                 y3 = -x1;
2177         }
2178         else {
2179                 t01 = sqrtf(x3 * x3 + y3 * y3);
2180                 x3 /= t01;
2181                 y3 /= t01;
2182         }
2183
2184         *r_sina = -y3 / t02;
2185         *r_cosa =  x3 / t02;
2186
2187 }
2188
2189 static void alfa_bezpart(BezTriple *prevbezt, BezTriple *bezt, Nurb *nu, float *tilt_array, float *radius_array,
2190                          float *weight_array, int resolu, int stride)
2191 {
2192         BezTriple *pprev, *next, *last;
2193         float fac, dfac, t[4];
2194         int a;
2195
2196         if (tilt_array == NULL && radius_array == NULL)
2197                 return;
2198
2199         last = nu->bezt + (nu->pntsu - 1);
2200
2201         /* returns a point */
2202         if (prevbezt == nu->bezt) {
2203                 if (nu->flagu & CU_NURB_CYCLIC)
2204                         pprev = last;
2205                 else
2206                         pprev = prevbezt;
2207         }
2208         else
2209                 pprev = prevbezt - 1;
2210
2211         /* next point */
2212         if (bezt == last) {
2213                 if (nu->flagu & CU_NURB_CYCLIC)
2214                         next = nu->bezt;
2215                 else
2216                         next = bezt;
2217         }
2218         else
2219                 next = bezt + 1;
2220
2221         fac = 0.0;
2222         dfac = 1.0f / (float)resolu;
2223
2224         for (a = 0; a < resolu; a++, fac += dfac) {
2225                 if (tilt_array) {
2226                         if (nu->tilt_interp == KEY_CU_EASE) { /* May as well support for tilt also 2.47 ease interp */
2227                                 *tilt_array = prevbezt->alfa +
2228                                         (bezt->alfa - prevbezt->alfa) * (3.0f * fac * fac - 2.0f * fac * fac * fac);
2229                         }
2230                         else {
2231                                 key_curve_position_weights(fac, t, nu->tilt_interp);
2232                                 *tilt_array = t[0] * pprev->alfa + t[1] * prevbezt->alfa + t[2] * bezt->alfa + t[3] * next->alfa;
2233                         }
2234
2235                         tilt_array = POINTER_OFFSET(tilt_array, stride);
2236                 }
2237
2238                 if (radius_array) {
2239                         if (nu->radius_interp == KEY_CU_EASE) {
2240                                 /* Support 2.47 ease interp
2241                                  * Note! - this only takes the 2 points into account,
2242                                  * giving much more localized results to changes in radius, sometimes you want that */
2243                                 *radius_array = prevbezt->radius +
2244                                         (bezt->radius - prevbezt->radius) * (3.0f * fac * fac - 2.0f * fac * fac * fac);
2245                         }
2246                         else {
2247
2248                                 /* reuse interpolation from tilt if we can */
2249                                 if (tilt_array == NULL || nu->tilt_interp != nu->radius_interp) {
2250                                         key_curve_position_weights(fac, t, nu->radius_interp);
2251                                 }
2252                                 *radius_array =
2253                                         t[0] * pprev->radius + t[1] * prevbezt->radius +
2254                                         t[2] * bezt->radius + t[3] * next->radius;
2255                         }
2256
2257                         radius_array = POINTER_OFFSET(radius_array, stride);
2258                 }
2259
2260                 if (weight_array) {
2261                         /* basic interpolation for now, could copy tilt interp too  */
2262                         *weight_array =
2263                                 prevbezt->weight +
2264                                 (bezt->weight - prevbezt->weight) * (3.0f * fac * fac - 2.0f * fac * fac * fac);
2265
2266                         weight_array = POINTER_OFFSET(weight_array, stride);
2267                 }
2268         }
2269 }
2270
2271 /* make_bevel_list_3D_* funcs, at a minimum these must
2272  * fill in the bezp->quat and bezp->dir values */
2273
2274 /* utility for make_bevel_list_3D_* funcs */
2275 static void bevel_list_calc_bisect(BevList *bl)
2276 {
2277         BevPoint *bevp2, *bevp1, *bevp0;
2278         int nr;
2279         bool is_cyclic = bl->poly != -1;
2280
2281         if (is_cyclic) {
2282                 bevp2 = bl->bevpoints;
2283                 bevp1 = bevp2 + (bl->nr - 1);
2284                 bevp0 = bevp1 - 1;
2285                 nr = bl->nr;
2286         }
2287         else {
2288                 /* If spline is not cyclic, direction of first and
2289                  * last bevel points matches direction of CV handle.
2290                  *
2291                  * This is getting calculated earlier when we know
2292                  * CV's handles and here we might simply skip evaluation
2293                  * of direction for this guys.
2294                  */
2295
2296                 bevp0 = bl->bevpoints;
2297                 bevp1 = bevp0 + 1;
2298                 bevp2 = bevp1 + 1;
2299
2300                 nr = bl->nr - 2;
2301         }
2302
2303         while (nr--) {
2304                 /* totally simple */
2305                 bisect_v3_v3v3v3(bevp1->dir, bevp0->vec, bevp1->vec, bevp2->vec);
2306
2307                 bevp0 = bevp1;
2308                 bevp1 = bevp2;
2309                 bevp2++;
2310         }
2311 }
2312 static void bevel_list_flip_tangents(BevList *bl)
2313 {
2314         BevPoint *bevp2, *bevp1, *bevp0;
2315         int nr;
2316
2317         bevp2 = bl->bevpoints;
2318         bevp1 = bevp2 + (bl->nr - 1);
2319         bevp0 = bevp1 - 1;
2320
2321         nr = bl->nr;
2322         while (nr--) {
2323                 if (angle_normalized_v3v3(bevp0->tan, bevp1->tan) > DEG2RADF(90.0f))
2324                         negate_v3(bevp1->tan);
2325
2326                 bevp0 = bevp1;
2327                 bevp1 = bevp2;
2328                 bevp2++;
2329         }
2330 }
2331 /* apply user tilt */
2332 static void bevel_list_apply_tilt(BevList *bl)
2333 {
2334         BevPoint *bevp2, *bevp1;
2335         int nr;
2336         float q[4];
2337
2338         bevp2 = bl->bevpoints;
2339         bevp1 = bevp2 + (bl->nr - 1);
2340
2341         nr = bl->nr;
2342         while (nr--) {
2343                 axis_angle_to_quat(q, bevp1->dir, bevp1->alfa);
2344                 mul_qt_qtqt(bevp1->quat, q, bevp1->quat);
2345                 normalize_qt(bevp1->quat);
2346
2347                 bevp1 = bevp2;
2348                 bevp2++;
2349         }
2350 }
2351 /* smooth quats, this function should be optimized, it can get slow with many iterations. */
2352 static void bevel_list_smooth(BevList *bl, int smooth_iter)
2353 {
2354         BevPoint *bevp2, *bevp1, *bevp0;
2355         int nr;
2356
2357         float q[4];
2358         float bevp0_quat[4];
2359         int a;
2360
2361         for (a = 0; a < smooth_iter; a++) {
2362                 bevp2 = bl->bevpoints;
2363                 bevp1 = bevp2 + (bl->nr - 1);
2364                 bevp0 = bevp1 - 1;
2365
2366                 nr = bl->nr;
2367
2368                 if (bl->poly == -1) { /* check its not cyclic */
2369                         /* skip the first point */
2370                         /* bevp0 = bevp1; */
2371                         bevp1 = bevp2;
2372                         bevp2++;
2373                         nr--;
2374
2375                         bevp0 = bevp1;
2376                         bevp1 = bevp2;
2377                         bevp2++;
2378                         nr--;
2379                 }
2380
2381                 copy_qt_qt(bevp0_quat, bevp0->quat);
2382
2383                 while (nr--) {
2384                         /* interpolate quats */
2385                         float zaxis[3] = {0, 0, 1}, cross[3], q2[4];
2386                         interp_qt_qtqt(q, bevp0_quat, bevp2->quat, 0.5);
2387                         normalize_qt(q);
2388
2389                         mul_qt_v3(q, zaxis);
2390                         cross_v3_v3v3(cross, zaxis, bevp1->dir);
2391                         axis_angle_to_quat(q2, cross, angle_normalized_v3v3(zaxis, bevp1->dir));
2392                         normalize_qt(q2);
2393
2394                         copy_qt_qt(bevp0_quat, bevp1->quat);
2395                         mul_qt_qtqt(q, q2, q);
2396                         interp_qt_qtqt(bevp1->quat, bevp1->quat, q, 0.5);
2397                         normalize_qt(bevp1->quat);
2398
2399                         /* bevp0 = bevp1; */ /* UNUSED */
2400                         bevp1 = bevp2;
2401                         bevp2++;
2402                 }
2403         }
2404 }
2405
2406 static void make_bevel_list_3D_zup(BevList *bl)
2407 {
2408         BevPoint *bevp = bl->bevpoints;
2409         int nr = bl->nr;
2410
2411         bevel_list_calc_bisect(bl);
2412
2413         while (nr--) {
2414                 vec_to_quat(bevp->quat, bevp->dir, 5, 1);
2415                 bevp++;
2416         }
2417 }
2418
2419 static void minimum_twist_between_two_points(BevPoint *current_point, BevPoint *previous_point)
2420 {
2421         float angle = angle_normalized_v3v3(previous_point->dir, current_point->dir);
2422         float q[4];
2423
2424         if (angle > 0.0f) { /* otherwise we can keep as is */
2425                 float cross_tmp[3];
2426                 cross_v3_v3v3(cross_tmp, previous_point->dir, current_point->dir);
2427                 axis_angle_to_quat(q, cross_tmp, angle);
2428                 mul_qt_qtqt(current_point->quat, q, previous_point->quat);
2429         }
2430         else {
2431                 copy_qt_qt(current_point->quat, previous_point->quat);
2432         }
2433 }
2434
2435 static void make_bevel_list_3D_minimum_twist(BevList *bl)
2436 {
2437         BevPoint *bevp2, *bevp1, *bevp0; /* standard for all make_bevel_list_3D_* funcs */
2438         int nr;
2439         float q[4];
2440
2441         bevel_list_calc_bisect(bl);
2442
2443         bevp2 = bl->bevpoints;
2444         bevp1 = bevp2 + (bl->nr - 1);
2445         bevp0 = bevp1 - 1;
2446
2447         nr = bl->nr;
2448         while (nr--) {
2449
2450                 if (nr + 4 > bl->nr) { /* first time and second time, otherwise first point adjusts last */
2451                         vec_to_quat(bevp1->quat, bevp1->dir, 5, 1);
2452                 }
2453                 else {
2454                         minimum_twist_between_two_points(bevp1, bevp0);
2455                 }
2456
2457                 bevp0 = bevp1;
2458                 bevp1 = bevp2;
2459                 bevp2++;
2460         }
2461
2462         if (bl->poly != -1) { /* check for cyclic */
2463
2464                 /* Need to correct for the start/end points not matching
2465                  * do this by calculating the tilt angle difference, then apply
2466                  * the rotation gradually over the entire curve
2467                  *
2468                  * note that the split is between last and second last, rather than first/last as youd expect.
2469                  *
2470                  * real order is like this
2471                  * 0,1,2,3,4 --> 1,2,3,4,0
2472                  *
2473                  * this is why we compare last with second last
2474                  * */
2475                 float vec_1[3] = {0, 1, 0}, vec_2[3] = {0, 1, 0}, angle, ang_fac, cross_tmp[3];
2476
2477                 BevPoint *bevp_first;
2478                 BevPoint *bevp_last;
2479
2480
2481                 bevp_first = bl->bevpoints;
2482                 bevp_first += bl->nr - 1;
2483                 bevp_last = bevp_first;
2484                 bevp_last--;
2485
2486                 /* quats and vec's are normalized, should not need to re-normalize */
2487                 mul_qt_v3(bevp_first->quat, vec_1);
2488                 mul_qt_v3(bevp_last->quat, vec_2);
2489                 normalize_v3(vec_1);
2490                 normalize_v3(vec_2);
2491
2492                 /* align the vector, can avoid this and it looks 98% OK but
2493                  * better to align the angle quat roll's before comparing */
2494                 {
2495                         cross_v3_v3v3(cross_tmp, bevp_last->dir, bevp_first->dir);
2496                         angle = angle_normalized_v3v3(bevp_first->dir, bevp_last->dir);
2497                         axis_angle_to_quat(q, cross_tmp, angle);
2498                         mul_qt_v3(q, vec_2);
2499                 }
2500
2501                 angle = angle_normalized_v3v3(vec_1, vec_2);
2502
2503                 /* flip rotation if needs be */
2504                 cross_v3_v3v3(cross_tmp, vec_1, vec_2);
2505                 normalize_v3(cross_tmp);
2506                 if (angle_normalized_v3v3(bevp_first->dir, cross_tmp) < DEG2RADF(90.0f))
2507                         angle = -angle;
2508
2509                 bevp2 = bl->bevpoints;
2510                 bevp1 = bevp2 + (bl->nr - 1);
2511                 bevp0 = bevp1 - 1;
2512
2513                 nr = bl->nr;
2514                 while (nr--) {
2515                         ang_fac = angle * (1.0f - ((float)nr / bl->nr)); /* also works */
2516
2517                         axis_angle_to_quat(q, bevp1->dir, ang_fac);
2518                         mul_qt_qtqt(bevp1->quat, q, bevp1->quat);
2519
2520                         bevp0 = bevp1;
2521                         bevp1 = bevp2;
2522                         bevp2++;
2523                 }
2524         }
2525         else {
2526                 /* Need to correct quat for the first/last point,
2527                  * this is so because previously it was only calculated
2528                  * using it's own direction, which might not correspond
2529                  * the twist of neighbor point.
2530                  */
2531                 bevp1 = bl->bevpoints;
2532                 bevp0 = bevp1 + 1;
2533                 minimum_twist_between_two_points(bevp1, bevp0);
2534
2535                 bevp2 = bl->bevpoints;
2536                 bevp1 = bevp2 + (bl->nr - 1);
2537                 bevp0 = bevp1 - 1;
2538                 minimum_twist_between_two_points(bevp1, bevp0);
2539         }
2540 }
2541
2542 static void make_bevel_list_3D_tangent(BevList *bl)
2543 {
2544         BevPoint *bevp2, *bevp1, *bevp0; /* standard for all make_bevel_list_3D_* funcs */
2545         int nr;
2546
2547         float bevp0_tan[3];
2548
2549         bevel_list_calc_bisect(bl);
2550         bevel_list_flip_tangents(bl);
2551
2552         /* correct the tangents */
2553         bevp2 = bl->bevpoints;
2554         bevp1 = bevp2 + (bl->nr - 1);
2555         bevp0 = bevp1 - 1;
2556
2557         nr = bl->nr;
2558         while (nr--) {
2559                 float cross_tmp[3];
2560                 cross_v3_v3v3(cross_tmp, bevp1->tan, bevp1->dir);
2561                 cross_v3_v3v3(bevp1->tan, cross_tmp, bevp1->dir);
2562                 normalize_v3(bevp1->tan);
2563
2564                 bevp0 = bevp1;
2565                 bevp1 = bevp2;
2566                 bevp2++;
2567         }
2568
2569
2570         /* now for the real twist calc */
2571         bevp2 = bl->bevpoints;
2572         bevp1 = bevp2 + (bl->nr - 1);
2573         bevp0 = bevp1 - 1;
2574
2575         copy_v3_v3(bevp0_tan, bevp0->tan);
2576
2577         nr = bl->nr;
2578         while (nr--) {
2579                 /* make perpendicular, modify tan in place, is ok */
2580                 float cross_tmp[3];
2581                 float zero[3] = {0, 0, 0};
2582
2583                 cross_v3_v3v3(cross_tmp, bevp1->tan, bevp1->dir);
2584                 normalize_v3(cross_tmp);
2585                 tri_to_quat(bevp1->quat, zero, cross_tmp, bevp1->tan); /* XXX - could be faster */
2586
2587                 /* bevp0 = bevp1; */ /* UNUSED */
2588                 bevp1 = bevp2;
2589                 bevp2++;
2590         }
2591 }
2592
2593 static void make_bevel_list_3D(BevList *bl, int smooth_iter, int twist_mode)
2594 {
2595         switch (twist_mode) {
2596                 case CU_TWIST_TANGENT:
2597                         make_bevel_list_3D_tangent(bl);
2598                         break;
2599                 case CU_TWIST_MINIMUM:
2600                         make_bevel_list_3D_minimum_twist(bl);
2601                         break;
2602                 default: /* CU_TWIST_Z_UP default, pre 2.49c */
2603                         make_bevel_list_3D_zup(bl);
2604                         break;
2605         }
2606
2607         if (smooth_iter)
2608                 bevel_list_smooth(bl, smooth_iter);
2609
2610         bevel_list_apply_tilt(bl);
2611 }
2612
2613 /* only for 2 points */
2614 static void make_bevel_list_segment_3D(BevList *bl)
2615 {
2616         float q[4];
2617
2618         BevPoint *bevp2 = bl->bevpoints;
2619         BevPoint *bevp1 = bevp2 + 1;
2620
2621         /* simple quat/dir */
2622         sub_v3_v3v3(bevp1->dir, bevp1->vec, bevp2->vec);
2623         normalize_v3(bevp1->dir);
2624
2625         vec_to_quat(bevp1->quat, bevp1->dir, 5, 1);
2626
2627         axis_angle_to_quat(q, bevp1->dir, bevp1->alfa);
2628         mul_qt_qtqt(bevp1->quat, q, bevp1->quat);
2629         normalize_qt(bevp1->quat);
2630         copy_v3_v3(bevp2->dir, bevp1->dir);
2631         copy_qt_qt(bevp2->quat, bevp1->quat);
2632 }
2633
2634 /* only for 2 points */
2635 static void make_bevel_list_segment_2D(BevList *bl)
2636 {
2637         BevPoint *bevp2 = bl->bevpoints;
2638         BevPoint *bevp1 = bevp2 + 1;
2639
2640         const float x1 = bevp1->vec[0] - bevp2->vec[0];
2641         const float y1 = bevp1->vec[1] - bevp2->vec[1];
2642
2643         calc_bevel_sin_cos(x1, y1, -x1, -y1, &(bevp1->sina), &(bevp1->cosa));
2644         bevp2->sina = bevp1->sina;
2645         bevp2->cosa = bevp1->cosa;
2646
2647         /* fill in dir & quat */
2648         make_bevel_list_segment_3D(bl);
2649 }
2650
2651 static void make_bevel_list_2D(BevList *bl)
2652 {
2653         /* note: bevp->dir and bevp->quat are not needed for beveling but are
2654          * used when making a path from a 2D curve, therefore they need to be set - Campbell */
2655
2656         BevPoint *bevp0, *bevp1, *bevp2;
2657         int nr;
2658
2659         if (bl->poly != -1) {
2660                 bevp2 = bl->bevpoints;
2661                 bevp1 = bevp2 + (bl->nr - 1);
2662                 bevp0 = bevp1 - 1;
2663                 nr = bl->nr;
2664         }
2665         else {
2666                 bevp0 = bl->bevpoints;
2667                 bevp1 = bevp0 + 1;
2668                 bevp2 = bevp1 + 1;
2669
2670                 nr = bl->nr - 2;
2671         }
2672
2673         while (nr--) {
2674                 const float x1 = bevp1->vec[0] - bevp0->vec[0];
2675                 const float x2 = bevp1->vec[0] - bevp2->vec[0];
2676                 const float y1 = bevp1->vec[1] - bevp0->vec[1];
2677                 const float y2 = bevp1->vec[1] - bevp2->vec[1];
2678
2679                 calc_bevel_sin_cos(x1, y1, x2, y2, &(bevp1->sina), &(bevp1->cosa));
2680
2681                 /* from: make_bevel_list_3D_zup, could call but avoid a second loop.
2682                  * no need for tricky tilt calculation as with 3D curves */
2683                 bisect_v3_v3v3v3(bevp1->dir, bevp0->vec, bevp1->vec, bevp2->vec);
2684                 vec_to_quat(bevp1->quat, bevp1->dir, 5, 1);
2685                 /* done with inline make_bevel_list_3D_zup */
2686
2687                 bevp0 = bevp1;
2688                 bevp1 = bevp2;
2689                 bevp2++;
2690         }
2691
2692         /* correct non-cyclic cases */
2693         if (bl->poly == -1) {
2694                 BevPoint *bevp;
2695                 float angle;
2696
2697                 /* first */
2698                 bevp = bl->bevpoints;
2699                 angle = atan2f(bevp->dir[0], bevp->dir[1]) - (float)M_PI_2;
2700                 bevp->sina = sinf(angle);
2701                 bevp->cosa = cosf(angle);
2702                 vec_to_quat(bevp->quat, bevp->dir, 5, 1);
2703
2704                 /* last */
2705                 bevp = bl->bevpoints;
2706                 bevp += (bl->nr - 1);
2707                 angle = atan2f(bevp->dir[0], bevp->dir[1]) - (float)M_PI_2;
2708                 bevp->sina = sinf(angle);
2709                 bevp->cosa = cosf(angle);
2710                 vec_to_quat(bevp->quat, bevp->dir, 5, 1);
2711         }
2712 }
2713
2714 static void bevlist_firstlast_direction_calc_from_bpoint(Nurb *nu, BevList *bl)
2715 {
2716         if (nu->pntsu > 1) {
2717                 BPoint *first_bp = nu->bp, *last_bp = nu->bp + (nu->pntsu - 1);
2718                 BevPoint *first_bevp, *last_bevp;
2719
2720                 first_bevp = bl->bevpoints;
2721                 last_bevp = first_bevp + (bl->nr - 1);
2722
2723                 sub_v3_v3v3(first_bevp->dir, (first_bp + 1)->vec, first_bp->vec);
2724                 normalize_v3(first_bevp->dir);
2725
2726                 sub_v3_v3v3(last_bevp->dir, last_bp->vec, (last_bp - 1)->vec);
2727                 normalize_v3(last_bevp->dir);
2728         }
2729 }
2730
2731 void BKE_curve_bevelList_free(ListBase *bev)
2732 {
2733         BevList *bl, *blnext;
2734         for (bl = bev->first; bl != NULL; bl = blnext) {
2735                 blnext = bl->next;
2736                 if (bl->seglen != NULL) {
2737                         MEM_freeN(bl->seglen);
2738                 }
2739                 if (bl->segbevcount != NULL) {
2740                         MEM_freeN(bl->segbevcount);
2741                 }
2742                 if (bl->bevpoints != NULL) {
2743                         MEM_freeN(bl->bevpoints);
2744                 }
2745                 MEM_freeN(bl);
2746         }
2747
2748         BLI_listbase_clear(bev);
2749 }
2750
2751 void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render)
2752 {
2753         /*
2754          * - convert all curves to polys, with indication of resol and flags for double-vertices
2755          * - possibly; do a smart vertice removal (in case Nurb)
2756          * - separate in individual blocks with BoundBox
2757          * - AutoHole detection
2758          */
2759
2760         /* this function needs an object, because of tflag and upflag */
2761         Curve *cu = ob->data;
2762         Nurb *nu;
2763         BezTriple *bezt, *prevbezt;
2764         BPoint *bp;
2765         BevList *bl, *blnew, *blnext;
2766         BevPoint *bevp2, *bevp1 = NULL, *bevp0;
2767         const float treshold = 0.00001f;
2768         float min, inp;
2769         float *seglen = NULL;
2770         struct BevelSort *sortdata, *sd, *sd1;
2771         int a, b, nr, poly, resolu = 0, len = 0, segcount;
2772         int *segbevcount;
2773         bool do_tilt, do_radius, do_weight;
2774         bool is_editmode = false;
2775         ListBase *bev;
2776
2777         /* segbevcount alsp requires seglen. */
2778         const bool need_seglen =
2779                 ELEM(cu->bevfac1_mapping, CU_BEVFAC_MAP_SEGMENT, CU_BEVFAC_MAP_SPLINE) ||
2780                 ELEM(cu->bevfac2_mapping, CU_BEVFAC_MAP_SEGMENT, CU_BEVFAC_MAP_SPLINE);
2781
2782
2783         bev = &ob->runtime.curve_cache->bev;
2784
2785         /* do we need to calculate the radius for each point? */
2786         /* do_radius = (cu->bevobj || cu->taperobj || (cu->flag & CU_FRONT) || (cu->flag & CU_BACK)) ? 0 : 1; */
2787
2788         /* STEP 1: MAKE POLYS  */
2789
2790         BKE_curve_bevelList_free(&ob->runtime.curve_cache->bev);
2791         nu = nurbs->first;
2792         if (cu->editnurb && ob->type != OB_FONT) {
2793                 is_editmode = 1;
2794         }
2795
2796         for (; nu; nu = nu->next) {
2797
2798                 if (nu->hide && is_editmode)
2799                         continue;
2800
2801                 /* check if we will calculate tilt data */
2802                 do_tilt = CU_DO_TILT(cu, nu);
2803                 do_radius = CU_DO_RADIUS(cu, nu); /* normal display uses the radius, better just to calculate them */
2804                 do_weight = true;
2805
2806                 /* check we are a single point? also check we are not a surface and that the orderu is sane,
2807                  * enforced in the UI but can go wrong possibly */
2808                 if (!BKE_nurb_check_valid_u(nu)) {
2809                         bl = MEM_callocN(sizeof(BevList), "makeBevelList1");
2810                         bl->bevpoints = MEM_calloc_arrayN(1, sizeof(BevPoint), "makeBevelPoints1");
2811                         BLI_addtail(bev, bl);
2812                         bl->nr = 0;
2813                         bl->charidx = nu->charidx;
2814                 }
2815                 else {
2816                         BevPoint *bevp;
2817
2818                         if (for_render && cu->resolu_ren != 0)
2819                                 resolu = cu->resolu_ren;
2820                         else
2821                                 resolu = nu->resolu;
2822
2823                         segcount = SEGMENTSU(nu);
2824
2825                         if (nu->type == CU_POLY) {
2826                                 len = nu->pntsu;
2827                                 bl = MEM_callocN(sizeof(BevList), "makeBevelList2");
2828                                 bl->bevpoints = MEM_calloc_arrayN(len, sizeof(BevPoint), "makeBevelPoints2");
2829                                 if (need_seglen && (nu->flagu & CU_NURB_CYCLIC) == 0) {
2830                                         bl->seglen = MEM_malloc_arrayN(segcount, sizeof(float), "makeBevelList2_seglen");
2831                                         bl->segbevcount = MEM_malloc_arrayN(segcount, sizeof(int), "makeBevelList2_segbevcount");
2832                                 }
2833                                 BLI_addtail(bev, bl);
2834
2835                                 bl->poly = (nu->flagu & CU_NURB_CYCLIC) ? 0 : -1;
2836                                 bl->nr = len;
2837                                 bl->dupe_nr = 0;
2838                                 bl->charidx = nu->charidx;
2839                                 bevp = bl->bevpoints;
2840                                 bevp->offset = 0;
2841                                 bp = nu->bp;
2842                                 seglen = bl->seglen;
2843                                 segbevcount = bl->segbevcount;
2844
2845                                 while (len--) {
2846                                         copy_v3_v3(bevp->vec, bp->vec);
2847                                         bevp->alfa = bp->alfa;
2848                                         bevp->radius = bp->radius;
2849                                         bevp->weight = bp->weight;
2850                                         bevp->split_tag = true;
2851                                         bp++;
2852                                         if (seglen != NULL && len != 0) {
2853                                                 *seglen = len_v3v3(bevp->vec, bp->vec);
2854                                                 bevp++;
2855                                                 bevp->offset = *seglen;
2856                                                 if (*seglen > treshold) *segbevcount = 1;
2857                                                 else *segbevcount = 0;
2858                                                 seglen++;
2859                                                 segbevcount++;
2860                                         }
2861                                         else {
2862                                                 bevp++;
2863                                         }
2864                                 }
2865
2866                                 if ((nu->flagu & CU_NURB_CYCLIC) == 0) {
2867                                         bevlist_firstlast_direction_calc_from_bpoint(nu, bl);
2868                                 }
2869                         }
2870                         else if (nu->type == CU_BEZIER) {
2871                                 /* in case last point is not cyclic */
2872                                 len = segcount * resolu + 1;
2873
2874                                 bl = MEM_callocN(sizeof(BevList), "makeBevelBPoints");
2875                                 bl->bevpoints = MEM_calloc_arrayN(len, sizeof(BevPoint), "makeBevelBPointsPoints");
2876                                 if (need_seglen && (nu->flagu & CU_NURB_CYCLIC) == 0) {
2877                                         bl->seglen = MEM_malloc_arrayN(segcount, sizeof(float), "makeBevelBPoints_seglen");
2878                                         bl->segbevcount = MEM_malloc_arrayN(segcount, sizeof(int), "makeBevelBPoints_segbevcount");
2879                                 }
2880                                 BLI_addtail(bev, bl);
2881
2882                                 bl->poly = (nu->flagu & CU_NURB_CYCLIC) ? 0 : -1;
2883                                 bl->charidx = nu->charidx;
2884
2885                                 bevp = bl->bevpoints;
2886                                 seglen = bl->seglen;
2887                                 segbevcount = bl->segbevcount;
2888
2889                                 bevp->offset = 0;
2890                                 if (seglen != NULL) {
2891                                         *seglen = 0;
2892                                         *segbevcount = 0;
2893                                 }
2894
2895                                 a = nu->pntsu - 1;
2896                                 bezt = nu->bezt;
2897                                 if (nu->flagu & CU_NURB_CYCLIC) {
2898                                         a++;
2899                                         prevbezt = nu->bezt + (nu->pntsu - 1);
2900                                 }
2901                                 else {
2902                                         prevbezt = bezt;
2903                                         bezt++;
2904                                 }
2905
2906                                 sub_v3_v3v3(bevp->dir, prevbezt->vec[2], prevbezt->vec[1]);
2907                                 normalize_v3(bevp->dir);
2908
2909                                 BLI_assert(segcount >= a);
2910
2911                                 while (a--) {
2912                                         if (prevbezt->h2 == HD_VECT && bezt->h1 == HD_VECT) {
2913
2914                                                 copy_v3_v3(bevp->vec, prevbezt->vec[1]);
2915                                                 bevp->alfa = prevbezt->alfa;
2916                                                 bevp->radius = prevbezt->radius;
2917                                                 bevp->weight = prevbezt->weight;
2918                                                 bevp->split_tag = true;
2919                                                 bevp->dupe_tag = false;
2920                                                 bevp++;
2921                                                 bl->nr++;
2922                                                 bl->dupe_nr = 1;
2923                                                 if (seglen != NULL) {
2924                                                         *seglen = len_v3v3(prevbezt->vec[1], bezt->vec[1]);
2925                                                         bevp->offset = *seglen;
2926                                                         seglen++;
2927                                                         /* match segbevcount to the cleaned up bevel lists (see STEP 2) */
2928                                                         if (bevp->offset > treshold) *segbevcount = 1;
2929                                                         segbevcount++;
2930                                                 }
2931                                         }
2932                                         else {
2933                                                 /* always do all three, to prevent data hanging around */
2934                                                 int j;
2935
2936                                                 /* BevPoint must stay aligned to 4 so sizeof(BevPoint)/sizeof(float) works */
2937                                                 for (j = 0; j < 3; j++) {
2938                                                         BKE_curve_forward_diff_bezier(prevbezt->vec[1][j],  prevbezt->vec[2][j],
2939                                                                                       bezt->vec[0][j],      bezt->vec[1][j],
2940                                                                                       &(bevp->vec[j]), resolu, sizeof(BevPoint));
2941                                                 }
2942
2943                                                 /* if both arrays are NULL do nothiong */
2944                                                 alfa_bezpart(prevbezt, bezt, nu,
2945                                                              do_tilt    ? &bevp->alfa : NULL,
2946                                                              do_radius  ? &bevp->radius : NULL,
2947                                                              do_weight  ? &bevp->weight : NULL,
2948                                                              resolu, sizeof(BevPoint));
2949
2950
2951                                                 if (cu->twist_mode == CU_TWIST_TANGENT) {
2952                                                         forward_diff_bezier_cotangent(prevbezt->vec[1], prevbezt->vec[2],
2953                                                                                       bezt->vec[0],     bezt->vec[1],
2954                                                                                       bevp->tan, resolu, sizeof(BevPoint));
2955                                                 }
2956
2957                                                 /* indicate with handlecodes double points */
2958                                                 if (prevbezt->h1 == prevbezt->h2) {
2959                                                         if (prevbezt->h1 == 0 || prevbezt->h1 == HD_VECT)
2960                                                                 bevp->split_tag = true;
2961                                                 }
2962                                                 else {
2963                                                         if (prevbezt->h1 == 0 || prevbezt->h1 == HD_VECT)
2964                                                                 bevp->split_tag = true;
2965                                                         else if (prevbezt->h2 == 0 || prevbezt->h2 == HD_VECT)
2966                                                                 bevp->split_tag = true;
2967                                                 }
2968
2969                                                 /* seglen */
2970                                                 if (seglen != NULL) {
2971                                                         *seglen = 0;
2972                                                         *segbevcount = 0;
2973                                                         for (j = 0; j < resolu; j++) {
2974                                                                 bevp0 = bevp;
2975                                                                 bevp++;
2976                                                                 bevp->offset = len_v3v3(bevp0->vec, bevp->vec);
2977                                                                 /* match seglen and segbevcount to the cleaned up bevel lists (see STEP 2) */
2978                                                                 if (bevp->offset > treshold) {
2979                                                                         *seglen += bevp->offset;
2980                                                                         *segbevcount += 1;
2981                                                                 }
2982                                                         }
2983                                                         seglen++;
2984                                                         segbevcount++;
2985                                                 }
2986                                                 else {
2987                                                         bevp += resolu;
2988                                                 }
2989                                                 bl->nr += resolu;
2990                                         }
2991                                         prevbezt = bezt;
2992                                         bezt++;
2993                                 }
2994
2995                                 if ((nu->flagu & CU_NURB_CYCLIC) == 0) {      /* not cyclic: endpoint */
2996                                         copy_v3_v3(bevp->vec, prevbezt->vec[1]);
2997                                         bevp->alfa = prevbezt->alfa;
2998                                         bevp->radius = prevbezt->radius;
2999                                         bevp->weight = prevbezt->weight;
3000
3001                                         sub_v3_v3v3(bevp->dir, prevbezt->vec[1], prevbezt->vec[0]);
3002                                         normalize_v3(bevp->dir);
3003
3004                                         bl->nr++;
3005                                 }
3006                         }
3007                         else if (nu->type == CU_NURBS) {
3008                                 if (nu->pntsv == 1) {
3009                                         len = (resolu * segcount);
3010
3011                                         bl = MEM_callocN(sizeof(BevList), "makeBevelList3");
3012                                         bl->bevpoints = MEM_calloc_arrayN(len, sizeof(BevPoint), "makeBevelPoints3");
3013                                         if (need_seglen && (nu->flagu & CU_NURB_CYCLIC) == 0) {
3014                                                 bl->seglen = MEM_malloc_arrayN(segcount, sizeof(float), "makeBevelList3_seglen");
3015                                                 bl->segbevcount = MEM_malloc_arrayN(segcount, sizeof(int), "makeBevelList3_segbevcount");
3016                                         }
3017                                         BLI_addtail(bev, bl);
3018                                         bl->nr = len;
3019                                         bl->dupe_nr = 0;
3020                                         bl->poly = (nu->flagu & CU_NURB_CYCLIC) ? 0 : -1;
3021                                         bl->charidx = nu->charidx;
3022
3023                                         bevp = bl->bevpoints;
3024                                         seglen = bl->seglen;
3025                                         segbevcount = bl->segbevcount;
3026
3027                                         BKE_nurb_makeCurve(nu, &bevp->vec[0],
3028                                                            do_tilt      ? &bevp->alfa : NULL,
3029                                                            do_radius    ? &bevp->radius : NULL,
3030                                                            do_weight    ? &bevp->weight : NULL,
3031                                                            resolu, sizeof(BevPoint));
3032
3033                                         /* match seglen and segbevcount to the cleaned up bevel lists (see STEP 2) */
3034                                         if (seglen != NULL) {
3035                                                 nr = segcount;
3036                                                 bevp0 = bevp;
3037                                                 bevp++;
3038                                                 while (nr) {
3039                                                         int j;
3040                                                         *seglen = 0;
3041                                                         *segbevcount = 0;
3042                                                         /* We keep last bevel segment zero-length. */
3043                                                         for (j = 0; j < ((nr == 1) ? (resolu - 1) : resolu); j++) {
3044                                                                 bevp->offset = len_v3v3(bevp0->vec, bevp->vec);
3045                                                                 if (bevp->offset > treshold) {
3046                                                                         *seglen += bevp->offset;
3047                                                                         *segbevcount += 1;
3048                                                                 }
3049                                                                 bevp0 = bevp;
3050                                                                 bevp++;
3051                                                         }
3052                                                         seglen++;
3053                                                         segbevcount++;
3054                                                         nr--;
3055                                                 }
3056                                         }
3057
3058                                         if ((nu->flagu & CU_NURB_CYCLIC) == 0) {
3059                                                 bevlist_firstlast_direction_calc_from_bpoint(nu, bl);
3060                                         }
3061                                 }
3062                         }
3063                 }
3064         }
3065
3066         /* STEP 2: DOUBLE POINTS AND AUTOMATIC RESOLUTION, REDUCE DATABLOCKS */
3067         bl = bev->first;
3068         while (bl) {
3069                 if (bl->nr) { /* null bevel items come from single points */
3070                         bool is_cyclic = bl->poly != -1;
3071                         nr = bl->nr;
3072                         if (is_cyclic) {
3073                                 bevp1 = bl->bevpoints;
3074                                 bevp0 = bevp1 + (nr - 1);
3075                         }
3076                         else {
3077                                 bevp0 = bl->bevpoints;
3078                                 bevp0->offset = 0;
3079                                 bevp1 = bevp0 + 1;
3080                         }
3081               &nb