Added a link to a sif file that demonstrates why r954 was useful.
[synfig.git] / synfig-core / trunk / 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         depth(0),
87         zoom(0),
88         time_offset(0),
89         extra_reference(false)
90 {
91         children_lock=false;
92         muck_with_time_=true;
93         curr_time=Time::begin();
94 }
95
96 Layer_PasteCanvas::~Layer_PasteCanvas()
97 {
98 /*      if(canvas)
99                 canvas->parent_set.erase(this);
100 */
101
102         //if(canvas)DEBUGINFO(strprintf("%d",canvas->count()));
103
104         set_sub_canvas(0);
105
106         //if(canvas && (canvas->is_inline() || !get_canvas() || get_canvas()->get_root()!=canvas->get_root()))
107         //if(extra_reference)
108         //      canvas->unref();
109 }
110
111 String
112 Layer_PasteCanvas::get_local_name()const
113 {
114         if(!canvas)     return _("Pasted Canvas");
115         if(canvas->is_inline()) return _("Inline Canvas");
116         if(canvas->get_root()==get_canvas()->get_root()) return '[' + canvas->get_id() + ']';
117
118         return '[' + canvas->get_file_name() + ']';
119 }
120
121 Layer::Vocab
122 Layer_PasteCanvas::get_param_vocab()const
123 {
124         Layer::Vocab ret(Layer_Composite::get_param_vocab());
125
126         ret.push_back(ParamDesc("origin")
127                 .set_local_name(_("Origin"))
128                 .set_description(_("Point where you want the origin to be"))
129         );
130         ret.push_back(ParamDesc("canvas")
131                 .set_local_name(_("Canvas"))
132                 .set_description(_("Canvas to paste"))
133         );
134         ret.push_back(ParamDesc("zoom")
135                 .set_local_name(_("Zoom"))
136                 .set_description(_("Size of canvas"))
137         );
138
139         ret.push_back(ParamDesc("time_offset")
140                 .set_local_name(_("Time Offset"))
141         );
142
143         ret.push_back(ParamDesc("children_lock")
144                 .set_local_name(_("Children Lock"))
145         );
146
147         return ret;
148 }
149
150 bool
151 Layer_PasteCanvas::set_param(const String & param, const ValueBase &value)
152 {
153         IMPORT(origin);
154
155         // IMPORT(canvas);
156         if(param=="canvas" && value.same_type_as(Canvas::Handle()))
157         {
158                 set_sub_canvas(value.get(Canvas::Handle()));
159                 return true;
160         }
161
162         //! \todo this introduces bug 1844764 if enabled; it was introduced in r954.
163         // http://synfig.org/images/3/3d/Moving-waypoints.sifz is an
164         // example of an animation that has its waypoints displayed
165         // incorrectly without this fix; select the outer layer and drag
166         // the time slider.  The linear waypoints don't take effect until
167         // 5s, but the time slider appears to pass the first one at 3s.
168 #if 0
169         if (param=="time_offset" && value.same_type_as(time_offset))
170         {
171                 if (time_offset != value.get(Time()))
172                 {
173                         value.put(&time_offset);
174                         // notify that the time_offset has changed so we can update the
175                         // waypoint positions in parent layers
176                         changed();
177                 }
178                 return true;
179         }
180 #else
181         IMPORT(time_offset);
182 #endif
183
184         IMPORT(children_lock);
185         IMPORT(zoom);
186
187         return Layer_Composite::set_param(param,value);
188 }
189
190 void
191 Layer_PasteCanvas::set_sub_canvas(etl::handle<synfig::Canvas> x)
192 {
193         if(canvas && muck_with_time_)
194                 remove_child(canvas.get());
195
196         // if(canvas && (canvas->is_inline() || !get_canvas() || get_canvas()->get_root()!=canvas->get_root()))
197         if (extra_reference)
198                 canvas->unref();
199
200         child_changed_connection.disconnect();
201
202         canvas=x;
203
204         /*if(canvas)
205                 child_changed_connection=canvas->signal_changed().connect(
206                         sigc::mem_fun(
207                                 *this,
208                                 &Layer_PasteCanvas::changed
209                         )
210                 );
211         */
212         if(canvas)
213                 bounds = ((canvas->get_context().get_full_bounding_rect() - canvas->rend_desc().get_focus()) * exp(zoom) +
214                                   origin + canvas->rend_desc().get_focus());
215
216         if(canvas && muck_with_time_)
217                 add_child(canvas.get());
218
219         if(canvas && (canvas->is_inline() || !get_canvas() || get_canvas()->get_root()!=canvas->get_root()))
220         {
221                 canvas->ref();
222                 extra_reference = true;
223         }
224         else
225                 extra_reference = false;
226
227         if(canvas)
228                 on_canvas_set();
229 }
230
231 // This is called whenever the parent canvas gets set/changed
232 void
233 Layer_PasteCanvas::on_canvas_set()
234 {
235         //synfig::info("before count()=%d",count());
236         if(get_canvas() && canvas && canvas->is_inline() && canvas->parent()!=get_canvas())
237         {
238                 //synfig::info("during count()=%d",count());
239                 canvas->set_inline(get_canvas());
240         }
241         //synfig::info("after count()=%d",count());
242 }
243
244 ValueBase
245 Layer_PasteCanvas::get_param(const String& param)const
246 {
247         EXPORT(origin);
248         EXPORT(canvas);
249         EXPORT(zoom);
250         EXPORT(time_offset);
251         EXPORT(children_lock);
252
253         EXPORT_NAME();
254         EXPORT_VERSION();
255
256         return Layer_Composite::get_param(param);
257 }
258
259 void
260 Layer_PasteCanvas::set_time(Context context, Time time)const
261 {
262         if(depth==MAX_DEPTH)return;depth_counter counter(depth);
263         curr_time=time;
264
265         context.set_time(time);
266         if(canvas)
267         {
268                 canvas->set_time(time+time_offset);
269
270                 bounds=(canvas->get_context().get_full_bounding_rect()-canvas->rend_desc().get_focus())*exp(zoom)+origin+canvas->rend_desc().get_focus();
271         }
272         else
273                 bounds=Rect::zero();
274 }
275
276 synfig::Layer::Handle
277 Layer_PasteCanvas::hit_check(synfig::Context context, const synfig::Point &pos)const
278 {
279         if(depth==MAX_DEPTH)return 0;depth_counter counter(depth);
280
281         if (canvas) {
282                 Point target_pos=(pos-canvas->rend_desc().get_focus()-origin)/exp(zoom)+canvas->rend_desc().get_focus();
283
284                 if(canvas && get_amount() && canvas->get_context().get_color(target_pos).get_a()>=0.25)
285                 {
286                         if(!children_lock)
287                         {
288                                 return canvas->get_context().hit_check(target_pos);
289                         }
290                         return const_cast<Layer_PasteCanvas*>(this);
291                 }
292         }
293         return context.hit_check(pos);
294 }
295
296 Color
297 Layer_PasteCanvas::get_color(Context context, const Point &pos)const
298 {
299         if(!canvas || !get_amount())
300                 return context.get_color(pos);
301
302         if(depth==MAX_DEPTH)return Color::alpha();depth_counter counter(depth);
303
304         Point target_pos=(pos-canvas->rend_desc().get_focus()-origin)/exp(zoom)+canvas->rend_desc().get_focus();
305
306         return Color::blend(canvas->get_context().get_color(target_pos),context.get_color(pos),get_amount(),get_blend_method());
307 }
308
309
310 bool
311 Layer_PasteCanvas::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
312 {
313         if(cb && !cb->amount_complete(0,10000)) return false;
314
315         if(depth==MAX_DEPTH)
316                 // if we are at the extent of our depth,
317                 // then we should just return whatever is under us.
318                 return context.accelerated_render(surface,quality,renddesc,cb);
319
320         depth_counter counter(depth);
321
322         if(!canvas || !get_amount())
323                 return context.accelerated_render(surface,quality,renddesc,cb);
324
325         if(muck_with_time_ && curr_time!=Time::begin() && canvas->get_time()!=curr_time+time_offset)
326                 canvas->set_time(curr_time+time_offset);
327
328         SuperCallback stageone(cb,0,4500,10000);
329         SuperCallback stagetwo(cb,4500,9000,10000);
330         SuperCallback stagethree(cb,9000,9999,10000);
331
332         RendDesc desc(renddesc);
333         Vector::value_type zoomfactor=1.0/exp(zoom);
334         desc.clear_flags();
335         desc.set_tl((desc.get_tl()-canvas->rend_desc().get_focus()-origin)*zoomfactor+canvas->rend_desc().get_focus());
336         desc.set_br((desc.get_br()-canvas->rend_desc().get_focus()-origin)*zoomfactor+canvas->rend_desc().get_focus());
337         desc.set_flags(RendDesc::PX_ASPECT);
338
339         if (is_solid_color() || context->empty())
340         {
341                 surface->set_wh(renddesc.get_w(),renddesc.get_h());
342                 surface->clear();
343         }
344         else if (!context.accelerated_render(surface,quality,renddesc,&stageone))
345                 return false;
346
347         Color::BlendMethod blend_method(get_blend_method());
348         const Rect full_bounding_rect(canvas->get_context().get_full_bounding_rect());
349
350         bool blend_using_straight = false; // use 'straight' just for the central blit
351
352         // sometimes the user changes the parameters while we're
353         // rendering, causing our pasted canvas' bounding box to shrink
354         // and no longer overlap with our tile.  if that has happened,
355         // let's just stop now - we'll be refreshing soon anyway
356         //! \todo shouldn't a mutex ensure this isn't needed?
357         // http://synfig.org/images/d/d2/Bbox-change.sifz is an example
358         // that shows this happening - open the encapsulation, select the
359         // 'shade', and toggle the 'invert' parameter quickly.
360         // Occasionally you'll see:
361         //   error: Context::accelerated_render(): Layer "shade" threw a bad_alloc exception!
362         // where the shade layer tries to allocate itself a canvas of
363         // negative proportions, due to changing bounding boxes.
364         if (!etl::intersect(desc.get_rect(), full_bounding_rect))
365         {
366                 warning("%s:%d bounding box shrank while rendering?", __FILE__, __LINE__);
367                 return true;
368         }
369
370         // we have rendered what's under us, if necessary
371         if(context->empty())
372         {
373                 // if there's nothing under us, and we're blending 'onto', then we've finished
374                 if (Color::is_onto(blend_method)) return true;
375
376                 // there's nothing under us, so using straight blending is
377                 // faster than and equivalent to using composite, but we don't
378                 // want to blank the surrounding areas
379                 if (blend_method==Color::BLEND_COMPOSITE) blend_using_straight = true;
380         }
381
382         if (!etl::intersect(context.get_full_bounding_rect(),full_bounding_rect+origin))
383         {
384                 // if there's no intersection between the context and our surface, and we're rendering 'onto', then we're done
385                 if (Color::is_onto(blend_method)) return true;
386
387                 /* 'straight' is faster than 'composite' and has the same
388                  * effect if the affected area of the lower layer is
389                  * transparent;  however, if we're not clipping the blit to
390                  * just the bounding rectangle, the affected area is the whole
391                  * tile, so we can't use this optimisation.  if we are
392                  * clipping, then we can use 'straight' to blit the clipped
393                  * rectangle, but we shouldn't set blend_method to 'straight',
394                  * or the surrounding areas will be blanked, which we don't
395                  * want.
396                  */
397 #ifdef SYNFIG_CLIP_PASTECANVAS
398                 if (blend_method==Color::BLEND_COMPOSITE) blend_using_straight = true;
399 #endif  // SYNFIG_CLIP_PASTECANVAS
400         }
401
402 #ifdef SYNFIG_CLIP_PASTECANVAS
403         Rect area(desc.get_rect() & full_bounding_rect);
404
405         Point min(area.get_min());
406         Point max(area.get_max());
407
408         if (desc.get_tl()[0] > desc.get_br()[0]) swap(min[0], max[0]);
409         if (desc.get_tl()[1] > desc.get_br()[1]) swap(min[1], max[1]);
410
411         const int x(floor_to_int((min[0] - desc.get_tl()[0]) / desc.get_pw()));
412         const int y(floor_to_int((min[1] - desc.get_tl()[1]) / desc.get_ph()));
413         const int w( ceil_to_int((max[0] - desc.get_tl()[0]) / desc.get_pw()) - x);
414         const int h( ceil_to_int((max[1] - desc.get_tl()[1]) / desc.get_ph()) - y);
415
416         const int tw = desc.get_w();
417         const int th = desc.get_h();
418
419         desc.set_subwindow(x,y,w,h);
420
421         // \todo this used to also have "area.area()<=0.000001 || " - is it useful?
422         //               it was causing bug #1809480 (Zoom in beyond 8.75 in nested canvases fails)
423         if(desc.get_w()==0 || desc.get_h()==0)
424         {
425                 if(cb && !cb->amount_complete(10000,10000)) return false;
426                 return true;
427         }
428
429         // SYNFIG_CLIP_PASTECANVAS is defined, so we are only touching the
430         // pixels within the affected rectangle.  If the blend method is
431         // 'straight', then we need to blend transparent pixels with the
432         // clipped areas of this tile, because with the 'straight' blend
433         // method, even transparent pixels have an effect on the layers below
434         if (Color::is_straight(blend_method))
435         {
436                 Surface clearsurface;
437
438                 Surface::alpha_pen apen(surface->begin());
439                 apen.set_alpha(get_amount());
440
441                 // the area we're about to blit is transparent, so it doesn't
442                 // matter whether we use 'straight' or 'straight onto' here
443                 if (blend_method == Color::BLEND_ALPHA_BRIGHTEN)
444                         apen.set_blend_method(blend_method);
445                 else
446                         apen.set_blend_method(Color::BLEND_STRAIGHT);
447
448                 /* This represents the area we're pasting into the tile,
449                  * within the tile as a whole.  Areas (A), (B), (C) and (D)
450                  * need blending with the underlying context if they're not
451                  * zero-sized:
452                  *
453                  *               0         x             x+w      tw
454                  *       0       +------------------------+
455                  *               |                                                |
456                  *               |                      (A)                       |
457                  *               |                                                |
458                  *       y       | - - +----------+ - - - |
459                  *               |         |              |               |
460                  *               | (C) |  w by h  |      (D)  |
461                  *               |         |              |               |
462                  *       y+h | - - +----------+ - - - |
463                  *               |                                                |
464                  *               |                      (B)                       |
465                  *               |                                                |
466                  *       tw      +------------------------+
467                  */
468
469                 if (y > 0)                              // draw the full-width strip above the rectangle (A)
470                 { apen.move_to(0,0);   clearsurface.set_wh(tw,y);        clearsurface.clear(); clearsurface.blit_to(apen); }
471                 if (y+h < th)                   // draw the full-width strip below the rectangle (B)
472                 { apen.move_to(0,y+h); clearsurface.set_wh(tw,th-(y+h)); clearsurface.clear(); clearsurface.blit_to(apen); }
473                 if (x > 0)                              // draw the box directly left of the rectangle (C)
474                 { apen.move_to(0,y);   clearsurface.set_wh(x,h);         clearsurface.clear(); clearsurface.blit_to(apen); }
475                 if (x+w < tw)                   // draw the box directly right of the rectangle (D)
476                 { apen.move_to(x+w,y); clearsurface.set_wh(tw-(x+w),h);  clearsurface.clear(); clearsurface.blit_to(apen); }
477         }
478 #endif  // SYNFIG_CLIP_PASTECANVAS
479
480         // render the canvas to be pasted onto pastesurface
481         Surface pastesurface;
482         if(!canvas->get_context().accelerated_render(&pastesurface,quality,desc,&stagetwo))
483                 return false;
484
485 #ifdef SYNFIG_CLIP_PASTECANVAS
486         Surface::alpha_pen apen(surface->get_pen(x,y));
487 #else  // SYNFIG_CLIP_PASTECANVAS
488         Surface::alpha_pen apen(surface->begin());
489 #endif  // SYNFIG_CLIP_PASTECANVAS
490
491         apen.set_alpha(get_amount());
492         apen.set_blend_method(blend_using_straight ? Color::BLEND_STRAIGHT : blend_method);
493         pastesurface.blit_to(apen);
494
495         if(cb && !cb->amount_complete(10000,10000)) return false;
496
497         return true;
498 }
499
500 Rect
501 Layer_PasteCanvas::get_bounding_rect()const
502 {
503         return bounds;
504 }
505
506 void Layer_PasteCanvas::get_times_vfunc(Node::time_set &set) const
507 {
508         Node::time_set tset;
509         if(canvas) tset = canvas->get_times();
510
511         Node::time_set::iterator i = tset.begin(), end = tset.end();
512
513         //Make sure we offset the time...
514         //! \todo: SOMETHING STILL HAS TO BE DONE WITH THE OTHER DIRECTION
515         //                 (recursing down the tree needs to take this into account too...)
516         for(; i != end; ++i)
517                 set.insert(*i
518 #ifdef ADJUST_WAYPOINTS_FOR_TIME_OFFSET // see node.h
519                                    - time_offset
520 #endif
521                         );
522
523         Layer::get_times_vfunc(set);
524 }