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