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