More descriptions for layer parameters
[synfig.git] / synfig-core / src / synfig / layer_pastecanvas.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file layer_pastecanvas.cpp
3 **      \brief Implementation of the "Paste Canvas" layer
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 #ifdef USING_PCH
27 #       include "pch.h"
28 #else
29 #ifdef HAVE_CONFIG_H
30 #       include <config.h>
31 #endif
32
33 #include "layer_pastecanvas.h"
34 #include "string.h"
35 #include "time.h"
36 #include "context.h"
37 #include "paramdesc.h"
38 #include "renddesc.h"
39 #include "surface.h"
40 #include "value.h"
41 #include "valuenode.h"
42 #include "canvas.h"
43
44 #endif
45
46 /* === U S I N G =========================================================== */
47
48 using namespace etl;
49 using namespace std;
50 using namespace synfig;
51
52 /* === M A C R O S ========================================================= */
53
54 #define MAX_DEPTH 10
55
56 // if this isn't defined, the 'dead heads' in examples/pirates.sifz don't render properly
57 #define SYNFIG_CLIP_PASTECANVAS
58
59 //#ifdef __APPLE__
60 //#undef SYNFIG_CLIP_PASTECANVAS
61 //#endif
62
63 /* === C L A S S E S ======================================================= */
64
65 class depth_counter     // Makes our recursive depth counter exception-safe
66 {
67         int *depth;
68 public:
69         depth_counter(int &x):depth(&x) { (*depth)++; }
70         ~depth_counter() { (*depth)--; }
71 };
72
73 /* === G L O B A L S ======================================================= */
74
75 SYNFIG_LAYER_INIT(Layer_PasteCanvas);
76 SYNFIG_LAYER_SET_NAME(Layer_PasteCanvas,"PasteCanvas"); // todo: use paste_canvas
77 SYNFIG_LAYER_SET_LOCAL_NAME(Layer_PasteCanvas,N_("Paste Canvas"));
78 SYNFIG_LAYER_SET_CATEGORY(Layer_PasteCanvas,N_("Other"));
79 SYNFIG_LAYER_SET_VERSION(Layer_PasteCanvas,"0.1");
80 SYNFIG_LAYER_SET_CVS_ID(Layer_PasteCanvas,"$Id$");
81
82 /* === M E T H O D S ======================================================= */
83
84 Layer_PasteCanvas::Layer_PasteCanvas():
85         origin(0,0),
86         focus(0,0),
87         depth(0),
88         zoom(0),
89         time_offset(0),
90         extra_reference(false)
91 {
92         children_lock=false;
93         muck_with_time_=true;
94         curr_time=Time::begin();
95         Layer::Vocab voc(get_param_vocab());
96         Layer::fill_static(voc);
97         set_param_static("children_lock", true);
98 }
99
100 Layer_PasteCanvas::~Layer_PasteCanvas()
101 {
102 /*      if(canvas)
103                 canvas->parent_set.erase(this);
104 */
105
106         //if(canvas)DEBUGINFO(strprintf("%d",canvas->count()));
107
108         set_sub_canvas(0);
109
110         //if(canvas && (canvas->is_inline() || !get_canvas() || get_canvas()->get_root()!=canvas->get_root()))
111         //if(extra_reference)
112         //      canvas->unref();
113 }
114
115 String
116 Layer_PasteCanvas::get_local_name()const
117 {
118         if(!canvas)     return _("Pasted Canvas");
119         if(canvas->is_inline()) return _("Inline Canvas");
120         if(canvas->get_root()==get_canvas()->get_root()) return '[' + canvas->get_id() + ']';
121
122         return '[' + canvas->get_file_name() + ']';
123 }
124
125 Layer::Vocab
126 Layer_PasteCanvas::get_param_vocab()const
127 {
128         Layer::Vocab ret(Layer_Composite::get_param_vocab());
129
130         ret.push_back(ParamDesc("origin")
131                 .set_local_name(_("Origin"))
132                 .set_description(_("Point where you want the origin to be"))
133         );
134         ret.push_back(ParamDesc("canvas")
135                 .set_local_name(_("Canvas"))
136                 .set_description(_("Canvas to paste"))
137         );
138         ret.push_back(ParamDesc("zoom")
139                 .set_local_name(_("Zoom"))
140                 .set_description(_("Size of canvas"))
141         );
142
143         ret.push_back(ParamDesc("time_offset")
144                 .set_local_name(_("Time Offset"))
145                 .set_description(_("Time Offset to apply to the context"))
146         );
147
148         ret.push_back(ParamDesc("children_lock")
149                 .set_local_name(_("Children Lock"))
150                 .set_description(_("When checked prevents to select the children using the mouse click"))
151         );
152
153         ret.push_back(ParamDesc("focus")
154                 .set_local_name(_("Focus Point"))
155                 .set_origin("origin")
156                 .set_connect("origin")
157                 .set_description(_("Point to remain fixed when zooming"))
158         //      .set_invisible_duck()
159         );
160
161         // optimize_layers() in canvas.cpp makes a new PasteCanvas layer
162         // and copies over the parameters of the old layer.  the
163         // 'curr_time' member wasn't being copied, so I've added it as a
164         // hidden, non critical parameter, and now it will be.  this
165         // allows a single exported subcanvas to be used more than once at
166         // a time, with different time offets in each.  see bug #1896557.
167         ret.push_back(ParamDesc("curr_time")
168                 .set_local_name(_("Current Time"))
169                 .not_critical()
170                 .hidden()
171         );
172
173         return ret;
174 }
175
176 bool
177 Layer_PasteCanvas::set_param(const String & param, const ValueBase &value)
178 {
179         IMPORT(origin);
180         IMPORT(focus);
181
182         // IMPORT(canvas);
183         if(param=="canvas" && value.same_type_as(Canvas::Handle()))
184         {
185                 set_sub_canvas(value.get(Canvas::Handle()));
186                 set_param_static(param, value.get_static());
187                 return true;
188         }
189         //! \todo this introduces bug 1844764 if enabled; it was introduced in r954.
190         // http://synfig.org/images/3/3d/Moving-waypoints.sifz is an
191         // example of an animation that has its waypoints displayed
192         // incorrectly without this fix; select the outer layer and drag
193         // the time slider.  The linear waypoints don't take effect until
194         // 5s, but the time slider appears to pass the first one at 3s.
195 #if 0
196         if (param=="time_offset" && value.same_type_as(time_offset))
197         {
198                 if (time_offset != value.get(Time()))
199                 {
200                         value.put(&time_offset);
201                         // notify that the time_offset has changed so we can update the
202                         // waypoint positions in parent layers
203                         changed();
204                 }
205                 return true;
206         }
207 #else
208         IMPORT(time_offset);
209 #endif
210
211         IMPORT(children_lock);
212         IMPORT(zoom);
213         IMPORT(curr_time);
214
215         return Layer_Composite::set_param(param,value);
216 }
217
218 void
219 Layer_PasteCanvas::set_sub_canvas(etl::handle<synfig::Canvas> x)
220 {
221         if(canvas && muck_with_time_)
222                 remove_child(canvas.get());
223
224         // if(canvas && (canvas->is_inline() || !get_canvas() || get_canvas()->get_root()!=canvas->get_root()))
225         if (extra_reference)
226                 canvas->unref();
227
228         child_changed_connection.disconnect();
229
230         if (canvas != x) signal_subcanvas_changed()();
231
232         canvas=x;
233
234         /*if(canvas)
235                 child_changed_connection=canvas->signal_changed().connect(
236                         sigc::mem_fun(
237                                 *this,
238                                 &Layer_PasteCanvas::changed
239                         )
240                 );
241         */
242         if(canvas)
243                 bounds = ((canvas->get_context().get_full_bounding_rect() - focus) * exp(zoom) + origin + focus);
244
245         if(canvas && muck_with_time_)
246                 add_child(canvas.get());
247
248         if(canvas && (canvas->is_inline() || !get_canvas() || get_canvas()->get_root()!=canvas->get_root()))
249         {
250                 canvas->ref();
251                 extra_reference = true;
252         }
253         else
254                 extra_reference = false;
255
256         if(canvas)
257                 on_canvas_set();
258 }
259
260 // when a pastecanvas that contains another pastecanvas is copy/pasted
261 // from one document to another, only the outermost pastecanvas was
262 // getting its renddesc set to match that of its new parent.  this
263 // function is used to recurse through the pastecanvas copying its
264 // renddesc to any pastecanvases it contains (bug #2116947, svn r2200)
265 void
266 Layer_PasteCanvas::update_renddesc()
267 {
268         if(!get_canvas() || !canvas || !canvas->is_inline()) return;
269
270         canvas->rend_desc()=get_canvas()->rend_desc();
271         for (Context context = canvas->get_context(); !context->empty(); context++)
272         {
273                 etl::handle<Layer_PasteCanvas> paste = etl::handle<Layer_PasteCanvas>::cast_dynamic(*context);
274                 if (paste) paste->update_renddesc();
275         }
276 }
277
278 // This is called whenever the parent canvas gets set/changed
279 void
280 Layer_PasteCanvas::on_canvas_set()
281 {
282         if(get_canvas() && canvas && canvas->is_inline() && canvas->parent()!=get_canvas())
283         {
284                 canvas->set_inline(get_canvas());
285         }
286 }
287
288 ValueBase
289 Layer_PasteCanvas::get_param(const String& param)const
290 {
291         EXPORT(origin);
292         EXPORT(focus);
293         EXPORT(canvas);
294         EXPORT(zoom);
295         EXPORT(time_offset);
296         EXPORT(children_lock);
297         EXPORT(curr_time);
298
299         EXPORT_NAME();
300         EXPORT_VERSION();
301
302         return Layer_Composite::get_param(param);
303 }
304
305 void
306 Layer_PasteCanvas::set_time(Context context, Time time)const
307 {
308         if(depth==MAX_DEPTH)return;depth_counter counter(depth);
309         curr_time=time;
310
311         context.set_time(time);
312         if(canvas)
313         {
314                 canvas->set_time(time+time_offset);
315
316                 bounds=(canvas->get_context().get_full_bounding_rect()-focus)*exp(zoom)+origin+focus;
317         }
318         else
319                 bounds=Rect::zero();
320 }
321
322 synfig::Layer::Handle
323 Layer_PasteCanvas::hit_check(synfig::Context context, const synfig::Point &pos)const
324 {
325         if(depth==MAX_DEPTH)return 0;depth_counter counter(depth);
326
327         if (canvas) {
328                 Point target_pos=(pos-focus-origin)/exp(zoom)+focus;
329
330                 if(canvas && get_amount() && canvas->get_context().get_color(target_pos).get_a()>=0.25)
331                 {
332                         if(!children_lock)
333                         {
334                                 return canvas->get_context().hit_check(target_pos);
335                         }
336                         return const_cast<Layer_PasteCanvas*>(this);
337                 }
338         }
339         return context.hit_check(pos);
340 }
341
342 Color
343 Layer_PasteCanvas::get_color(Context context, const Point &pos)const
344 {
345         if(!canvas || !get_amount())
346                 return context.get_color(pos);
347
348         if(depth==MAX_DEPTH)return Color::alpha();depth_counter counter(depth);
349
350         Point target_pos=(pos-focus-origin)/exp(zoom)+focus;
351
352         return Color::blend(canvas->get_context().get_color(target_pos),context.get_color(pos),get_amount(),get_blend_method());
353 }
354
355
356 bool
357 Layer_PasteCanvas::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
358 {
359         if(cb && !cb->amount_complete(0,10000)) return false;
360
361         if(depth==MAX_DEPTH)
362                 // if we are at the extent of our depth,
363                 // then we should just return whatever is under us.
364                 return context.accelerated_render(surface,quality,renddesc,cb);
365
366         depth_counter counter(depth);
367
368         if(!canvas || !get_amount())
369                 return context.accelerated_render(surface,quality,renddesc,cb);
370
371         SuperCallback stageone(cb,0,4500,10000);
372         SuperCallback stagetwo(cb,4500,9000,10000);
373         SuperCallback stagethree(cb,9000,9999,10000);
374
375         RendDesc desc(renddesc);
376         Vector::value_type zoomfactor=1.0/exp(zoom);
377         desc.clear_flags();
378         desc.set_tl((desc.get_tl()-focus-origin)*zoomfactor+focus);
379         desc.set_br((desc.get_br()-focus-origin)*zoomfactor+focus);
380         desc.set_flags(RendDesc::PX_ASPECT);
381
382         if (is_solid_color() || context->empty())
383         {
384                 surface->set_wh(renddesc.get_w(),renddesc.get_h());
385                 surface->clear();
386         }
387         else if (!context.accelerated_render(surface,quality,renddesc,&stageone))
388                 return false;
389
390         if(muck_with_time_ && curr_time!=Time::begin() /*&& canvas->get_time()!=curr_time+time_offset*/)
391                 canvas->set_time(curr_time+time_offset);
392
393         Color::BlendMethod blend_method(get_blend_method());
394         const Rect full_bounding_rect(canvas->get_context().get_full_bounding_rect());
395
396         bool blend_using_straight = false; // use 'straight' just for the central blit
397
398         // sometimes the user changes the parameters while we're
399         // rendering, causing our pasted canvas' bounding box to shrink
400         // and no longer overlap with our tile.  if that has happened,
401         // let's just stop now - we'll be refreshing soon anyway
402         //! \todo shouldn't a mutex ensure this isn't needed?
403         // http://synfig.org/images/d/d2/Bbox-change.sifz is an example
404         // that shows this happening - open the encapsulation, select the
405         // 'shade', and toggle the 'invert' parameter quickly.
406         // Occasionally you'll see:
407         //   error: Context::accelerated_render(): Layer "shade" threw a bad_alloc exception!
408         // where the shade layer tries to allocate itself a canvas of
409         // negative proportions, due to changing bounding boxes.
410         if (!etl::intersect(desc.get_rect(), full_bounding_rect))
411         {
412                 warning("%s:%d bounding box shrank while rendering?", __FILE__, __LINE__);
413                 return true;
414         }
415
416         // we have rendered what's under us, if necessary
417         if(context->empty())
418         {
419                 // if there's nothing under us, and we're blending 'onto', then we've finished
420                 if (Color::is_onto(blend_method)) return true;
421
422                 // there's nothing under us, so using straight blending is
423                 // faster than and equivalent to using composite, but we don't
424                 // want to blank the surrounding areas
425                 if (blend_method==Color::BLEND_COMPOSITE) blend_using_straight = true;
426         }
427
428         if (!etl::intersect(context.get_full_bounding_rect(),(full_bounding_rect-focus)*exp(zoom)+origin+focus))
429         {
430                 // if there's no intersection between the context and our
431                 // surface, and we're rendering 'onto', then we're done
432                 if (Color::is_onto(blend_method) && !Color::is_straight(blend_method))
433                         return true;
434
435                 /* 'straight' is faster than 'composite' and has the same
436                  * effect if the affected area of the lower layer is
437                  * transparent;  however, if we're not clipping the blit to
438                  * just the bounding rectangle, the affected area is the whole
439                  * tile, so we can't use this optimisation.  if we are
440                  * clipping, then we can use 'straight' to blit the clipped
441                  * rectangle, but we shouldn't set blend_method to 'straight',
442                  * or the surrounding areas will be blanked, which we don't
443                  * want.
444                  */
445 #ifdef SYNFIG_CLIP_PASTECANVAS
446                 if (blend_method==Color::BLEND_COMPOSITE) blend_using_straight = true;
447 #endif  // SYNFIG_CLIP_PASTECANVAS
448         }
449
450 #ifdef SYNFIG_CLIP_PASTECANVAS
451         Rect area(desc.get_rect() & full_bounding_rect);
452
453         Point min(area.get_min());
454         Point max(area.get_max());
455
456         if (desc.get_tl()[0] > desc.get_br()[0]) swap(min[0], max[0]);
457         if (desc.get_tl()[1] > desc.get_br()[1]) swap(min[1], max[1]);
458
459         const int x(floor_to_int((min[0] - desc.get_tl()[0]) / desc.get_pw()));
460         const int y(floor_to_int((min[1] - desc.get_tl()[1]) / desc.get_ph()));
461         const int w( ceil_to_int((max[0] - desc.get_tl()[0]) / desc.get_pw()) - x);
462         const int h( ceil_to_int((max[1] - desc.get_tl()[1]) / desc.get_ph()) - y);
463
464         const int tw = desc.get_w();
465         const int th = desc.get_h();
466
467         desc.set_subwindow(x,y,w,h);
468
469         // \todo this used to also have "area.area()<=0.000001 || " - is it useful?
470         //               it was causing bug #1809480 (Zoom in beyond 8.75 in nested canvases fails)
471         if(desc.get_w()==0 || desc.get_h()==0)
472         {
473                 if(cb && !cb->amount_complete(10000,10000)) return false;
474                 return true;
475         }
476
477         // SYNFIG_CLIP_PASTECANVAS is defined, so we are only touching the
478         // pixels within the affected rectangle.  If the blend method is
479         // 'straight', then we need to blend transparent pixels with the
480         // clipped areas of this tile, because with the 'straight' blend
481         // method, even transparent pixels have an effect on the layers below
482         if (Color::is_straight(blend_method))
483         {
484                 Surface clearsurface;
485
486                 Surface::alpha_pen apen(surface->begin());
487                 apen.set_alpha(get_amount());
488
489                 // the area we're about to blit is transparent, so it doesn't
490                 // matter whether we use 'straight' or 'straight onto' here
491                 if (blend_method == Color::BLEND_ALPHA_BRIGHTEN)
492                         apen.set_blend_method(blend_method);
493                 else
494                         apen.set_blend_method(Color::BLEND_STRAIGHT);
495
496                 /* This represents the area we're pasting into the tile,
497                  * within the tile as a whole.  Areas (A), (B), (C) and (D)
498                  * need blending with the underlying context if they're not
499                  * zero-sized:
500                  *
501                  *               0         x             x+w      tw
502                  *       0       +------------------------+
503                  *               |                                                |
504                  *               |                      (A)                       |
505                  *               |                                                |
506                  *       y       | - - +----------+ - - - |
507                  *               |         |              |               |
508                  *               | (C) |  w by h  |      (D)  |
509                  *               |         |              |               |
510                  *       y+h | - - +----------+ - - - |
511                  *               |                                                |
512                  *               |                      (B)                       |
513                  *               |                                                |
514                  *       tw      +------------------------+
515                  */
516
517                 if (y > 0)                              // draw the full-width strip above the rectangle (A)
518                 { apen.move_to(0,0);   clearsurface.set_wh(tw,y);        clearsurface.clear(); clearsurface.blit_to(apen); }
519                 if (y+h < th)                   // draw the full-width strip below the rectangle (B)
520                 { apen.move_to(0,y+h); clearsurface.set_wh(tw,th-(y+h)); clearsurface.clear(); clearsurface.blit_to(apen); }
521                 if (x > 0)                              // draw the box directly left of the rectangle (C)
522                 { apen.move_to(0,y);   clearsurface.set_wh(x,h);         clearsurface.clear(); clearsurface.blit_to(apen); }
523                 if (x+w < tw)                   // draw the box directly right of the rectangle (D)
524                 { apen.move_to(x+w,y); clearsurface.set_wh(tw-(x+w),h);  clearsurface.clear(); clearsurface.blit_to(apen); }
525         }
526 #endif  // SYNFIG_CLIP_PASTECANVAS
527
528         // render the canvas to be pasted onto pastesurface
529         Surface pastesurface;
530         if(!canvas->get_context().accelerated_render(&pastesurface,quality,desc,&stagetwo))
531                 return false;
532
533 #ifdef SYNFIG_CLIP_PASTECANVAS
534         Surface::alpha_pen apen(surface->get_pen(x,y));
535 #else  // SYNFIG_CLIP_PASTECANVAS
536         Surface::alpha_pen apen(surface->begin());
537 #endif  // SYNFIG_CLIP_PASTECANVAS
538
539         apen.set_alpha(get_amount());
540         apen.set_blend_method(blend_using_straight ? Color::BLEND_STRAIGHT : blend_method);
541         pastesurface.blit_to(apen);
542
543         if(cb && !cb->amount_complete(10000,10000)) return false;
544
545         return true;
546 }
547
548 Rect
549 Layer_PasteCanvas::get_bounding_rect()const
550 {
551         return bounds;
552 }
553
554 void Layer_PasteCanvas::get_times_vfunc(Node::time_set &set) const
555 {
556         Node::time_set tset;
557         if(canvas) tset = canvas->get_times();
558
559         Node::time_set::iterator i = tset.begin(), end = tset.end();
560
561         //Make sure we offset the time...
562         //! \todo: SOMETHING STILL HAS TO BE DONE WITH THE OTHER DIRECTION
563         //                 (recursing down the tree needs to take this into account too...)
564         for(; i != end; ++i)
565                 set.insert(*i
566 #ifdef ADJUST_WAYPOINTS_FOR_TIME_OFFSET // see node.h
567                                    - time_offset
568 #endif
569                         );
570
571         Layer::get_times_vfunc(set);
572 }
573
574
575 bool
576 Layer_PasteCanvas::set_param_static(const String &param, const bool x)
577 {
578         return Layer_Composite::set_param_static(param, x);
579 }
580
581
582 bool
583 Layer_PasteCanvas::get_param_static(const String &param) const
584 {
585         return Layer_Composite::get_param_static(param);
586 }