Show 'info' messages during the sync()ing of large plants - one message for every...
[synfig.git] / synfig-core / trunk / src / modules / mod_particle / plant.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file plant.cpp
3 **      \brief Template
4 **
5 **      $Id$
6 **
7 **      \legal
8 **      Copyright (c) 2002-2005 Robert B. Quattlebaum Jr., Adrian Bentley
9 **
10 **      This package is free software; you can redistribute it and/or
11 **      modify it under the terms of the GNU General Public License as
12 **      published by the Free Software Foundation; either version 2 of
13 **      the License, or (at your option) any later version.
14 **
15 **      This package is distributed in the hope that it will be useful,
16 **      but WITHOUT ANY WARRANTY; without even the implied warranty of
17 **      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 **      General Public License for more details.
19 **      \endlegal
20 */
21 /* ========================================================================= */
22
23 /* === H E A D E R S ======================================================= */
24
25 #ifdef USING_PCH
26 #       include "pch.h"
27 #else
28 #ifdef HAVE_CONFIG_H
29 #       include <config.h>
30 #endif
31
32 #include <synfig/angle.h>
33 #include "plant.h"
34 #include <synfig/string.h>
35 #include <synfig/time.h>
36 #include <synfig/context.h>
37 #include <synfig/paramdesc.h>
38 #include <synfig/renddesc.h>
39 #include <synfig/surface.h>
40 #include <synfig/value.h>
41 #include <synfig/valuenode.h>
42
43 #include <ETL/calculus>
44 #include <ETL/bezier>
45 #include <ETL/hermite>
46 #include <vector>
47
48 #include <synfig/valuenode_bline.h>
49
50 #endif
51
52 using namespace etl;
53
54 /* === M A C R O S ========================================================= */
55
56 #define SAMPLES         300
57 #define ROUND_END_FACTOR        (4)
58 #define CUSP_THRESHOLD          (0.15)
59 #define NO_LOOP_COOKIE          synfig::Vector(84951305,7836658)
60 #define EPSILON                         (0.000000001)
61 #define CUSP_TANGENT_ADJUST     (0.025)
62
63 /* === G L O B A L S ======================================================= */
64
65 SYNFIG_LAYER_INIT(Plant);
66 SYNFIG_LAYER_SET_NAME(Plant,"plant");
67 SYNFIG_LAYER_SET_LOCAL_NAME(Plant,_("Plant"));
68 SYNFIG_LAYER_SET_CATEGORY(Plant,_("Other"));
69 SYNFIG_LAYER_SET_VERSION(Plant,"0.1");
70 SYNFIG_LAYER_SET_CVS_ID(Plant,"$Id$");
71
72 /* === P R O C E D U R E S ================================================= */
73
74 /* === M E T H O D S ======================================================= */
75
76
77 Plant::Plant():
78         split_angle(Angle::deg(10)),
79         gravity(0,-0.1),
80         velocity(0.3),
81         step(0.01),
82         sprouts(10)
83 {
84         bounding_rect=Rect::zero();
85         random_factor=0.2;
86         random.set_seed(time(NULL));
87
88         bline.push_back(BLinePoint());
89         bline.push_back(BLinePoint());
90         bline.push_back(BLinePoint());
91         bline[0].set_vertex(Point(0,1));
92         bline[1].set_vertex(Point(0,-1));
93         bline[2].set_vertex(Point(1,0));
94         bline[0].set_tangent(bline[1].get_vertex()-bline[2].get_vertex()*0.5f);
95         bline[1].set_tangent(bline[2].get_vertex()-bline[0].get_vertex()*0.5f);
96         bline[2].set_tangent(bline[0].get_vertex()-bline[1].get_vertex()*0.5f);
97         bline[0].set_width(1.0f);
98         bline[1].set_width(1.0f);
99         bline[2].set_width(1.0f);
100         bline_loop=true;
101         mass=(0.5);
102         splits=5;
103         drag=0.1;
104         size=0.015;
105         needs_sync_=true;
106         sync();
107         size_as_alpha=false;
108 }
109
110 void
111 Plant::branch(int n,int depth,float t, float stunt_growth, synfig::Point position,synfig::Vector vel)const
112 {
113         float next_split((1.0-t)/(splits-depth)+t/*+random_factor*random(40+depth,t*splits,0,0)/splits*/);
114         for(;t<next_split;t+=step)
115         {
116                 vel[0]+=gravity[0]*step;
117                 vel[1]+=gravity[1]*step;
118                 vel*=(1.0-(drag)*step);
119                 position[0]+=vel[0]*step;
120                 position[1]+=vel[1]*step;
121
122                 particle_list.push_back(Particle(position, gradient(t)));
123                 if (particle_list.size() % 1000000 == 0)
124                         synfig::info("constructed %d million particles...", particle_list.size()/1000000);
125
126                 bounding_rect.expand(position);
127         }
128
129         if(t>=1.0-stunt_growth)return;
130
131         synfig::Real sin_v=synfig::Angle::cos(split_angle).get();
132         synfig::Real cos_v=synfig::Angle::sin(split_angle).get();
133
134         synfig::Vector velocity1(vel[0]*sin_v - vel[1]*cos_v + random_factor*random(Random::SMOOTH_COSINE, 30+n+depth, t*splits, 0.0f, 0.0f),
135                                                          vel[0]*cos_v + vel[1]*sin_v + random_factor*random(Random::SMOOTH_COSINE, 32+n+depth, t*splits, 0.0f, 0.0f));
136         synfig::Vector velocity2(vel[0]*sin_v + vel[1]*cos_v + random_factor*random(Random::SMOOTH_COSINE, 31+n+depth, t*splits, 0.0f, 0.0f),
137                                                         -vel[0]*cos_v + vel[1]*sin_v + random_factor*random(Random::SMOOTH_COSINE, 33+n+depth, t*splits, 0.0f, 0.0f));
138
139         Plant::branch(n,depth+1,t,stunt_growth,position,velocity1);
140         Plant::branch(n,depth+1,t,stunt_growth,position,velocity2);
141 }
142
143 void
144 Plant::calc_bounding_rect()const
145 {
146         std::vector<synfig::BLinePoint>::const_iterator iter,next;
147
148         bounding_rect=Rect::zero();
149
150         // Bline must have at least 2 points in it
151         if(bline.size()<2)
152                 return;
153
154         next=bline.begin();
155
156         if(bline_loop)
157                 iter=--bline.end();
158         else
159                 iter=next++;
160
161         for(;next!=bline.end();iter=next++)
162         {
163                 bounding_rect.expand(iter->get_vertex());
164                 bounding_rect.expand(next->get_vertex());
165                 bounding_rect.expand(iter->get_vertex()+iter->get_tangent2()*0.3333333333333);
166                 bounding_rect.expand(next->get_vertex()-next->get_tangent1()*0.3333333333333);
167                 bounding_rect.expand(next->get_vertex()+next->get_tangent2()*velocity);
168         }
169         bounding_rect.expand_x(gravity[0]);
170         bounding_rect.expand_y(gravity[1]);
171         bounding_rect.expand_x(size);
172         bounding_rect.expand_y(size);
173 }
174
175 void
176 Plant::sync()const
177 {
178         Mutex::Lock lock(mutex);
179         if (!needs_sync_) return;
180         particle_list.clear();
181
182         bounding_rect=Rect::zero();
183
184         // Bline must have at least 2 points in it
185         if(bline.size()<2)
186         {
187                 needs_sync_=false;
188                 return;
189         }
190
191         std::vector<synfig::BLinePoint>::const_iterator iter,next;
192
193         etl::hermite<Vector> curve;
194
195         Real step(abs(this->step));
196
197         int seg(0);
198
199         next=bline.begin();
200
201         if(bline_loop)  iter=--bline.end(); // iter is the last  bline in the list; next is the first  bline in the list
202         else                    iter=next++;            // iter is the first bline in the list; next is the second bline in the list
203
204         // loop through the bline; seg counts the blines as we do so; stop before iter is the last bline in the list
205         for(;next!=bline.end();iter=next++,seg++)
206         {
207                 curve.p1()=iter->get_vertex();
208                 curve.t1()=iter->get_tangent2();
209                 curve.p2()=next->get_vertex();
210                 curve.t2()=next->get_tangent1();
211                 curve.sync();
212                 etl::derivative<etl::hermite<Vector> > deriv(curve);
213
214                 Real f;
215
216                 int i=0, branch_count = 0, steps = round_to_int(1.0/step);
217                 for(f=0.0;f<1.0;f+=step,i++)
218                 {
219                         Point point(curve(f));
220
221                         particle_list.push_back(Particle(point, gradient(0)));
222                         if (particle_list.size() % 1000000 == 0)
223                                 synfig::info("constructed %d million particles...", particle_list.size()/1000000);
224
225                         bounding_rect.expand(point);
226
227                         Real stunt_growth(random_factor * random(Random::SMOOTH_COSINE,i,f+seg,0.0f,0.0f)/2.0+0.5);
228                         stunt_growth*=stunt_growth;
229
230                         Vector branch_velocity(deriv(f).norm()*velocity);
231
232                         branch_velocity[0] += random_factor * random(Random::SMOOTH_COSINE, 1, f*splits, 0.0f, 0.0f);
233                         branch_velocity[1] += random_factor * random(Random::SMOOTH_COSINE, 2, f*splits, 0.0f, 0.0f);
234
235                         if((((i+1)*sprouts + steps/2) / steps) > branch_count) {
236                                 branch_count++;
237                                 branch(i, 0, 0,          // time
238                                            stunt_growth, // stunt growth
239                                            point, branch_velocity);
240                         }
241                 }
242         }
243
244         needs_sync_=false;
245 }
246
247 bool
248 Plant::set_param(const String & param, const ValueBase &value)
249 {
250         if(param=="bline" && value.get_type()==ValueBase::TYPE_LIST)
251         {
252                 bline=value;
253                 bline_loop=value.get_loop();
254                 needs_sync_=true;
255
256                 return true;
257         }
258         if(param=="seed" && value.same_type_as(int()))
259         {
260                 random.set_seed(value.get(int()));
261                 needs_sync_=true;
262                 return true;
263         }
264         IMPORT_PLUS(split_angle,needs_sync_=true);
265         IMPORT_PLUS(gravity,needs_sync_=true);
266         IMPORT_PLUS(gradient,needs_sync_=true);
267         IMPORT_PLUS(velocity,needs_sync_=true);
268         IMPORT_PLUS(step,needs_sync_=true);
269         IMPORT_PLUS(splits,needs_sync_=true);
270         IMPORT_PLUS(sprouts,needs_sync_=true);
271         IMPORT_PLUS(random_factor,needs_sync_=true);
272         IMPORT_PLUS(drag,needs_sync_=true);
273         IMPORT(size);
274         IMPORT(size_as_alpha);
275
276         return Layer_Composite::set_param(param,value);
277 }
278 /*
279 void
280 Plant::set_time(Context context, Time time)const
281 {
282         if(needs_sync==true)
283         {
284                 sync();
285                 needs_sync_=false;
286         }
287         //const_cast<Plant*>(this)->sync();
288         context.set_time(time);
289 }
290
291 void
292 Plant::set_time(Context context, Time time, Vector pos)const
293 {
294         if(needs_sync==true)
295         {
296                 sync();
297                 needs_sync_=false;
298         }
299         //const_cast<Plant*>(this)->sync();
300         context.set_time(time,pos);
301 }
302 */
303 ValueBase
304 Plant::get_param(const String& param)const
305 {
306         if(param=="seed")
307                 return random.get_seed();
308         EXPORT(bline);
309         EXPORT(split_angle);
310         EXPORT(gravity);
311         EXPORT(velocity);
312         EXPORT(step);
313         EXPORT(gradient);
314         EXPORT(splits);
315         EXPORT(sprouts);
316         EXPORT(random_factor);
317         EXPORT(drag);
318         EXPORT(size);
319
320         EXPORT(size_as_alpha);
321
322         EXPORT_NAME();
323         EXPORT_VERSION();
324
325         return Layer_Composite::get_param(param);
326 }
327
328 Layer::Vocab
329 Plant::get_param_vocab()const
330 {
331         Layer::Vocab ret(Layer_Composite::get_param_vocab());
332
333         ret.push_back(ParamDesc("bline")
334                 .set_local_name(_("Vertices"))
335                 .set_description(_("A list of BLine Points"))
336                 //.set_origin("offset")
337                 //.set_scalar("width")
338         );
339
340         ret.push_back(ParamDesc("gradient")
341                 .set_local_name(_("Gradient"))
342                 .set_description(_("Gradient to be used for coloring the plant"))
343         );
344
345         ret.push_back(ParamDesc("split_angle")
346                 .set_local_name(_("Split Angle"))
347                 .set_description(_("Angle by which each split deviates from its parent"))
348         );
349
350         ret.push_back(ParamDesc("gravity")
351                 .set_local_name(_("Gravity"))
352                 .set_description(_("Direction in which the shoots tend to face"))
353                 .set_is_distance()
354         );
355
356         ret.push_back(ParamDesc("velocity")
357                 .set_local_name(_("Velocity"))
358                 .set_description(_("Amount to which shoots tend to follow the tangent of the BLine"))
359         );
360
361         ret.push_back(ParamDesc("size")
362                 .set_local_name(_("Stem Size"))
363                 .set_description(_("Size of the stem"))
364                 .set_is_distance()
365         );
366
367         ret.push_back(ParamDesc("size_as_alpha")
368                 .set_local_name(_("Size As Alpha"))
369                 .set_description(_("If enabled, the alpha channel from the gradient is multiplied by the stem size, and an alpha of 1.0 is used when rendering"))
370         );
371
372         ret.push_back(ParamDesc("step")
373                 .set_local_name(_("Step"))
374                 .set_description(_("Measure of the distance between points when rendering"))
375         );
376
377         ret.push_back(ParamDesc("seed")
378                 .set_local_name(_("Seed"))
379                 .set_description(_("Used to seed the pseudo-random number generator"))
380         );
381
382         ret.push_back(ParamDesc("splits")
383                 .set_local_name(_("Splits"))
384                 .set_description(_("Maximum number of times that each sprout can sprout recursively"))
385         );
386
387         ret.push_back(ParamDesc("sprouts")
388                 .set_local_name(_("Sprouts"))
389                 .set_description(_("Number of places that growth occurs on each bline section"))
390         );
391
392         ret.push_back(ParamDesc("random_factor")
393                 .set_local_name(_("Random Factor"))
394                 .set_description(_("Used to scale down all random effects.  Set to zero to disable randomness"))
395         );
396
397         ret.push_back(ParamDesc("drag")
398                 .set_local_name(_("Drag"))
399                 .set_description(_("Drag slows the growth"))
400         );
401
402         return ret;
403 }
404
405 bool
406 Plant::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
407 {
408         bool ret(context.accelerated_render(surface,quality,renddesc,cb));
409         if(is_disabled() || !ret)
410                 return ret;
411
412         Surface dest_surface;
413         dest_surface.set_wh(surface->get_w(),surface->get_h());
414         dest_surface.clear();
415
416         const Point     tl(renddesc.get_tl());
417         const Point br(renddesc.get_br());
418
419         const int       w(renddesc.get_w());
420         const int       h(renddesc.get_h());
421
422         // Width and Height of a pixel
423         const Real pw = (br[0] - tl[0]) / w;
424         const Real ph = (br[1] - tl[1]) / h;
425
426         if(needs_sync_==true)
427                 sync();
428
429         std::vector<Particle>::reverse_iterator iter;
430         const float size_factor(1);
431         float radius(size_factor*size*sqrt(1.0f/(abs(pw)*abs(ph)))), temp_radius;
432
433         if(radius>1.0f)
434         {
435                 radius*=1.0;                    // what does this do?
436                 int x1,y1,x2,y2;
437                 for(iter=particle_list.rbegin();iter!=particle_list.rend();++iter)
438                 {
439                         temp_radius = radius;
440                         float radius(temp_radius);
441                         Color color(iter->color);
442                         if(size_as_alpha)
443                         {
444                                 radius*=color.get_a();
445                                 color.set_a(1);
446                         }
447
448                         // calculate the box that this particle will be drawn as
449                         x1=ceil_to_int((iter->point[0]-tl[0])/pw-(radius*0.5));
450                         y1=ceil_to_int((iter->point[1]-tl[1])/ph-(radius*0.5));
451                         x2=x1+round_to_int(radius);
452                         y2=y1+round_to_int(radius);
453
454                         // if the box is entirely off the canvas, go to the next particle
455                         if(x1>=surface->get_w() || y1>=surface->get_h() || x2<0 || y2<0) continue;
456
457                         // adjust the box so it's entirely on the canvas
458                         if(x2>=surface->get_w()) x2=surface->get_w();
459                         if(y2>=surface->get_h()) y2=surface->get_h();
460                         if(x1<0) x1=0;
461                         if(y1<0) y1=0;
462
463                         int w(min(round_to_int(radius),x2-x1));
464                         int h(min(round_to_int(radius),y2-y1));
465
466                         if(w<=0 || h<=0)
467                                 continue;
468
469                         Surface::alpha_pen surface_pen(dest_surface.get_pen(x1,y1),1.0f);
470                         dest_surface.fill(color,surface_pen,w,h);
471                 }
472         }
473         else
474         {
475                 //radius/=0.01;
476                 radius*=sqrt(step)*12.0f;
477                 for(iter=particle_list.rbegin();iter!=particle_list.rend();++iter)
478                 {
479                         temp_radius = radius;
480                         float radius(temp_radius);
481                         Color color(iter->color);
482                         if(size_as_alpha)
483                         {
484                                 radius*=color.get_a();
485                                 color.set_a(1);
486                         }
487
488                         // calculate the point that this particle will be drawn as
489                         int x=floor_to_int((iter->point[0]-tl[0])/pw-0.5f);
490                         int y=floor_to_int((iter->point[1]-tl[1])/ph-0.5f);
491
492                         // if the point is off the canvas, go to the next particle
493                         // fixme: we're losing a whole row and a whole column of pixels from each tile
494                         //        by doing this.  even in the final rendered image there are visible
495                         //                horizontal stripes of damage:
496                         //          http://dooglus.rincevent.net/synfig/plant-corruption.png
497                         if(x>=surface->get_w()-1 || y>=surface->get_h()-1 || x<0 || y<0) continue;
498
499                         // calculate how much of the point is at (x) and how much at (x+1)
500                         float x1=((iter->point[0]-tl[0])/pw-0.5f-x)*radius, x0=radius-x1;
501
502                         // calculate how much of the point is at (y) and how much at (y+1)
503                         float y1=((iter->point[1]-tl[1])/ph-0.5f-y)*radius, y0=radius-y1;
504
505                         Surface::alpha_pen surface_pen(dest_surface.get_pen(x,y),1.0f);
506
507                         //     |  x0 |  x1
508                         //  ---+-----+-----
509                         //  y0 | 1st | 2nd
510                         //  ---+-----+-----
511                         //  y1 | 4th | 3rd
512
513                         surface_pen.set_alpha(x0*y0); surface_pen.put_value(color); surface_pen.inc_x();
514                         surface_pen.set_alpha(x1*y0); surface_pen.put_value(color); surface_pen.inc_y();
515                         surface_pen.set_alpha(x1*y1); surface_pen.put_value(color); surface_pen.dec_x();
516                         surface_pen.set_alpha(x0*y1); surface_pen.put_value(color);
517                 }
518         }
519
520         Surface::alpha_pen pen(surface->get_pen(0,0),get_amount(),get_blend_method());
521         dest_surface.blit_to(pen);
522
523         return true;
524 }
525
526 Rect
527 Plant::get_bounding_rect(Context context)const
528 {
529         if(needs_sync_==true)
530                 sync();
531
532         if(is_disabled())
533                 return Rect::zero();
534
535         if(Color::is_onto(get_blend_method()))
536                 return context.get_full_bounding_rect() & bounding_rect;
537
538         //if(get_blend_method()==Color::BLEND_BEHIND)
539         //      return context.get_full_bounding_rect() | bounding_rect;
540         return bounding_rect;
541 }