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