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