Improve the rendering of curvegradient layers near vertices with zero-length tangents...
[synfig.git] / synfig-core / trunk / src / modules / mod_gradient / curvegradient.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file curvegradient.cpp
3 **      \brief Implementation of the "Curve Gradient" layer
4 **
5 **      $Id$
6 **
7 **      \legal
8 **      Copyright (c) 2002-2005 Robert B. Quattlebaum Jr., Adrian Bentley
9 **      Copyright (c) 2007-2008 Chris Moore
10 **
11 **      This package is free software; you can redistribute it and/or
12 **      modify it under the terms of the GNU General Public License as
13 **      published by the Free Software Foundation; either version 2 of
14 **      the License, or (at your option) any later version.
15 **
16 **      This package is distributed in the hope that it will be useful,
17 **      but WITHOUT ANY WARRANTY; without even the implied warranty of
18 **      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 **      General Public License for more details.
20 **      \endlegal
21 **
22 ** === N O T E S ===========================================================
23 **
24 ** ========================================================================= */
25
26 /* === H E A D E R S ======================================================= */
27
28 #ifdef USING_PCH
29 #       include "pch.h"
30 #else
31 #ifdef HAVE_CONFIG_H
32 #       include <config.h>
33 #endif
34
35 #include "curvegradient.h"
36
37 #include <synfig/string.h>
38 #include <synfig/time.h>
39 #include <synfig/context.h>
40 #include <synfig/paramdesc.h>
41 #include <synfig/renddesc.h>
42 #include <synfig/surface.h>
43 #include <synfig/value.h>
44 #include <synfig/valuenode.h>
45 #include <ETL/bezier>
46 #include <ETL/hermite>
47 #include <ETL/calculus>
48
49 #endif
50
51 /* === M A C R O S ========================================================= */
52
53 #define FAKE_TANGENT_STEP 0.000001
54
55 /* === G L O B A L S ======================================================= */
56
57 SYNFIG_LAYER_INIT(CurveGradient);
58 SYNFIG_LAYER_SET_NAME(CurveGradient,"curve_gradient");
59 SYNFIG_LAYER_SET_LOCAL_NAME(CurveGradient,N_("Curve Gradient"));
60 SYNFIG_LAYER_SET_CATEGORY(CurveGradient,N_("Gradients"));
61 SYNFIG_LAYER_SET_VERSION(CurveGradient,"0.0");
62 SYNFIG_LAYER_SET_CVS_ID(CurveGradient,"$Id$");
63
64 /* === P R O C E D U R E S ================================================= */
65
66 inline float calculate_distance(const synfig::BLinePoint& a,const synfig::BLinePoint& b)
67 {
68 #if 1
69         const Point& c1(a.get_vertex());
70         const Point c2(a.get_vertex()+a.get_tangent2()/3);
71         const Point c3(b.get_vertex()-b.get_tangent1()/3);
72         const Point& c4(b.get_vertex());
73         return (c1-c2).mag()+(c2-c3).mag()+(c3-c4).mag();
74 #else
75 #endif
76 }
77
78 inline float calculate_distance(const std::vector<synfig::BLinePoint>& bline, bool bline_loop)
79 {
80         std::vector<synfig::BLinePoint>::const_iterator iter,next,ret;
81         std::vector<synfig::BLinePoint>::const_iterator end(bline.end());
82
83         float dist(0);
84
85         if (bline.empty()) return dist;
86
87         next=bline.begin();
88
89         if(bline_loop)
90                 iter=--bline.end();
91         else
92                 iter=next++;
93
94         for(;next!=end;iter=next++)
95         {
96                 // Setup the curve
97                 etl::hermite<Vector> curve(
98                         iter->get_vertex(),
99                         next->get_vertex(),
100                         iter->get_tangent2(),
101                         next->get_tangent1());
102
103 //              dist+=calculate_distance(*iter,*next);
104                 dist+=curve.length();
105         }
106
107         return dist;
108 }
109
110 std::vector<synfig::BLinePoint>::const_iterator
111 find_closest(bool fast, const std::vector<synfig::BLinePoint>& bline,const Point& p,float& t,bool loop=false,float *bline_dist_ret=0)
112 {
113         std::vector<synfig::BLinePoint>::const_iterator iter,next,ret;
114         std::vector<synfig::BLinePoint>::const_iterator end(bline.end());
115
116         ret=bline.end();
117         float dist(100000000000.0);
118
119         next=bline.begin();
120
121         float best_bline_dist(0);
122         float best_bline_len(0);
123         float total_bline_dist(0);
124         float best_pos(0);
125         etl::hermite<Vector> best_curve;
126
127         if(loop)
128                 iter=--bline.end();
129         else
130                 iter=next++;
131
132         Point bp;
133
134         for(;next!=end;iter=next++)
135         {
136                 // Setup the curve
137                 etl::hermite<Vector> curve(
138                         iter->get_vertex(),
139                         next->get_vertex(),
140                         iter->get_tangent2(),
141                         next->get_tangent1());
142
143                 /*
144                 const float t(curve.find_closest(p,6,0.01,0.99));
145                 bp=curve(t);if((bp-p).mag_squared()<dist) { ret=iter; dist=(bp-p).mag_squared(); ret_t=t; }
146                 */
147
148                 float thisdist(0);
149                 float len(0);
150                 if(bline_dist_ret)
151                 {
152                         //len=calculate_distance(*iter,*next);
153                         len=curve.length();
154                 }
155
156                 if (fast)
157                 {
158 #define POINT_CHECK(x) bp=curve(x);     thisdist=(bp-p).mag_squared(); if(thisdist<dist) { ret=iter; dist=thisdist; best_bline_dist=total_bline_dist; best_bline_len=len; best_curve=curve; }
159                         POINT_CHECK(0.0001);
160                         POINT_CHECK((1.0/6.0));
161                         POINT_CHECK((2.0/6.0));
162                         POINT_CHECK((3.0/6.0));
163                         POINT_CHECK((4.0/6.0));
164                         POINT_CHECK((5.0/6.0));
165                         POINT_CHECK(0.9999);
166                 }
167                 else
168                 {
169                         float pos = curve.find_closest(fast, p);
170                         thisdist=(curve(pos)-p).mag_squared();
171                         if(thisdist<dist)
172                         {
173                                 ret=iter;
174                                 dist=thisdist;
175                                 best_bline_dist=total_bline_dist;
176                                 best_bline_len=len;
177                                 best_curve=curve;
178                                 best_pos = pos;
179                         }
180                 }
181
182                 total_bline_dist+=len;
183         }
184
185         t = best_pos;
186
187         if(bline_dist_ret)
188         {
189                 //! \todo is this a redundant call to find_closest()?
190                 // note bline_dist_ret is null except when 'perpendicular' is true
191                 *bline_dist_ret=best_bline_dist+best_curve.find_distance(0,best_curve.find_closest(fast, p));
192 //              *bline_dist_ret=best_bline_dist+best_curve.find_closest(fast, p)*best_bline_len;
193         }
194
195         return ret;
196 }
197
198 /* === M E T H O D S ======================================================= */
199
200 inline void
201 CurveGradient::sync()
202 {
203         curve_length_=calculate_distance(bline, bline_loop);
204 }
205
206
207 CurveGradient::CurveGradient():
208         origin(0,0),
209         width(0.25),
210         gradient(Color::black(), Color::white()),
211         loop(false),
212         zigzag(false),
213         perpendicular(false),
214         fast(true)
215 {
216         bline.push_back(BLinePoint());
217         bline.push_back(BLinePoint());
218         bline.push_back(BLinePoint());
219         bline[0].set_vertex(Point(0,1));
220         bline[1].set_vertex(Point(0,-1));
221         bline[2].set_vertex(Point(1,0));
222         bline[0].set_tangent(bline[1].get_vertex()-bline[2].get_vertex()*0.5f);
223         bline[1].set_tangent(bline[2].get_vertex()-bline[0].get_vertex()*0.5f);
224         bline[2].set_tangent(bline[0].get_vertex()-bline[1].get_vertex()*0.5f);
225         bline[0].set_width(1.0f);
226         bline[1].set_width(1.0f);
227         bline[2].set_width(1.0f);
228         bline_loop=true;
229
230         sync();
231 }
232
233 inline Color
234 CurveGradient::color_func(const Point &point_, int quality, float supersample)const
235 {
236         Vector tangent;
237         Vector diff;
238         Point p1;
239         Real thickness;
240         Real dist;
241
242         float perp_dist;
243         bool edge_case = false;
244
245         if(bline.size()==0)
246                 return Color::alpha();
247         else if(bline.size()==1)
248         {
249                 tangent=bline.front().get_tangent1();
250                 p1=bline.front().get_vertex();
251                 thickness=bline.front().get_width();
252         }
253         else
254         {
255                 float t;
256                 Point point(point_-origin);
257
258                 std::vector<synfig::BLinePoint>::const_iterator iter,next;
259
260                 // Figure out the BLinePoints we will be using,
261                 // Taking into account looping.
262                 if(perpendicular)
263                 {
264                         next=find_closest(fast,bline,point,t,bline_loop,&perp_dist);
265                         perp_dist/=curve_length_;
266                 }
267                 else                                    // not perpendicular
268                 {
269                         next=find_closest(fast,bline,point,t,bline_loop);
270                 }
271
272                 iter=next++;
273                 if(next==bline.end()) next=bline.begin();
274
275                 // Setup the curve
276                 etl::hermite<Vector> curve(
277                         iter->get_vertex(),
278                         next->get_vertex(),
279                         iter->get_tangent2(),
280                         next->get_tangent1()
281                         );
282
283                 // Setup the derivative function
284                 etl::derivative<etl::hermite<Vector> > deriv(curve);
285
286                 int search_iterations(7);
287
288                 /*if(quality==0)search_iterations=8;
289                   else if(quality<=2)search_iterations=10;
290                   else if(quality<=4)search_iterations=8;
291                 */
292                 if(perpendicular)
293                 {
294                         if(quality>7)
295                                 search_iterations=4;
296                 }
297                 else                                    // not perpendicular
298                 {
299                         if(quality<=6)search_iterations=7;
300                         else if(quality<=7)search_iterations=6;
301                         else if(quality<=8)search_iterations=5;
302                         else search_iterations=4;
303                 }
304
305                 // Figure out the closest point on the curve
306                 if (fast)
307                         t = curve.find_closest(fast, point,search_iterations);
308
309                 // Calculate our values
310                 p1=curve(t);                     // the closest point on the curve
311                 tangent=deriv(t);                // the tangent at that point
312
313                 // if the point we're nearest to is at either end of the
314                 // bline, our distance from the curve is the distance from the
315                 // point on the curve.  we need to know which side of the
316                 // curve we're on, so find the average of the two tangents at
317                 // this point
318                 if (t<0.00001 || t>0.99999)
319                 {
320                         bool zero_tangent = (tangent[0] == 0 && tangent[1] == 0);
321
322                         if (t<0.5)
323                         {
324                                 if (iter->get_split_tangent_flag() || zero_tangent)
325                                 {
326                                         // fake the current tangent if we need to
327                                         if (zero_tangent) tangent = curve(FAKE_TANGENT_STEP) - curve(0);
328
329                                         // calculate the other tangent
330                                         Vector other_tangent(iter->get_tangent1());
331                                         if (other_tangent[0] == 0 && other_tangent[1] == 0)
332                                         {
333                                                 // find the previous blinepoint
334                                                 std::vector<synfig::BLinePoint>::const_iterator prev;
335                                                 if (iter != bline.begin()) (prev = iter)--;
336                                                 else if (loop) (prev = bline.end())--;
337                                                 else prev = iter;
338
339                                                 etl::hermite<Vector> other_curve(prev->get_vertex(), iter->get_vertex(), prev->get_tangent2(), iter->get_tangent1());
340                                                 other_tangent = other_curve(1) - other_curve(1-FAKE_TANGENT_STEP);
341                                         }
342
343                                         // normalise and sum the two tangents
344                                         tangent=(other_tangent.norm()+tangent.norm());
345                                         edge_case=true;
346                                 }
347                         }
348                         else
349                         {
350                                 if (next->get_split_tangent_flag() || zero_tangent)
351                                 {
352                                         // fake the current tangent if we need to
353                                         if (zero_tangent) tangent = curve(1) - curve(1-FAKE_TANGENT_STEP);
354
355                                         // calculate the other tangent
356                                         Vector other_tangent(next->get_tangent2());
357                                         if (other_tangent[0] == 0 && other_tangent[1] == 0)
358                                         {
359                                                 // find the next blinepoint
360                                                 std::vector<synfig::BLinePoint>::const_iterator next2(next);
361                                                 if (++next2 == bline.end())
362                                                 {
363                                                         if (loop) next2 = bline.begin();
364                                                         else next2 = next;
365                                                 }
366
367                                                 etl::hermite<Vector> other_curve(next->get_vertex(), next2->get_vertex(), next->get_tangent2(), next2->get_tangent1());
368                                                 other_tangent = other_curve(FAKE_TANGENT_STEP) - other_curve(0);
369                                         }
370
371                                         // normalise and sum the two tangents
372                                         tangent=(other_tangent.norm()+tangent.norm());
373                                         edge_case=true;
374                                 }
375                         }
376                 }
377                 tangent = tangent.norm();
378
379                 if(perpendicular)
380                 {
381                         tangent*=curve_length_;
382                         p1-=tangent*perp_dist;
383                         tangent=-tangent.perp();
384                 }
385                 else                                    // not perpendicular
386                         // the width of the bline at the closest point on the curve
387                         thickness=(next->get_width()-iter->get_width())*t+iter->get_width();
388         }
389
390         if(perpendicular)
391         {
392                 if(quality>7)
393                 {
394                         dist=perp_dist;
395 /*                      diff=tangent.perp();
396                         const Real mag(diff.inv_mag());
397                         supersample=supersample*mag;
398 */
399                         supersample=0;
400                 }
401                 else
402                 {
403                         diff=tangent.perp();
404                         //p1-=diff*0.5;
405                         const Real mag(diff.inv_mag());
406                         supersample=supersample*mag;
407                         diff*=mag*mag;
408                         dist=(point_-origin - p1)*diff;
409                 }
410         }
411         else                                            // not perpendicular
412         {
413                 if (edge_case)
414                 {
415                         diff=(p1-(point_-origin));
416                         if(diff*tangent.perp()<0) diff=-diff;
417                         diff=diff.norm()*thickness*width;
418                 }
419                 else
420                         diff=tangent.perp()*thickness*width;
421
422                 p1-=diff*0.5;
423                 const Real mag(diff.inv_mag());
424                 supersample=supersample*mag;
425                 diff*=mag*mag;
426                 dist=(point_-origin - p1)*diff;
427         }
428
429         if(loop)
430                 dist-=floor(dist);
431
432         if(zigzag)
433         {
434                 dist*=2.0;
435                 supersample*=2.0;
436                 if(dist>1)dist=2.0-dist;
437         }
438
439         if(loop)
440         {
441                 if(dist+supersample*0.5>1.0)
442                 {
443                         float  left(supersample*0.5-(dist-1.0));
444                         float right(supersample*0.5+(dist-1.0));
445                         Color pool(gradient(1.0-(left*0.5),left).premult_alpha()*left/supersample);
446                         if (zigzag) pool+=gradient(1.0-right*0.5,right).premult_alpha()*right/supersample;
447                         else            pool+=gradient(right*0.5,right).premult_alpha()*right/supersample;
448                         return pool.demult_alpha();
449                 }
450                 if(dist-supersample*0.5<0.0)
451                 {
452                         float  left(supersample*0.5-dist);
453                         float right(supersample*0.5+dist);
454                         Color pool(gradient(right*0.5,right).premult_alpha()*right/supersample);
455                         if (zigzag) pool+=gradient(left*0.5,left).premult_alpha()*left/supersample;
456                         else            pool+=gradient(1.0-left*0.5,left).premult_alpha()*left/supersample;
457                         return pool.demult_alpha();
458                 }
459         }
460         return gradient(dist,supersample);
461 }
462
463 float
464 CurveGradient::calc_supersample(const synfig::Point &/*x*/, float pw,float /*ph*/)const
465 {
466         return pw;
467 }
468
469 synfig::Layer::Handle
470 CurveGradient::hit_check(synfig::Context context, const synfig::Point &point)const
471 {
472         if(get_blend_method()==Color::BLEND_STRAIGHT && get_amount()>=0.5)
473                 return const_cast<CurveGradient*>(this);
474         if(get_amount()==0.0)
475                 return context.hit_check(point);
476         if((get_blend_method()==Color::BLEND_STRAIGHT || get_blend_method()==Color::BLEND_COMPOSITE|| get_blend_method()==Color::BLEND_ONTO) && color_func(point).get_a()>0.5)
477                 return const_cast<CurveGradient*>(this);
478         return context.hit_check(point);
479 }
480
481 bool
482 CurveGradient::set_param(const String & param, const ValueBase &value)
483 {
484
485
486         IMPORT(origin);
487         IMPORT(perpendicular);
488         IMPORT(fast);
489
490         if(param=="bline" && value.get_type()==ValueBase::TYPE_LIST)
491         {
492                 bline=value;
493                 bline_loop=value.get_loop();
494                 sync();
495
496                 return true;
497         }
498
499         IMPORT(width);
500         IMPORT(gradient);
501         IMPORT(loop);
502         IMPORT(zigzag);
503
504         IMPORT_AS(origin,"offset");
505
506         return Layer_Composite::set_param(param,value);
507 }
508
509 ValueBase
510 CurveGradient::get_param(const String & param)const
511 {
512         EXPORT(origin);
513         EXPORT(bline);
514         EXPORT(gradient);
515         EXPORT(loop);
516         EXPORT(zigzag);
517         EXPORT(width);
518         EXPORT(perpendicular);
519         EXPORT(fast);
520
521         EXPORT_NAME();
522         EXPORT_VERSION();
523
524         return Layer_Composite::get_param(param);
525 }
526
527 Layer::Vocab
528 CurveGradient::get_param_vocab()const
529 {
530         Layer::Vocab ret(Layer_Composite::get_param_vocab());
531
532         ret.push_back(ParamDesc("origin")
533                                   .set_local_name(_("Origin")));
534
535         ret.push_back(ParamDesc("width")
536                                   .set_is_distance()
537                                   .set_local_name(_("Width")));
538
539         ret.push_back(ParamDesc("bline")
540                                   .set_local_name(_("Vertices"))
541                                   .set_origin("origin")
542                                   .set_hint("width")
543                                   .set_description(_("A list of BLine Points")));
544
545         ret.push_back(ParamDesc("gradient")
546                                   .set_local_name(_("Gradient")));
547         ret.push_back(ParamDesc("loop")
548                                   .set_local_name(_("Loop")));
549         ret.push_back(ParamDesc("zigzag")
550                                   .set_local_name(_("ZigZag")));
551         ret.push_back(ParamDesc("perpendicular")
552                                   .set_local_name(_("Perpendicular")));
553         ret.push_back(ParamDesc("fast")
554                                   .set_local_name(_("Fast")));
555
556         return ret;
557 }
558
559 Color
560 CurveGradient::get_color(Context context, const Point &point)const
561 {
562         const Color color(color_func(point,0));
563
564         if(get_amount()==1.0 && get_blend_method()==Color::BLEND_STRAIGHT)
565                 return color;
566         else
567                 return Color::blend(color,context.get_color(point),get_amount(),get_blend_method());
568 }
569
570 bool
571 CurveGradient::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
572 {
573         SuperCallback supercb(cb,0,9500,10000);
574
575         if(get_amount()==1.0 && get_blend_method()==Color::BLEND_STRAIGHT)
576         {
577                 surface->set_wh(renddesc.get_w(),renddesc.get_h());
578         }
579         else
580         {
581                 if(!context.accelerated_render(surface,quality,renddesc,&supercb))
582                         return false;
583                 if(get_amount()==0)
584                         return true;
585         }
586
587
588         int x,y;
589
590         Surface::pen pen(surface->begin());
591         const Real pw(renddesc.get_pw()),ph(renddesc.get_ph());
592         Point pos;
593         Point tl(renddesc.get_tl());
594         const int w(surface->get_w());
595         const int h(surface->get_h());
596
597         if(get_amount()==1.0 && get_blend_method()==Color::BLEND_STRAIGHT)
598         {
599                 for(y=0,pos[1]=tl[1];y<h;y++,pen.inc_y(),pen.dec_x(x),pos[1]+=ph)
600                         for(x=0,pos[0]=tl[0];x<w;x++,pen.inc_x(),pos[0]+=pw)
601                                 pen.put_value(color_func(pos,quality,calc_supersample(pos,pw,ph)));
602         }
603         else
604         {
605                 for(y=0,pos[1]=tl[1];y<h;y++,pen.inc_y(),pen.dec_x(x),pos[1]+=ph)
606                         for(x=0,pos[0]=tl[0];x<w;x++,pen.inc_x(),pos[0]+=pw)
607                                 pen.put_value(Color::blend(color_func(pos,quality,calc_supersample(pos,pw,ph)),pen.get_value(),get_amount(),get_blend_method()));
608         }
609
610         // Mark our progress as finished
611         if(cb && !cb->amount_complete(10000,10000))
612                 return false;
613
614         return true;
615 }