Multiplying a gradient by zero empties it.
[synfig.git] / synfig-core / trunk / src / synfig / gradient.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file gradient.cpp
3 **      \brief Color Gradient Class Member Definitions
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 /* ========================================================================= */
22
23 /* === H E A D E R S ======================================================= */
24
25 #ifdef USING_PCH
26 #       include "pch.h"
27 #else
28 #ifdef HAVE_CONFIG_H
29 #       include <config.h>
30 #endif
31
32 #include "gradient.h"
33 #include "general.h"
34 #include <stdexcept>
35 #include "exception.h"
36 #include <algorithm>
37
38 #include <ETL/misc>
39 #endif
40
41 /* === U S I N G =========================================================== */
42
43 using namespace std;
44 using namespace etl;
45 using namespace synfig;
46
47 /* === M A C R O S ========================================================= */
48
49 /* === G L O B A L S ======================================================= */
50
51 /* === P R O C E D U R E S ================================================= */
52
53 /* === M E T H O D S ======================================================= */
54
55 synfig::Gradient::Gradient(const Color &c1, const Color &c2)
56 {
57         push_back(CPoint(0.0,c1));
58         push_back(CPoint(1.0,c2));
59 }
60
61 synfig::Gradient::Gradient(const Color &c1, const Color &c2, const Color &c3)
62 {
63         push_back(CPoint(0.0,c1));
64         push_back(CPoint(0.5,c2));
65         push_back(CPoint(1.0,c3));
66 }
67
68 // This sort algorithm MUST be stable
69 // ie: it must not change the order of items with the same value.
70 // I am using a bubble sort.
71 // This algorithm will sort a nearly-sorted list at ~O(N), and
72 // it will sort an inverse sorted list at ~O(N*N).
73 void
74 synfig::Gradient::sort()
75 {
76         stable_sort(begin(),end());
77         /*
78         iterator iter;
79         iterator iter2,next;
80
81         for(iter=begin();iter!=end();iter++)
82         {
83                 for(next=iter, iter2=next--;iter2!=begin();iter2=next--)
84                 {
85                         if(*iter<*next)
86                         {
87                                 //insert(next,*iter);
88                                 //erase(iter);
89                                 iter_swap(next,iter);
90
91                                 continue;
92                         }
93                         else
94                                 break;
95                 }
96         }
97         */
98 }
99
100 static synfig::ColorAccumulator
101 supersample_helper(const synfig::Gradient::CPoint &color1, const synfig::Gradient::CPoint &color2, float begin, float end, float &weight)
102 {
103         if(color1.pos==color2.pos || color1.pos>=end || color2.pos<=begin)
104         {
105                 weight=0;
106                 return Color::alpha();
107         }
108         if(color1.pos>=begin && color2.pos<end)
109         {
110                 weight=color2.pos-color1.pos;
111                 ColorAccumulator ret=Color::blend(color2.color,color1.color, 0.5, Color::BLEND_STRAIGHT).premult_alpha()*weight;
112                 return ret;
113         }
114         if(color1.pos>=begin && color2.pos>=end)
115         {
116                 weight=end-color1.pos;
117                 float pos((end+color1.pos)*0.5);
118                 float amount((pos-color1.pos)/(color2.pos-color1.pos));
119                 //if(abs(amount)>1)amount=(amount>0)?1:-1;
120                 ColorAccumulator ret(Color::blend(color2.color,color1.color, amount, Color::BLEND_STRAIGHT).premult_alpha()*weight);
121                 return ret;
122         }
123         if(color1.pos<begin && color2.pos<end)
124         {
125                 weight=color2.pos-begin;
126                 float pos((begin+color2.pos)*0.5);
127                 float amount((pos-color1.pos)/(color2.pos-color1.pos));
128                 //if(abs(amount)>1)amount=(amount>0)?1:-1;
129                 ColorAccumulator ret(Color::blend(color2.color,color1.color, amount, Color::BLEND_STRAIGHT).premult_alpha()*weight);
130                 return ret;
131         }
132         synfig::error("color1.pos=%f",color1.pos);
133         synfig::error("color2.pos=%f",color2.pos);
134         synfig::error("begin=%f",begin);
135         synfig::error("end=%f",end);
136
137         weight=0;
138         return Color::alpha();
139
140 //      assert(0);
141 }
142
143 Gradient &
144 synfig::Gradient::operator+=(const Gradient &rhs)
145 {
146         CPointList ret;
147         const_iterator iter1 = begin(), iter2 = rhs.begin(), left_same, right_same;
148         CPoint left, right;
149         if (iter1 != end()) left = *iter1;
150         if (iter2 != rhs.end()) right = *iter2;
151         if (iter1 != end() && iter2 != rhs.end())
152                 while(true)
153                 {
154                         if (left.pos < right.pos)
155                         {
156                                 ret.push_back(CPoint(left.pos, left.color + rhs(left.pos)));
157                                 if(++iter1 == end()) break;
158                                 left=*iter1;
159                         }
160                         else if (left.pos > right.pos)
161                         {
162                                 ret.push_back(CPoint(right.pos, right.color + (*this)(right.pos)));
163                                 if(++iter2 == rhs.end()) break;
164                                 right=*iter2;
165                         }
166                         else
167                         {
168                                 for(left_same = iter1++; (*iter1).pos == left.pos; iter1++);
169                                 for(right_same = iter2++; (*iter2).pos == right.pos; iter2++);
170                                 if (iter1 == left_same+1 && iter2 == right_same+1)
171                                         ret.push_back(CPoint(left.pos, left.color + right.color));
172                                 else
173                                 {
174                                         ret.push_back(CPoint(left.pos, left.color + right.color));
175                                         ret.push_back(CPoint(left.pos, (*(iter1-1)).color + (*(iter2-1)).color));
176                                 }
177                                 if (iter1 != end()) left=*iter1;
178                                 if (iter2 == rhs.end()) break;
179                                 right = *iter2;
180                                 if (iter1 == end()) break;
181                         }
182                 }
183
184         if (iter1 != end())
185                 while(true)
186                 {
187                         ret.push_back(CPoint(left.pos, left.color + rhs(left.pos)));
188                         if(++iter1 == end()) break;
189                         left = *iter1;
190                 }
191
192         if (iter2 != rhs.end())
193                 while(true)
194                 {
195                         ret.push_back(CPoint(right.pos, right.color + (*this)(right.pos)));
196                         if(++iter2 == rhs.end()) break;
197                         right = *iter2;
198                 }
199
200         cpoints = ret;
201         return *this;
202 }
203
204 Gradient &
205 synfig::Gradient::operator-=(const Gradient &rhs)
206 {
207         return (*this)+=(rhs*-1);
208 }
209
210 Gradient &
211 synfig::Gradient::operator*=(const float    &rhs)
212 {
213         if (rhs == 0)
214                 cpoints.clear();
215         else
216                 for (iterator iter = cpoints.begin(); iter!=cpoints.end(); iter++)
217                         (*iter).color *= rhs;
218         return *this;
219 }
220
221 Gradient &
222 synfig::Gradient::operator/=(const float    &rhs)
223 {
224         for (iterator iter = cpoints.begin(); iter!=cpoints.end(); iter++)
225                 (*iter).color /= rhs;
226         return *this;
227 }
228
229 Color
230 synfig::Gradient::operator()(const Real &x,float supersample)const
231 {
232         if(cpoints.empty())
233                 return Color(0,0,0,0);
234         if(supersample<0)
235                 supersample=-supersample;
236         if(supersample>2.0)
237                 supersample=2.0f;
238
239         float begin_sample(x-supersample*0.5);
240         float end_sample(x+supersample*0.5);
241
242         if(cpoints.size()==1 || end_sample<=cpoints.front().pos || isnan(x))
243                 return cpoints.front().color;
244
245         if(begin_sample>=cpoints.back().pos)
246                 return cpoints.back().color;
247
248         /*
249         if(end_sample>=back().pos)
250                 end_sample=back().pos;
251
252         if(begin_sample<=front().pos)
253                 begin_sample=front().pos;
254         */
255
256         const_iterator iter,next;
257
258         /*
259         //optimizize...
260         Real    left = x-supersample/2, right = x+supersample/2;
261
262         if(left < front().pos) left = front().pos;
263         if(right > back().pos) right = back().pos;
264
265         //find using binary search...
266         const_iterator iterl,iterr;
267
268         //the binary search should give us the values BEFORE the point we're looking for...
269         iterl = binary_find(begin(),end(),left);
270         iterr = binary_find(iterl,end(),right);
271
272         //now integrate over the range of left to right...
273
274         if(iterl == iterr)
275         {
276                 iterr++; //let's look at the next one shall we :)
277
278                 //interpolate neighboring colors
279                 const Real one = iterr->pos - iterl->pos;
280                 const Real lambda = (x - iterl->pos)/one;
281
282                 //(1-l)iterl + (l)iterr
283                 return iterl->color.premult_alpha()*(1-lambda) + iterr->color.premult_alpha()*lambda;
284
285                 //return Color::blend(iterr->color,iterl->color,lambda,Color::BLEND_STRAIGHT);
286         }else
287         {
288                 //itegration madness
289                 const_iterator i = iterl, ie = iterr+1;
290                 Real wlast = left;
291
292                 ColorAccumulator clast,cwork;
293                 {
294                         const Real lambda = (x - iterl->pos)/(iterr->pos - iterl->pos);
295
296                         //premultiply because that's the form in which we can combine things...
297                         clast = iterl->color.premult_alpha()*(1-lambda) + iterr->color.premult_alpha()*lambda;
298                         //Color::blend((i+1)->color,i->color,(left - i->pos)/((i+1)->pos - i->pos),Color::BLEND_STRAIGHT);
299                 }
300
301                 ColorAccumulator        accum = 0;
302
303                 //loop through all the trapezoids and integrate them as we go...
304                 //      area of trap = (yi + yi1)*(xi1 - xi)
305                 //      yi = clast, xi = wlast, yi1 = i->color, xi1 = i->pos
306
307                 for(;i<=iterr; wlast=i->pos,clast=i->color.premult_alpha(),++i)
308                 {
309                         const Real diff = i->pos - wlast;
310                         if(diff > 0) //only accumulate if there will be area to add
311                         {
312                                 cwork = i->color.premult_alpha();
313                                 accum += (cwork + clast)*diff;
314                         }
315                 }
316
317                 {
318                         const_iterator ibef = i-1;
319                         const Real diff = right - ibef->pos;
320
321                         if(diff > 0)
322                         {
323                                 const Real lambda = diff/(i->pos - ibef->pos);
324                                 cwork = ibef->color.premult_alpha()*(1-lambda) + i->color.premult_alpha()*lambda;
325
326                                 accum += (cwork + clast)*diff; //can probably optimize this more... but it's not too bad
327                         }
328                 }
329
330                 accum /= supersample; //should be the total area it was sampled over...
331                 return accum.demult_alpha();
332         }*/
333
334         next=begin(),iter=next++;
335
336         //add for optimization
337         next = binary_find(begin(),end(),(Real)begin_sample);
338         iter = next++;
339
340         //! As a future optimization, this could be performed faster
341         //! using a binary search.
342         for(;iter<end();iter=next++)
343         {
344                 if(next==end() || x>=iter->pos &&  x<next->pos && iter->pos!=next->pos)
345                 {
346                         // If the supersample region falls square in between
347                         // two CPoints, then we don't have to do anything special.
348                         if(next!=end() && (!supersample || (iter->pos<=begin_sample && next->pos>=end_sample)))
349                         {
350                                 const Real dist(next->pos-iter->pos);
351                                 const Real pos(x-iter->pos);
352                                 const Real amount(pos/dist);
353                                 return Color::blend(next->color,iter->color, amount, Color::BLEND_STRAIGHT);
354                         }
355                         // In this case our supersample region extends over one or more
356                         // CPoints. So, we need to calculate our coverage amount.
357                         ColorAccumulator pool(Color::alpha());
358                         float divisor(0.0),weight(0);
359
360                         const_iterator iter2,next2;
361                         iter2=iter;
362                         if(iter==begin() && iter->pos>x)
363                         {
364                                 weight=x-iter->pos;
365                                 //weight*=iter->color.get_a();
366                                 pool+=ColorAccumulator(iter->color).premult_alpha()*weight;
367                                 divisor+=weight;
368                         }
369                         else
370                         {
371                                 while(iter2->pos>=begin_sample)
372                                 {
373                                         if(iter2==begin())
374                                         {
375                                                 weight=iter2->pos-(begin_sample);
376                                                 //weight*=iter2->color.get_a();
377                                                 pool+=ColorAccumulator(iter2->color).premult_alpha()*weight;
378                                                 divisor+=weight;
379                                                 break;
380                                         }
381                                         next2=iter2--;
382                                         pool+=supersample_helper(*iter2, *next2, begin_sample, end_sample, weight);
383                                         divisor+=weight;
384                                 }
385                         }
386
387                         next2=iter;
388                         iter2=next2++;
389                         while(iter2->pos<=end_sample)
390                         {
391                                 if(next2==end())
392                                 {
393                                         weight=(end_sample)-iter2->pos;
394                                         pool+=ColorAccumulator(iter2->color).premult_alpha()*weight;
395                                         divisor+=weight;
396                                         break;
397                                 }
398                                 pool+=supersample_helper(*iter2, *next2, begin_sample, end_sample, weight);
399                                 divisor+=weight;
400                                 iter2=next2++;
401                         }
402
403                         if(divisor && pool.get_a() && pool.is_valid())
404                         {
405 /*
406                                 pool.set_r(pool.get_r()/pool.get_a());
407                                 pool.set_g(pool.get_g()/pool.get_a());
408                                 pool.set_b(pool.get_b()/pool.get_a());
409                                 pool.set_a(pool.get_a()/divisor);
410 */
411                                 pool/=divisor;
412                                 pool.set_r(pool.get_r()/pool.get_a());
413                                 pool.set_g(pool.get_g()/pool.get_a());
414                                 pool.set_b(pool.get_b()/pool.get_a());
415                                 if(pool.is_valid())
416                                         return pool;
417                                 else
418                                         return Color::alpha();
419                         }
420                         else
421                                 return Color::alpha();
422                 }
423         }
424
425         // We should never get to this point.
426
427         synfig::error("synfig::Gradient::operator()(): Logic Error (x=%f)",x);
428         assert(0);
429         throw std::logic_error(strprintf("synfig::Gradient::operator()(): Logic Error (x=%f)",x));
430 }
431
432 synfig::Gradient::iterator
433 synfig::Gradient::proximity(const Real &x)
434 {
435         iterator iter;
436         float dist(100000000);
437         float prev_pos(-0230);
438         // This algorithm requires a sorted list.
439         for(iter=begin();iter<end();iter++)
440         {
441                 float new_dist;
442
443                 if(prev_pos==iter->pos)
444                         new_dist=(abs(x-iter->pos-0.00001));
445                 else
446                         new_dist=(abs(x-iter->pos));
447
448                 if(new_dist>dist)
449                 {
450                         iter--;
451                         return iter;
452                 }
453                 dist=new_dist;
454                 prev_pos=iter->pos;
455         }
456         iter--;
457         return iter;
458 }
459
460 synfig::Gradient::const_iterator
461 synfig::Gradient::proximity(const Real &x)const
462 {
463         return const_cast<Gradient*>(this)->proximity(x);
464         /*
465         const_iterator iter;
466         float dist(100000000);
467
468         // This algorithm requires a sorted list.
469         for(iter=begin();iter<end();iter++)
470         {
471                 const float new_dist(abs(x-iter->pos));
472                 if(new_dist>dist)
473                 {
474                         iter--;
475                         return iter;
476                 }
477                 dist=new_dist;
478         }
479         iter--;
480         return iter;
481         */
482 }
483
484 synfig::Gradient::iterator
485 synfig::Gradient::find(const UniqueID &id)
486 {
487         iterator iter;
488
489         for(iter=begin();iter<end();iter++)
490         {
491                 if(id==*iter)
492                         return iter;
493         }
494
495         throw Exception::NotFound("synfig::Gradient::find(): Unable to find UniqueID in gradient");
496 }
497
498 synfig::Gradient::const_iterator
499 synfig::Gradient::find(const UniqueID &id)const
500 {
501         const_iterator iter;
502
503         for(iter=begin();iter<end();iter++)
504         {
505                 if(id==*iter)
506                         return iter;
507         }
508
509         throw Exception::NotFound("synfig::Gradient::find()const: Unable to find UniqueID in gradient");
510 }