Add ValueNode "Gradient Color" for selecting individual colors from a gradient.
[synfig.git] / synfig-core / trunk / src / synfig / valuenode.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file valuenode.cpp
3 **      \brief Implementation of the "Placeholder" valuenode conversion.
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 /* ========================================================================= */
23
24 /* === H E A D E R S ======================================================= */
25
26 #define SYNFIG_NO_ANGLE
27
28 //#define HAS_HASH_MAP 1
29
30 #ifdef USING_PCH
31 #       include "pch.h"
32 #else
33 #ifdef HAVE_CONFIG_H
34 #       include <config.h>
35 #endif
36
37 #include "valuenode.h"
38 #include "general.h"
39 #include "canvas.h"
40 #include "paramdesc.h"
41 #include "releases.h"
42
43 #include "valuenode_const.h"
44 #include "valuenode_linear.h"
45 #include "valuenode_composite.h"
46 #include "valuenode_reference.h"
47 #include "valuenode_scale.h"
48 #include "valuenode_blinecalctangent.h"
49 #include "valuenode_blinecalcvertex.h"
50 #include "valuenode_blinecalcwidth.h"
51 #include "valuenode_blinereversetangent.h"
52 #include "valuenode_segcalctangent.h"
53 #include "valuenode_segcalcvertex.h"
54 #include "valuenode_repeat_gradient.h"
55 #include "valuenode_stripes.h"
56 #include "valuenode_range.h"
57 #include "valuenode_add.h"
58 #include "valuenode_subtract.h"
59 #include "valuenode_timedswap.h"
60 #include "valuenode_twotone.h"
61 #include "valuenode_bline.h"
62 #include "valuenode_dynamiclist.h"
63 #include "valuenode_radialcomposite.h"
64 #include "valuenode_gradientrotate.h"
65 #include "valuenode_sine.h"
66 #include "valuenode_cos.h"
67 #include "valuenode_atan2.h"
68 #include "valuenode_exp.h"
69 #include "valuenode_switch.h"
70 #include "valuenode_timeloop.h"
71 #include "valuenode_reciprocal.h"
72 #include "valuenode_duplicate.h"
73 #include "valuenode_integer.h"
74 #include "valuenode_step.h"
75 #include "valuenode_vectorangle.h"
76 #include "valuenode_vectorlength.h"
77 #include "valuenode_vectorx.h"
78 #include "valuenode_vectory.h"
79 #include "valuenode_gradientcolor.h"
80
81 #include "layer.h"
82
83 #endif
84
85 /* === U S I N G =========================================================== */
86
87 using namespace std;
88 using namespace etl;
89 using namespace synfig;
90
91 /* === M A C R O S ========================================================= */
92
93 /* === G L O B A L S ======================================================= */
94
95 static int value_node_count(0);
96
97 static LinkableValueNode::Book *book_;
98
99
100 ValueNode::LooseHandle
101 synfig::find_value_node(const GUID& guid)
102 {
103         return guid_cast<ValueNode>(guid);
104 }
105
106 /* === P R O C E D U R E S ================================================= */
107
108 /* === M E T H O D S ======================================================= */
109
110 bool
111 ValueNode::subsys_init()
112 {
113         book_=new LinkableValueNode::Book();
114
115 #define ADD_VALUENODE(class,name,local,version)                                                                                                 \
116         (*book_)[name].factory=reinterpret_cast<LinkableValueNode::Factory>(&class::create);            \
117         (*book_)[name].check_type=&class::check_type;                                                                                           \
118         (*book_)[name].local_name=local;                                                                                                                        \
119         (*book_)[name].release_version=version
120
121 #define ADD_VALUENODE2(class,name,local,version)                                                                                                \
122         (*book_)[name].factory=reinterpret_cast<LinkableValueNode::Factory>(&class::create_from);       \
123         (*book_)[name].check_type=&class::check_type;                                                                                           \
124         (*book_)[name].local_name=local;                                                                                                                        \
125         (*book_)[name].release_version=version
126
127         ADD_VALUENODE(ValueNode_Linear,                   "linear",                       _("Linear"),                   RELEASE_VERSION_0_61_06);
128         ADD_VALUENODE(ValueNode_Composite,                "composite",            _("Composite"),                RELEASE_VERSION_0_61_06);
129         ADD_VALUENODE(ValueNode_RadialComposite,  "radial_composite", _("Radial Composite"), RELEASE_VERSION_0_61_06);
130         ADD_VALUENODE(ValueNode_Reference,                "reference",            _("Reference"),                RELEASE_VERSION_0_61_06);
131         ADD_VALUENODE(ValueNode_Scale,                    "scale",                        _("Scale"),                    RELEASE_VERSION_0_61_06);
132         ADD_VALUENODE(ValueNode_SegCalcTangent,   "segcalctangent",       _("Segment Tangent"),  RELEASE_VERSION_0_61_06);
133         ADD_VALUENODE(ValueNode_SegCalcVertex,    "segcalcvertex",        _("Segment Vertex"),   RELEASE_VERSION_0_61_06);
134         ADD_VALUENODE(ValueNode_Stripes,                  "stripes",              _("Stripes"),                  RELEASE_VERSION_0_61_06);
135         ADD_VALUENODE(ValueNode_Subtract,                 "subtract",             _("Subtract"),                 RELEASE_VERSION_0_61_06);
136         ADD_VALUENODE(ValueNode_TwoTone,                  "twotone",              _("Two-Tone"),                 RELEASE_VERSION_0_61_06);
137         ADD_VALUENODE(ValueNode_BLine,                    "bline",                        _("BLine"),                    RELEASE_VERSION_0_61_06);
138         ADD_VALUENODE2(ValueNode_DynamicList,     "dynamic_list",         _("Dynamic List"),     RELEASE_VERSION_0_61_06);
139         ADD_VALUENODE(ValueNode_GradientRotate,   "gradient_rotate",  _("Gradient Rotate"),      RELEASE_VERSION_0_61_06);
140         ADD_VALUENODE(ValueNode_Sine,                     "sine",                         _("Sine"),                     RELEASE_VERSION_0_61_06);
141
142         ADD_VALUENODE(ValueNode_TimedSwap,                "timed_swap",           _("Timed Swap"),               RELEASE_VERSION_0_61_07); // SVN r610
143         ADD_VALUENODE(ValueNode_Repeat_Gradient,  "repeat_gradient",  _("Repeat Gradient"),      RELEASE_VERSION_0_61_07); // SVN r666
144         ADD_VALUENODE(ValueNode_Exp,                      "exp",                          _("Exponential"),              RELEASE_VERSION_0_61_07); // SVN r739
145         ADD_VALUENODE(ValueNode_Add,                      "add",                          _("Add"),                              RELEASE_VERSION_0_61_07); // SVN r742
146         ADD_VALUENODE(ValueNode_BLineCalcTangent, "blinecalctangent", _("BLine Tangent"),        RELEASE_VERSION_0_61_07); // SVN r744
147         ADD_VALUENODE(ValueNode_BLineCalcVertex,  "blinecalcvertex",  _("BLine Vertex"),         RELEASE_VERSION_0_61_07); // SVN r744
148         ADD_VALUENODE(ValueNode_Range,                    "range",                        _("Range"),                    RELEASE_VERSION_0_61_07); // SVN r776
149
150         ADD_VALUENODE(ValueNode_Switch,                   "switch",                       _("Switch"),                   RELEASE_VERSION_0_61_08); // SVN r923
151         ADD_VALUENODE(ValueNode_Cos,                      "cos",                          _("Cos"),                              RELEASE_VERSION_0_61_08); // SVN r1111
152         ADD_VALUENODE(ValueNode_Atan2,                    "atan2",                        _("aTan2"),                    RELEASE_VERSION_0_61_08); // SVN r1132
153         ADD_VALUENODE(ValueNode_BLineRevTangent,  "blinerevtangent",  _("Reverse Tangent"),      RELEASE_VERSION_0_61_08); // SVN r1162
154         ADD_VALUENODE(ValueNode_TimeLoop,                 "timeloop",             _("Time Loop"),                RELEASE_VERSION_0_61_08); // SVN r1226
155         ADD_VALUENODE(ValueNode_Reciprocal,               "reciprocal",           _("Reciprocal"),               RELEASE_VERSION_0_61_08); // SVN r1238
156         ADD_VALUENODE(ValueNode_Duplicate,                "duplicate",            _("Duplicate"),                RELEASE_VERSION_0_61_08); // SVN r1267
157         ADD_VALUENODE(ValueNode_Integer,                  "fromint",              _("From Integer"),     RELEASE_VERSION_0_61_08); // SVN r1267
158         ADD_VALUENODE(ValueNode_Step,                     "step",                         _("Step"),                     RELEASE_VERSION_0_61_08); // SVN r1691
159         ADD_VALUENODE(ValueNode_BLineCalcWidth,   "blinecalcwidth",       _("BLine Width"),              RELEASE_VERSION_0_61_08); // SVN r1694
160
161         ADD_VALUENODE(ValueNode_VectorAngle,      "vectorangle",          _("Vector Angle"),     RELEASE_VERSION_0_61_09); // SVN r1880
162         ADD_VALUENODE(ValueNode_VectorLength,     "vectorlength",         _("Vector Length"),    RELEASE_VERSION_0_61_09); // SVN r1881
163         ADD_VALUENODE(ValueNode_VectorX,                  "vectorx",              _("Vector X"),                 RELEASE_VERSION_0_61_09); // SVN r1882
164         ADD_VALUENODE(ValueNode_VectorY,                  "vectory",              _("Vector Y"),                 RELEASE_VERSION_0_61_09); // SVN r1882
165         ADD_VALUENODE(ValueNode_GradientColor,    "gradientcolor",        _("Gradient Color"),   RELEASE_VERSION_0_61_09); // SVN r1885
166
167 #undef ADD_VALUENODE
168 #undef ADD_VALUENODE2
169
170         return true;
171 }
172
173 bool
174 ValueNode::subsys_stop()
175 {
176         delete book_;
177 /*      if(global_value_node_map.size() || value_node_count)
178         {
179                 if(value_node_count)
180                         synfig::error("%d ValueNodes haven't been destroyed yet!",value_node_count);
181
182                 if(global_value_node_map.size()!=value_node_count)
183                         synfig::error("value node count mismatch! map.size()!=value_node_count (%d!=%d)",global_value_node_map.size(),value_node_count);
184
185                 GlobalValueNodeMap::iterator iter;
186                 for(iter=global_value_node_map.begin();iter!=global_value_node_map.end();++iter)
187                 {
188                         if(!iter->second->is_exported())
189                                 synfig::info(_("%s: count:%d name:%s type:%s"),
190                                         iter->first.get_string().c_str(),
191                                         iter->second->count(),
192                                         iter->second->get_name().c_str(),
193                                         ValueBase::type_local_name(iter->second->get_type()).c_str()
194                                 );
195                         else
196                                 synfig::info(_("%s: id:%s count:%d name:%s type:%s"),
197                                         iter->first.get_string().c_str(),
198                                         iter->second->get_id().c_str(),
199                                         iter->second->count(),
200                                         iter->second->get_name().c_str(),
201                                         ValueBase::type_local_name(iter->second->get_type()).c_str()
202                                 );
203                 }
204         }
205 */
206         return true;
207 }
208
209 ValueNode::ValueNode(ValueBase::Type type):type(type)
210 {
211         value_node_count++;
212 }
213
214 LinkableValueNode::Book&
215 LinkableValueNode::book()
216 {
217         return *book_;
218 }
219
220 LinkableValueNode::Handle
221 LinkableValueNode::create(const String &name, const ValueBase& x)
222 {
223         if(!book().count(name))
224                 return 0;
225
226         if (!check_type(name, x.get_type()) &&
227                 // the Duplicate ValueNode is an exception - we don't want the
228                 // user creating it for themselves, so check_type() fails for
229                 // it even when it is valid
230                 !(name == "duplicate" && x.get_type() == ValueBase::TYPE_REAL))
231         {
232                 error(_("Bad type: ValueNode '%s' doesn't accept type '%s'"), book()[name].local_name.c_str(), ValueBase::type_local_name(x.get_type()).c_str());
233                 return 0;
234         }
235
236         return book()[name].factory(x);
237 }
238
239 bool
240 LinkableValueNode::check_type(const String &name, ValueBase::Type x)
241 {
242         if(!book().count(name) || !book()[name].check_type)
243                 return false;
244         return book()[name].check_type(x);
245 }
246
247 bool
248 LinkableValueNode::set_link(int i,ValueNode::Handle x)
249 {
250         ValueNode::Handle previous(get_link(i));
251
252         if(set_link_vfunc(i,x))
253         {
254                 if(previous)
255                         remove_child(previous.get());
256                 add_child(x.get());
257
258                 if(!x->is_exported() && get_parent_canvas())
259                 {
260                         x->set_parent_canvas(get_parent_canvas());
261                 }
262                 changed();
263                 return true;
264         }
265         return false;
266 }
267
268 ValueNode::LooseHandle
269 LinkableValueNode::get_link(int i)const
270 {
271         return get_link_vfunc(i);
272 }
273
274 void
275 LinkableValueNode::unlink_all()
276 {
277         for(int i=0;i<link_count();i++)
278         {
279                 ValueNode::LooseHandle value_node(get_link(i));
280                 if(value_node)
281                         value_node->parent_set.erase(this);
282         }
283 }
284
285 ValueNode::~ValueNode()
286 {
287         value_node_count--;
288
289         begin_delete();
290 }
291
292 void
293 ValueNode::on_changed()
294 {
295         etl::loose_handle<Canvas> parent_canvas = get_parent_canvas();
296         if(parent_canvas)
297                 do                                              // signal to all the ancestor canvases
298                         parent_canvas->signal_value_node_changed()(this);
299                 while (parent_canvas = parent_canvas->parent());
300         else if(get_root_canvas())
301                 get_root_canvas()->signal_value_node_changed()(this);
302
303         Node::on_changed();
304 }
305
306 int
307 ValueNode::replace(etl::handle<ValueNode> x)
308 {
309         if(x.get()==this)
310                 return 0;
311
312         while(parent_set.size())
313         {
314                 (*parent_set.begin())->add_child(x.get());
315                 (*parent_set.begin())->remove_child(this);
316                 //x->parent_set.insert(*parent_set.begin());
317                 //parent_set.erase(parent_set.begin());
318         }
319         int r(RHandle(this).replace(x));
320         x->changed();
321         return r;
322 }
323
324 void
325 ValueNode::set_id(const String &x)
326 {
327         if(name!=x)
328         {
329                 name=x;
330                 signal_id_changed_();
331         }
332 }
333
334 String
335 ValueNode::get_description(bool show_exported_name)const
336 {
337         String ret(_("ValueNode"));
338
339         if (dynamic_cast<const LinkableValueNode*>(this))
340                 return (dynamic_cast<const LinkableValueNode*>(this))->get_description(-1, show_exported_name);
341
342         if (show_exported_name && !is_exported())
343                 show_exported_name = false;
344
345         if (show_exported_name)
346                 ret += strprintf(" (%s)", get_id().c_str());
347
348         return ret;
349 }
350
351 ValueNodeList::ValueNodeList():
352         placeholder_count_(0)
353 {
354 }
355
356 bool
357 ValueNodeList::count(const String &id)const
358 {
359         const_iterator iter;
360
361         if(id.empty())
362                 return false;
363
364         for(iter=begin();iter!=end() && id!=(*iter)->get_id();++iter)
365                 ;
366
367         if(iter==end())
368                 return false;
369
370         return true;
371 }
372
373 ValueNode::Handle
374 ValueNodeList::find(const String &id)
375 {
376         iterator iter;
377
378         if(id.empty())
379                 throw Exception::IDNotFound("Empty ID");
380
381         for(iter=begin();iter!=end() && id!=(*iter)->get_id();++iter)
382                 ;
383
384         if(iter==end())
385                 throw Exception::IDNotFound("ValueNode in ValueNodeList: "+id);
386
387         return *iter;
388 }
389
390 ValueNode::ConstHandle
391 ValueNodeList::find(const String &id)const
392 {
393         const_iterator iter;
394
395         if(id.empty())
396                 throw Exception::IDNotFound("Empty ID");
397
398         for(iter=begin();iter!=end() && id!=(*iter)->get_id();++iter)
399                 ;
400
401         if(iter==end())
402                 throw Exception::IDNotFound("ValueNode in ValueNodeList: "+id);
403
404         return *iter;
405 }
406
407 ValueNode::Handle
408 ValueNodeList::surefind(const String &id)
409 {
410         if(id.empty())
411                 throw Exception::IDNotFound("Empty ID");
412
413         ValueNode::Handle value_node;
414
415         try
416         {
417                 value_node=find(id);
418         }
419         catch(Exception::IDNotFound)
420         {
421                 value_node=PlaceholderValueNode::create();
422                 value_node->set_id(id);
423                 push_back(value_node);
424                 placeholder_count_++;
425         }
426
427         return value_node;
428 }
429
430 bool
431 ValueNodeList::erase(ValueNode::Handle value_node)
432 {
433         assert(value_node);
434
435         iterator iter;
436
437         for(iter=begin();iter!=end();++iter)
438                 if(value_node.get()==iter->get())
439                 {
440                         std::list<ValueNode::RHandle>::erase(iter);
441                         if(PlaceholderValueNode::Handle::cast_dynamic(value_node))
442                                 placeholder_count_--;
443                         return true;
444                 }
445         return false;
446 }
447
448 bool
449 ValueNodeList::add(ValueNode::Handle value_node)
450 {
451         if(!value_node)
452                 return false;
453         if(value_node->get_id().empty())
454                 return false;
455
456         try
457         {
458                 ValueNode::RHandle other_value_node=find(value_node->get_id());
459                 if(PlaceholderValueNode::Handle::cast_dynamic(other_value_node))
460                 {
461                         other_value_node->replace(value_node);
462                         placeholder_count_--;
463                         return true;
464                 }
465
466                 return false;
467         }
468         catch(Exception::IDNotFound)
469         {
470                 push_back(value_node);
471                 return true;
472         }
473
474         return false;
475 }
476
477 void
478 ValueNodeList::audit()
479 {
480         iterator iter,next;
481
482         for(next=begin(),iter=next++;iter!=end();iter=next++)
483                 if(iter->count()==1)
484                         std::list<ValueNode::RHandle>::erase(iter);
485 }
486
487
488 String
489 PlaceholderValueNode::get_name()const
490 {
491         return "placeholder";
492 }
493
494 String
495 PlaceholderValueNode::get_local_name()const
496 {
497         return _("Placeholder");
498 }
499
500 ValueNode*
501 PlaceholderValueNode::clone(const GUID& deriv_guid)const
502 {
503         ValueNode* ret(new PlaceholderValueNode());
504         ret->set_guid(get_guid()^deriv_guid);
505         return ret;
506 }
507
508 PlaceholderValueNode::Handle
509 PlaceholderValueNode::create(ValueBase::Type type)
510 {
511         return new PlaceholderValueNode(type);
512 }
513
514 ValueBase
515 PlaceholderValueNode::operator()(Time /*t*/)const
516 {
517         assert(0);
518         return ValueBase();
519 }
520
521 PlaceholderValueNode::PlaceholderValueNode(ValueBase::Type type):
522         ValueNode(type)
523 {
524 }
525
526 ValueNode*
527 LinkableValueNode::clone(const GUID& deriv_guid)const
528 {
529         {
530                 ValueNode* x(find_value_node(get_guid()^deriv_guid).get());
531                 if(x)
532                         return x;
533         }
534
535         int i;
536         LinkableValueNode *ret=create_new();
537         ret->set_guid(get_guid()^deriv_guid);
538
539         for(i=0;i<link_count();i++)
540         {
541                 ValueNode::Handle link=get_link_vfunc(i);
542                 if(!link->is_exported())
543                 {
544                         ValueNode::LooseHandle value_node(find_value_node(link->get_guid()^deriv_guid));
545                         if(!value_node)
546                                 value_node=link->clone(deriv_guid);
547                         ret->set_link(i,value_node);
548                 }
549                 else
550                         ret->set_link(i,link);
551         }
552
553         return ret;
554 }
555
556 String
557 ValueNode::get_relative_id(etl::loose_handle<const Canvas> x)const
558 {
559         assert(is_exported());
560         assert(canvas_);
561
562         if(x.get()==canvas_.get())
563                 return get_id();
564
565         return canvas_->_get_relative_id(x)+':'+get_id();
566 }
567
568 void
569 ValueNode::set_parent_canvas(etl::loose_handle<Canvas> x)
570 {
571         canvas_=x; if(x) root_canvas_=x->get_root();
572 }
573
574 void
575 ValueNode::set_root_canvas(etl::loose_handle<Canvas> x)
576 {
577         root_canvas_=x->get_root();
578 }
579
580 void LinkableValueNode::get_times_vfunc(Node::time_set &set) const
581 {
582         ValueNode::LooseHandle  h;
583
584         int size = link_count();
585
586         //just add it to the set...
587         for(int i=0; i < size; ++i)
588         {
589                 h = get_link(i);
590
591                 if(h)
592                 {
593                         const Node::time_set &tset = h->get_times();
594                         set.insert(tset.begin(),tset.end());
595                 }
596         }
597 }
598
599 String
600 LinkableValueNode::get_description(int index, bool show_exported_name)const
601 {
602         String description;
603
604         if (index == -1)
605         {
606                 if (show_exported_name && is_exported())
607                         description += strprintf(" (%s)", get_id().c_str());
608         }
609         else
610         {
611                 description = String(":") + link_local_name(index);
612
613                 if (show_exported_name)
614                 {
615                         ValueNode::LooseHandle link(get_link(index));
616                         if (link->is_exported())
617                                 description += strprintf(" (%s)", link->get_id().c_str());
618                 }
619         }
620
621         const synfig::Node* node = this;
622         LinkableValueNode::ConstHandle parent_linkable_vn = 0;
623
624         // walk up through the valuenodes trying to find the layer at the top
625         while (!node->parent_set.empty() && !dynamic_cast<const Layer*>(node))
626         {
627                 LinkableValueNode::ConstHandle linkable_value_node(dynamic_cast<const LinkableValueNode*>(node));
628                 if (linkable_value_node)
629                 {
630                         String link;
631                         int cnt = linkable_value_node->link_count();
632                         for (int i = 0; i < cnt; i++)
633                                 if (linkable_value_node->get_link(i) == parent_linkable_vn)
634                                 {
635                                         link = String(":") + linkable_value_node->link_local_name(i);
636                                         break;
637                                 }
638
639                         description = linkable_value_node->get_local_name() + link + (parent_linkable_vn?">":"") + description;
640                 }
641                 node = *node->parent_set.begin();
642                 parent_linkable_vn = linkable_value_node;
643         }
644
645         Layer::ConstHandle parent_layer(dynamic_cast<const Layer*>(node));
646         if(parent_layer)
647         {
648                 String param;
649                 const Layer::DynamicParamList &dynamic_param_list(parent_layer->dynamic_param_list());
650                 // loop to find the parameter in the dynamic parameter list - this gives us its name
651                 for (Layer::DynamicParamList::const_iterator iter = dynamic_param_list.begin(); iter != dynamic_param_list.end(); iter++)
652                         if (iter->second == parent_linkable_vn)
653                                 param = String(":") + parent_layer->get_param_local_name(iter->first);
654                 description = strprintf("(%s)%s>%s",
655                                                                 parent_layer->get_non_empty_description().c_str(),
656                                                                 param.c_str(),
657                                                                 description.c_str());
658         }
659
660         return description;
661 }