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