Merge branch 'master' into genete_core_review
[synfig.git] / synfig-core / 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         Layer_Composite(1.0,Color::BLEND_COMPOSITE),
209         origin(0,0),
210         width(0.25),
211         gradient(Color::black(), Color::white()),
212         loop(false),
213         zigzag(false),
214         perpendicular(false),
215         fast(true)
216 {
217         bline.push_back(BLinePoint());
218         bline.push_back(BLinePoint());
219         bline.push_back(BLinePoint());
220         bline[0].set_vertex(Point(0,1));
221         bline[1].set_vertex(Point(0,-1));
222         bline[2].set_vertex(Point(1,0));
223         bline[0].set_tangent(bline[1].get_vertex()-bline[2].get_vertex()*0.5f);
224         bline[1].set_tangent(bline[2].get_vertex()-bline[0].get_vertex()*0.5f);
225         bline[2].set_tangent(bline[0].get_vertex()-bline[1].get_vertex()*0.5f);
226         bline[0].set_width(1.0f);
227         bline[1].set_width(1.0f);
228         bline[2].set_width(1.0f);
229         bline_loop=true;
230
231         sync();
232 }
233
234 inline Color
235 CurveGradient::color_func(const Point &point_, int quality, float supersample)const
236 {
237         Vector tangent;
238         Vector diff;
239         Point p1;
240         Real thickness;
241         Real dist;
242
243         float perp_dist;
244         bool edge_case = false;
245
246         if(bline.size()==0)
247                 return Color::alpha();
248         else if(bline.size()==1)
249         {
250                 tangent=bline.front().get_tangent1();
251                 p1=bline.front().get_vertex();
252                 thickness=bline.front().get_width();
253         }
254         else
255         {
256                 float t;
257                 Point point(point_-origin);
258
259                 std::vector<synfig::BLinePoint>::const_iterator iter,next;
260
261                 // Figure out the BLinePoints we will be using,
262                 // Taking into account looping.
263                 if(perpendicular)
264                 {
265                         next=find_closest(fast,bline,point,t,bline_loop,&perp_dist);
266                         perp_dist/=curve_length_;
267                 }
268                 else                                    // not perpendicular
269                 {
270                         next=find_closest(fast,bline,point,t,bline_loop);
271                 }
272
273                 iter=next++;
274                 if(next==bline.end()) next=bline.begin();
275
276                 // Setup the curve
277                 etl::hermite<Vector> curve(
278                         iter->get_vertex(),
279                         next->get_vertex(),
280                         iter->get_tangent2(),
281                         next->get_tangent1()
282                         );
283
284                 // Setup the derivative function
285                 etl::derivative<etl::hermite<Vector> > deriv(curve);
286
287                 int search_iterations(7);
288
289                 /*if(quality==0)search_iterations=8;
290                   else if(quality<=2)search_iterations=10;
291                   else if(quality<=4)search_iterations=8;
292                 */
293                 if(perpendicular)
294                 {
295                         if(quality>7)
296                                 search_iterations=4;
297                 }
298                 else                                    // not perpendicular
299                 {
300                         if(quality<=6)search_iterations=7;
301                         else if(quality<=7)search_iterations=6;
302                         else if(quality<=8)search_iterations=5;
303                         else search_iterations=4;
304                 }
305
306                 // Figure out the closest point on the curve
307                 if (fast)
308                         t = curve.find_closest(fast, point,search_iterations);
309
310                 // Calculate our values
311                 p1=curve(t);                     // the closest point on the curve
312                 tangent=deriv(t);                // the tangent at that point
313
314                 // if the point we're nearest to is at either end of the
315                 // bline, our distance from the curve is the distance from the
316                 // point on the curve.  we need to know which side of the
317                 // curve we're on, so find the average of the two tangents at
318                 // this point
319                 if (t<0.00001 || t>0.99999)
320                 {
321                         bool zero_tangent = (tangent[0] == 0 && tangent[1] == 0);
322
323                         if (t<0.5)
324                         {
325                                 if (iter->get_split_tangent_flag() || zero_tangent)
326                                 {
327                                         // fake the current tangent if we need to
328                                         if (zero_tangent) tangent = curve(FAKE_TANGENT_STEP) - curve(0);
329
330                                         // calculate the other tangent
331                                         Vector other_tangent(iter->get_tangent1());
332                                         if (other_tangent[0] == 0 && other_tangent[1] == 0)
333                                         {
334                                                 // find the previous blinepoint
335                                                 std::vector<synfig::BLinePoint>::const_iterator prev;
336                                                 if (iter != bline.begin()) (prev = iter)--;
337                                                 else if (loop) (prev = bline.end())--;
338                                                 else prev = iter;
339
340                                                 etl::hermite<Vector> other_curve(prev->get_vertex(), iter->get_vertex(), prev->get_tangent2(), iter->get_tangent1());
341                                                 other_tangent = other_curve(1) - other_curve(1-FAKE_TANGENT_STEP);
342                                         }
343
344                                         // normalise and sum the two tangents
345                                         tangent=(other_tangent.norm()+tangent.norm());
346                                         edge_case=true;
347                                 }
348                         }
349                         else
350                         {
351                                 if (next->get_split_tangent_flag() || zero_tangent)
352                                 {
353                                         // fake the current tangent if we need to
354                                         if (zero_tangent) tangent = curve(1) - curve(1-FAKE_TANGENT_STEP);
355
356                                         // calculate the other tangent
357                                         Vector other_tangent(next->get_tangent2());
358                                         if (other_tangent[0] == 0 && other_tangent[1] == 0)
359                                         {
360                                                 // find the next blinepoint
361                                                 std::vector<synfig::BLinePoint>::const_iterator next2(next);
362                                                 if (++next2 == bline.end())
363                                                 {
364                                                         if (loop) next2 = bline.begin();
365                                                         else next2 = next;
366                                                 }
367
368                                                 etl::hermite<Vector> other_curve(next->get_vertex(), next2->get_vertex(), next->get_tangent2(), next2->get_tangent1());
369                                                 other_tangent = other_curve(FAKE_TANGENT_STEP) - other_curve(0);
370                                         }
371
372                                         // normalise and sum the two tangents
373                                         tangent=(other_tangent.norm()+tangent.norm());
374                                         edge_case=true;
375                                 }
376                         }
377                 }
378                 tangent = tangent.norm();
379
380                 if(perpendicular)
381                 {
382                         tangent*=curve_length_;
383                         p1-=tangent*perp_dist;
384                         tangent=-tangent.perp();
385                 }
386                 else                                    // not perpendicular
387                         // the width of the bline at the closest point on the curve
388                         thickness=(next->get_width()-iter->get_width())*t+iter->get_width();
389         }
390
391         if(perpendicular)
392         {
393                 if(quality>7)
394                 {
395                         dist=perp_dist;
396 /*                      diff=tangent.perp();
397                         const Real mag(diff.inv_mag());
398                         supersample=supersample*mag;
399 */
400                         supersample=0;
401                 }
402                 else
403                 {
404                         diff=tangent.perp();
405                         //p1-=diff*0.5;
406                         const Real mag(diff.inv_mag());
407                         supersample=supersample*mag;
408                         diff*=mag*mag;
409                         dist=(point_-origin - p1)*diff;
410                 }
411         }
412         else                                            // not perpendicular
413         {
414                 if (edge_case)
415                 {
416                         diff=(p1-(point_-origin));
417                         if(diff*tangent.perp()<0) diff=-diff;
418                         diff=diff.norm()*thickness*width;
419                 }
420                 else
421                         diff=tangent.perp()*thickness*width;
422
423                 p1-=diff*0.5;
424                 const Real mag(diff.inv_mag());
425                 supersample=supersample*mag;
426                 diff*=mag*mag;
427                 dist=(point_-origin - p1)*diff;
428         }
429
430         if(loop)
431                 dist-=floor(dist);
432
433         if(zigzag)
434         {
435                 dist*=2.0;
436                 supersample*=2.0;
437                 if(dist>1)dist=2.0-dist;
438         }
439
440         if(loop)
441         {
442                 if(dist+supersample*0.5>1.0)
443                 {
444                         float  left(supersample*0.5-(dist-1.0));
445                         float right(supersample*0.5+(dist-1.0));
446                         Color pool(gradient(1.0-(left*0.5),left).premult_alpha()*left/supersample);
447                         if (zigzag) pool+=gradient(1.0-right*0.5,right).premult_alpha()*right/supersample;
448                         else            pool+=gradient(right*0.5,right).premult_alpha()*right/supersample;
449                         return pool.demult_alpha();
450                 }
451                 if(dist-supersample*0.5<0.0)
452                 {
453                         float  left(supersample*0.5-dist);
454                         float right(supersample*0.5+dist);
455                         Color pool(gradient(right*0.5,right).premult_alpha()*right/supersample);
456                         if (zigzag) pool+=gradient(left*0.5,left).premult_alpha()*left/supersample;
457                         else            pool+=gradient(1.0-left*0.5,left).premult_alpha()*left/supersample;
458                         return pool.demult_alpha();
459                 }
460         }
461         return gradient(dist,supersample);
462 }
463
464 float
465 CurveGradient::calc_supersample(const synfig::Point &/*x*/, float pw,float /*ph*/)const
466 {
467         return pw;
468 }
469
470 synfig::Layer::Handle
471 CurveGradient::hit_check(synfig::Context context, const synfig::Point &point)const
472 {
473         if(get_blend_method()==Color::BLEND_STRAIGHT && get_amount()>=0.5)
474                 return const_cast<CurveGradient*>(this);
475         if(get_amount()==0.0)
476                 return context.hit_check(point);
477         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)
478                 return const_cast<CurveGradient*>(this);
479         return context.hit_check(point);
480 }
481
482 bool
483 CurveGradient::set_param(const String & param, const ValueBase &value)
484 {
485
486
487         IMPORT(origin);
488         IMPORT(perpendicular);
489         IMPORT(fast);
490
491         if(param=="bline" && value.get_type()==ValueBase::TYPE_LIST)
492         {
493                 bline=value;
494                 bline_loop=value.get_loop();
495                 sync();
496
497                 return true;
498         }
499
500         IMPORT(width);
501         IMPORT(gradient);
502         IMPORT(loop);
503         IMPORT(zigzag);
504
505         IMPORT_AS(origin,"offset");
506
507         return Layer_Composite::set_param(param,value);
508 }
509
510 ValueBase
511 CurveGradient::get_param(const String & param)const
512 {
513         EXPORT(origin);
514         EXPORT(bline);
515         EXPORT(gradient);
516         EXPORT(loop);
517         EXPORT(zigzag);
518         EXPORT(width);
519         EXPORT(perpendicular);
520         EXPORT(fast);
521
522         EXPORT_NAME();
523         EXPORT_VERSION();
524
525         return Layer_Composite::get_param(param);
526 }
527
528 Layer::Vocab
529 CurveGradient::get_param_vocab()const
530 {
531         Layer::Vocab ret(Layer_Composite::get_param_vocab());
532
533         ret.push_back(ParamDesc("origin")
534                                   .set_local_name(_("Origin")));
535
536         ret.push_back(ParamDesc("width")
537                                   .set_is_distance()
538                                   .set_local_name(_("Width")));
539
540         ret.push_back(ParamDesc("bline")
541                                   .set_local_name(_("Vertices"))
542                                   .set_origin("origin")
543                                   .set_hint("width")
544                                   .set_description(_("A list of BLine Points")));
545
546         ret.push_back(ParamDesc("gradient")
547                                   .set_local_name(_("Gradient")));
548         ret.push_back(ParamDesc("loop")
549                                   .set_local_name(_("Loop")));
550         ret.push_back(ParamDesc("zigzag")
551                                   .set_local_name(_("ZigZag")));
552         ret.push_back(ParamDesc("perpendicular")
553                                   .set_local_name(_("Perpendicular")));
554         ret.push_back(ParamDesc("fast")
555                                   .set_local_name(_("Fast")));
556
557         return ret;
558 }
559
560 Color
561 CurveGradient::get_color(Context context, const Point &point)const
562 {
563         const Color color(color_func(point,0));
564
565         if(get_amount()==1.0 && get_blend_method()==Color::BLEND_STRAIGHT)
566                 return color;
567         else
568                 return Color::blend(color,context.get_color(point),get_amount(),get_blend_method());
569 }
570
571 bool
572 CurveGradient::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
573 {
574         SuperCallback supercb(cb,0,9500,10000);
575
576         if(get_amount()==1.0 && get_blend_method()==Color::BLEND_STRAIGHT)
577         {
578                 surface->set_wh(renddesc.get_w(),renddesc.get_h());
579         }
580         else
581         {
582                 if(!context.accelerated_render(surface,quality,renddesc,&supercb))
583                         return false;
584                 if(get_amount()==0)
585                         return true;
586         }
587
588
589         int x,y;
590
591         Surface::pen pen(surface->begin());
592         const Real pw(renddesc.get_pw()),ph(renddesc.get_ph());
593         Point pos;
594         Point tl(renddesc.get_tl());
595         const int w(surface->get_w());
596         const int h(surface->get_h());
597
598         if(get_amount()==1.0 && get_blend_method()==Color::BLEND_STRAIGHT)
599         {
600                 for(y=0,pos[1]=tl[1];y<h;y++,pen.inc_y(),pen.dec_x(x),pos[1]+=ph)
601                         for(x=0,pos[0]=tl[0];x<w;x++,pen.inc_x(),pos[0]+=pw)
602                                 pen.put_value(color_func(pos,quality,calc_supersample(pos,pw,ph)));
603         }
604         else
605         {
606                 for(y=0,pos[1]=tl[1];y<h;y++,pen.inc_y(),pen.dec_x(x),pos[1]+=ph)
607                         for(x=0,pos[0]=tl[0];x<w;x++,pen.inc_x(),pos[0]+=pw)
608                                 pen.put_value(Color::blend(color_func(pos,quality,calc_supersample(pos,pw,ph)),pen.get_value(),get_amount(),get_blend_method()));
609         }
610
611         // Mark our progress as finished
612         if(cb && !cb->amount_complete(10000,10000))
613                 return false;
614
615         return true;
616 }