Reject invalid and dangerous values for the 'step' parameter.
[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 **      Copyright (c) 2007 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 <synfig/angle.h>
34 #include "plant.h"
35 #include <synfig/string.h>
36 #include <synfig/time.h>
37 #include <synfig/context.h>
38 #include <synfig/paramdesc.h>
39 #include <synfig/renddesc.h>
40 #include <synfig/surface.h>
41 #include <synfig/value.h>
42 #include <synfig/valuenode.h>
43
44 #include <ETL/calculus>
45 #include <ETL/bezier>
46 #include <ETL/hermite>
47 #include <vector>
48
49 #include <synfig/valuenode_bline.h>
50
51 #endif
52
53 using namespace etl;
54
55 /* === M A C R O S ========================================================= */
56
57 #define SAMPLES         300
58 #define ROUND_END_FACTOR        (4)
59 #define CUSP_THRESHOLD          (0.15)
60 #define NO_LOOP_COOKIE          synfig::Vector(84951305,7836658)
61 #define EPSILON                         (0.000000001)
62 #define CUSP_TANGENT_ADJUST     (0.025)
63
64 /* === G L O B A L S ======================================================= */
65
66 SYNFIG_LAYER_INIT(Plant);
67 SYNFIG_LAYER_SET_NAME(Plant,"plant");
68 SYNFIG_LAYER_SET_LOCAL_NAME(Plant,_("Plant"));
69 SYNFIG_LAYER_SET_CATEGORY(Plant,_("Other"));
70 SYNFIG_LAYER_SET_VERSION(Plant,"0.1");
71 SYNFIG_LAYER_SET_CVS_ID(Plant,"$Id$");
72
73 /* === P R O C E D U R E S ================================================= */
74
75 /* === M E T H O D S ======================================================= */
76
77
78 Plant::Plant():
79         split_angle(Angle::deg(10)),
80         gravity(0,-0.1),
81         velocity(0.3),
82         perp_velocity(0.0),
83         step(0.01),
84         sprouts(10)
85 {
86         bounding_rect=Rect::zero();
87         random_factor=0.2;
88         random.set_seed(time(NULL));
89
90         bline.push_back(BLinePoint());
91         bline.push_back(BLinePoint());
92         bline.push_back(BLinePoint());
93         bline[0].set_vertex(Point(0,1));
94         bline[1].set_vertex(Point(0,-1));
95         bline[2].set_vertex(Point(1,0));
96         bline[0].set_tangent(bline[1].get_vertex()-bline[2].get_vertex()*0.5f);
97         bline[1].set_tangent(bline[2].get_vertex()-bline[0].get_vertex()*0.5f);
98         bline[2].set_tangent(bline[0].get_vertex()-bline[1].get_vertex()*0.5f);
99         bline[0].set_width(1.0f);
100         bline[1].set_width(1.0f);
101         bline[2].set_width(1.0f);
102         bline_loop=true;
103         mass=(0.5);
104         splits=5;
105         drag=0.1;
106         size=0.015;
107         needs_sync_=true;
108         sync();
109         size_as_alpha=false;
110 }
111
112 void
113 Plant::branch(int n,int depth,float t, float stunt_growth, synfig::Point position,synfig::Vector vel)const
114 {
115         float next_split((1.0-t)/(splits-depth)+t/*+random_factor*random(40+depth,t*splits,0,0)/splits*/);
116         for(;t<next_split;t+=step)
117         {
118                 vel[0]+=gravity[0]*step;
119                 vel[1]+=gravity[1]*step;
120                 vel*=(1.0-(drag)*step);
121                 position[0]+=vel[0]*step;
122                 position[1]+=vel[1]*step;
123
124                 particle_list.push_back(Particle(position, gradient(t)));
125                 if (particle_list.size() % 1000000 == 0)
126                         synfig::info("constructed %d million particles...", particle_list.size()/1000000);
127
128                 bounding_rect.expand(position);
129         }
130
131         if(t>=1.0-stunt_growth)return;
132
133         synfig::Real sin_v=synfig::Angle::cos(split_angle).get();
134         synfig::Real cos_v=synfig::Angle::sin(split_angle).get();
135
136         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),
137                                                          vel[0]*cos_v + vel[1]*sin_v + random_factor*random(Random::SMOOTH_COSINE, 32+n+depth, t*splits, 0.0f, 0.0f));
138         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),
139                                                         -vel[0]*cos_v + vel[1]*sin_v + random_factor*random(Random::SMOOTH_COSINE, 33+n+depth, t*splits, 0.0f, 0.0f));
140
141         Plant::branch(n,depth+1,t,stunt_growth,position,velocity1);
142         Plant::branch(n,depth+1,t,stunt_growth,position,velocity2);
143 }
144
145 void
146 Plant::calc_bounding_rect()const
147 {
148         std::vector<synfig::BLinePoint>::const_iterator iter,next;
149
150         bounding_rect=Rect::zero();
151
152         // Bline must have at least 2 points in it
153         if(bline.size()<2)
154                 return;
155
156         next=bline.begin();
157
158         if(bline_loop)
159                 iter=--bline.end();
160         else
161                 iter=next++;
162
163         for(;next!=bline.end();iter=next++)
164         {
165                 bounding_rect.expand(iter->get_vertex());
166                 bounding_rect.expand(next->get_vertex());
167                 bounding_rect.expand(iter->get_vertex()+iter->get_tangent2()*0.3333333333333);
168                 bounding_rect.expand(next->get_vertex()-next->get_tangent1()*0.3333333333333);
169                 bounding_rect.expand(next->get_vertex()+next->get_tangent2()*velocity);
170         }
171         bounding_rect.expand_x(gravity[0]);
172         bounding_rect.expand_y(gravity[1]);
173         bounding_rect.expand_x(size);
174         bounding_rect.expand_y(size);
175 }
176
177 void
178 Plant::sync()const
179 {
180         Mutex::Lock lock(mutex);
181         if (!needs_sync_) return;
182         time_t start_time; time(&start_time);
183         particle_list.clear();
184
185         bounding_rect=Rect::zero();
186
187         // Bline must have at least 2 points in it
188         if(bline.size()<2)
189         {
190                 needs_sync_=false;
191                 return;
192         }
193
194         std::vector<synfig::BLinePoint>::const_iterator iter,next;
195
196         etl::hermite<Vector> curve;
197
198         Real step(abs(this->step));
199
200         int seg(0);
201
202         next=bline.begin();
203
204         if(bline_loop)  iter=--bline.end(); // iter is the last  bline in the list; next is the first  bline in the list
205         else                    iter=next++;            // iter is the first bline in the list; next is the second bline in the list
206
207         // loop through the bline; seg counts the blines as we do so; stop before iter is the last bline in the list
208         for(;next!=bline.end();iter=next++,seg++)
209         {
210                 curve.p1()=iter->get_vertex();
211                 curve.t1()=iter->get_tangent2();
212                 curve.p2()=next->get_vertex();
213                 curve.t2()=next->get_tangent1();
214                 curve.sync();
215                 etl::derivative<etl::hermite<Vector> > deriv(curve);
216
217                 Real f;
218
219                 int i=0, branch_count = 0, steps = round_to_int(1.0/step);
220                 if (steps < 1) steps = 1;
221                 for(f=0.0;f<1.0;f+=step,i++)
222                 {
223                         Point point(curve(f));
224
225                         particle_list.push_back(Particle(point, gradient(0)));
226                         if (particle_list.size() % 1000000 == 0)
227                                 synfig::info("constructed %d million particles...", particle_list.size()/1000000);
228
229                         bounding_rect.expand(point);
230
231                         Real stunt_growth(random_factor * (random(Random::SMOOTH_COSINE,i,f+seg,0.0f,0.0f)/2.0+0.5));
232                         stunt_growth*=stunt_growth;
233
234                         if((((i+1)*sprouts + steps/2) / steps) > branch_count) {
235                                 Vector branch_velocity(deriv(f).norm()*velocity + deriv(f).perp().norm()*perp_velocity);
236
237                                 branch_velocity[0] += random_factor * random(Random::SMOOTH_COSINE, 1, f*splits, 0.0f, 0.0f);
238                                 branch_velocity[1] += random_factor * random(Random::SMOOTH_COSINE, 2, f*splits, 0.0f, 0.0f);
239
240                                 branch_count++;
241                                 branch(i, 0, 0,          // time
242                                            stunt_growth, // stunt growth
243                                            point, branch_velocity);
244                         }
245                 }
246         }
247
248         time_t end_time; time(&end_time);
249         if (end_time-start_time > 4)
250                 synfig::info("Plant::sync() constructed %d particles in %d seconds\n",
251                                          particle_list.size(), int(end_time-start_time));
252         needs_sync_=false;
253 }
254
255 bool
256 Plant::set_param(const String & param, const ValueBase &value)
257 {
258         if(param=="bline" && value.get_type()==ValueBase::TYPE_LIST)
259         {
260                 bline=value;
261                 bline_loop=value.get_loop();
262                 needs_sync_=true;
263
264                 return true;
265         }
266         if(param=="seed" && value.same_type_as(int()))
267         {
268                 random.set_seed(value.get(int()));
269                 needs_sync_=true;
270                 return true;
271         }
272         IMPORT_PLUS(split_angle,needs_sync_=true);
273         IMPORT_PLUS(gravity,needs_sync_=true);
274         IMPORT_PLUS(gradient,needs_sync_=true);
275         IMPORT_PLUS(velocity,needs_sync_=true);
276         IMPORT_PLUS(perp_velocity,needs_sync_=true);
277         IMPORT_PLUS(step,{
278                         needs_sync_ = true;
279                         if (step <= 0)
280                                 step=0.01; // user is probably clueless - give a good default
281                         else if (step < 0.00001)
282                                 step=0.00001; // 100K should be enough for anyone
283                         else if (step > 1)
284                                 step=1;
285                 });
286         IMPORT_PLUS(splits,needs_sync_=true);
287         IMPORT_PLUS(sprouts,needs_sync_=true);
288         IMPORT_PLUS(random_factor,needs_sync_=true);
289         IMPORT_PLUS(drag,needs_sync_=true);
290         IMPORT(size);
291         IMPORT(size_as_alpha);
292
293         return Layer_Composite::set_param(param,value);
294 }
295 /*
296 void
297 Plant::set_time(Context context, Time time)const
298 {
299         if(needs_sync==true)
300         {
301                 sync();
302                 needs_sync_=false;
303         }
304         //const_cast<Plant*>(this)->sync();
305         context.set_time(time);
306 }
307
308 void
309 Plant::set_time(Context context, Time time, Vector pos)const
310 {
311         if(needs_sync==true)
312         {
313                 sync();
314                 needs_sync_=false;
315         }
316         //const_cast<Plant*>(this)->sync();
317         context.set_time(time,pos);
318 }
319 */
320 ValueBase
321 Plant::get_param(const String& param)const
322 {
323         if(param=="seed")
324                 return random.get_seed();
325         EXPORT(bline);
326         EXPORT(split_angle);
327         EXPORT(gravity);
328         EXPORT(velocity);
329         EXPORT(perp_velocity);
330         EXPORT(step);
331         EXPORT(gradient);
332         EXPORT(splits);
333         EXPORT(sprouts);
334         EXPORT(random_factor);
335         EXPORT(drag);
336         EXPORT(size);
337
338         EXPORT(size_as_alpha);
339
340         EXPORT_NAME();
341         EXPORT_VERSION();
342
343         return Layer_Composite::get_param(param);
344 }
345
346 Layer::Vocab
347 Plant::get_param_vocab()const
348 {
349         Layer::Vocab ret(Layer_Composite::get_param_vocab());
350
351         ret.push_back(ParamDesc("bline")
352                 .set_local_name(_("Vertices"))
353                 .set_description(_("A list of BLine Points"))
354                 //.set_origin("offset")
355                 //.set_scalar("width")
356         );
357
358         ret.push_back(ParamDesc("gradient")
359                 .set_local_name(_("Gradient"))
360                 .set_description(_("Gradient to be used for coloring the plant"))
361         );
362
363         ret.push_back(ParamDesc("split_angle")
364                 .set_local_name(_("Split Angle"))
365                 .set_description(_("Angle by which each split deviates from its parent"))
366         );
367
368         ret.push_back(ParamDesc("gravity")
369                 .set_local_name(_("Gravity"))
370                 .set_description(_("Direction in which the shoots tend to face"))
371                 .set_is_distance()
372         );
373
374         ret.push_back(ParamDesc("velocity")
375                 .set_local_name(_("Tangential Velocity"))
376                 .set_description(_("Amount to which shoots tend to grow along the tangent to the BLine"))
377         );
378
379         ret.push_back(ParamDesc("perp_velocity")
380                 .set_local_name(_("Perpendicular Velocity"))
381                 .set_description(_("Amount to which shoots tend to grow perpendicular to the tangent to the BLine"))
382         );
383
384         ret.push_back(ParamDesc("size")
385                 .set_local_name(_("Stem Size"))
386                 .set_description(_("Size of the stem"))
387                 .set_is_distance()
388         );
389
390         ret.push_back(ParamDesc("size_as_alpha")
391                 .set_local_name(_("Size As Alpha"))
392                 .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"))
393         );
394
395         ret.push_back(ParamDesc("step")
396                 .set_local_name(_("Step"))
397                 .set_description(_("Measure of the distance between points when rendering"))
398         );
399
400         ret.push_back(ParamDesc("seed")
401                 .set_local_name(_("Seed"))
402                 .set_description(_("Used to seed the pseudo-random number generator"))
403         );
404
405         ret.push_back(ParamDesc("splits")
406                 .set_local_name(_("Splits"))
407                 .set_description(_("Maximum number of times that each sprout can sprout recursively"))
408         );
409
410         ret.push_back(ParamDesc("sprouts")
411                 .set_local_name(_("Sprouts"))
412                 .set_description(_("Number of places that growth occurs on each bline section"))
413         );
414
415         ret.push_back(ParamDesc("random_factor")
416                 .set_local_name(_("Random Factor"))
417                 .set_description(_("Used to scale down all random effects.  Set to zero to disable randomness"))
418         );
419
420         ret.push_back(ParamDesc("drag")
421                 .set_local_name(_("Drag"))
422                 .set_description(_("Drag slows the growth"))
423         );
424
425         return ret;
426 }
427
428 bool
429 Plant::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
430 {
431         bool ret(context.accelerated_render(surface,quality,renddesc,cb));
432         if(is_disabled() || !ret)
433                 return ret;
434
435         Surface dest_surface;
436         dest_surface.set_wh(surface->get_w(),surface->get_h());
437         dest_surface.clear();
438
439         const Point     tl(renddesc.get_tl());
440         const Point br(renddesc.get_br());
441
442         const int       w(renddesc.get_w());
443         const int       h(renddesc.get_h());
444
445         const int       surface_width(surface->get_w());
446         const int       surface_height(surface->get_h());
447
448         // Width and Height of a pixel
449         const Real pw = (br[0] - tl[0]) / w;
450         const Real ph = (br[1] - tl[1]) / h;
451
452         if(needs_sync_==true)
453                 sync();
454
455         std::vector<Particle>::reverse_iterator iter;
456
457         float radius(size*sqrt(1.0f/(abs(pw)*abs(ph))));
458
459         int x1,y1,x2,y2;
460         for(iter=particle_list.rbegin();iter!=particle_list.rend();++iter)
461         {
462                 float scaled_radius(radius);
463                 Color color(iter->color);
464                 if(size_as_alpha)
465                 {
466                         scaled_radius*=color.get_a();
467                         color.set_a(1);
468                 }
469
470                 // previously, radius was multiplied by sqrt(step)*12 only if
471                 // the radius came out at less than 1 (pixel):
472                 //   if (radius<=1.0f) radius*=sqrt(step)*12.0f;
473                 // seems a little arbitrary - does it help?
474
475                 // calculate the box that this particle will be drawn as
476                 float x1f=(iter->point[0]-tl[0])/pw-(scaled_radius*0.5);
477                 float x2f=(iter->point[0]-tl[0])/pw+(scaled_radius*0.5);
478                 float y1f=(iter->point[1]-tl[1])/ph-(scaled_radius*0.5);
479                 float y2f=(iter->point[1]-tl[1])/ph+(scaled_radius*0.5);
480                 x1=ceil_to_int(x1f);
481                 x2=ceil_to_int(x2f)-1;
482                 y1=ceil_to_int(y1f);
483                 y2=ceil_to_int(y2f)-1;
484
485                 // if the box is entirely off the canvas, go to the next particle
486                 if(x1>surface_width || y1>surface_height || x2<0 || y2<0) continue;
487
488                 float x1e=x1-x1f, x2e=x2f-x2, y1e=y1-y1f, y2e=y2f-y2;
489                 // printf("x1e %.4f x2e %.4f y1e %.4f y2e %.4f\n", x1e, x2e, y1e, y2e);
490
491                 // adjust the box so it's entirely on the canvas
492                 if(x1<=0) { x1=0; x1e=0; }
493                 if(y1<=0) { y1=0; y1e=0; }
494                 if(x2>=surface_width)  { x2=surface_width;  x2e=0; }
495                 if(y2>=surface_height) { y2=surface_height; y2e=0; }
496
497                 int w(x2-x1), h(y2-y1);
498
499                 Surface::alpha_pen surface_pen(dest_surface.get_pen(x1,y1),1.0f);
500                 if(w>0 && h>0)
501                         dest_surface.fill(color,surface_pen,w,h);
502
503                 /* the rectangle doesn't cross any vertical pixel boundaries so we don't
504                  * need to draw any top or bottom edges
505                  */
506                 if(x2<x1)
507                 {
508                         // case 1 - a single pixel
509                         if(y2<y1)
510                         {
511                                 surface_pen.move_to(x2,y2);
512                                 surface_pen.set_alpha((x2f-x1f)*(y2f-y1f));
513                                 surface_pen.put_value(color);
514                         }
515                         // case 2 - a single vertical column of pixels
516                         else
517                         {
518                                 surface_pen.move_to(x2,y1-1);
519                                 if (y1e!=0)     // maybe draw top pixel
520                                 {
521                                         surface_pen.set_alpha(y1e*(x2f-x1f));
522                                         surface_pen.put_value(color);
523                                 }
524                                 surface_pen.inc_y();
525                                 surface_pen.set_alpha(x2f-x1f);
526                                 for(int i=y1; i<y2; i++) // maybe draw pixels between
527                                 {
528                                         surface_pen.put_value(color);
529                                         surface_pen.inc_y();
530                                 }
531                                 if (y2e!=0)     // maybe draw bottom pixel
532                                 {
533                                         surface_pen.set_alpha(y2e*(x2f-x1f));
534                                         surface_pen.put_value(color);
535                                 }
536                         }
537                 }
538                 else
539                 {
540                         // case 3 - a single horizontal row of pixels
541                         if(y2<y1)
542                         {
543                                 surface_pen.move_to(x1-1,y2);
544                                 if (x1e!=0)     // maybe draw left pixel
545                                 {
546                                         surface_pen.set_alpha(x1e*(y2f-y1f));
547                                         surface_pen.put_value(color);
548                                 }
549                                 surface_pen.inc_x();
550                                 surface_pen.set_alpha(y2f-y1f);
551                                 for(int i=x1; i<x2; i++) // maybe draw pixels between
552                                 {
553                                         surface_pen.put_value(color);
554                                         surface_pen.inc_x();
555                                 }
556                                 if (x2e!=0)     // maybe draw right pixel
557                                 {
558                                         surface_pen.set_alpha(x2e*(y2f-y1f));
559                                         surface_pen.put_value(color);
560                                 }
561                         }
562                         // case 4 - a proper block of pixels
563                         else
564                         {
565                                 if (x1e!=0)     // maybe draw left edge
566                                 {
567                                         surface_pen.move_to(x1-1,y1-1);
568                                         if (y1e!=0)     // maybe draw top left pixel
569                                         {
570                                                 surface_pen.set_alpha(x1e*y1e);
571                                                 surface_pen.put_value(color);
572                                         }
573                                         surface_pen.inc_y();
574                                         surface_pen.set_alpha(x1e);
575                                         for(int i=y1; i<y2; i++) // maybe draw pixels along the left edge
576                                         {
577                                                 surface_pen.put_value(color);
578                                                 surface_pen.inc_y();
579                                         }
580                                         if (y2e!=0)     // maybe draw bottom left pixel
581                                         {
582                                                 surface_pen.set_alpha(x1e*y2e);
583                                                 surface_pen.put_value(color);
584                                         }
585                                         surface_pen.inc_x();
586                                 }
587                                 else
588                                         surface_pen.move_to(x1,y2);
589
590                                 if (y2e!=0)     // maybe draw bottom edge
591                                 {
592                                         surface_pen.set_alpha(y2e);
593                                         for(int i=x1; i<x2; i++) // maybe draw pixels along the bottom edge
594                                         {
595                                                 surface_pen.put_value(color);
596                                                 surface_pen.inc_x();
597                                         }
598                                         if (x2e!=0)     // maybe draw bottom right pixel
599                                         {
600                                                 surface_pen.set_alpha(x2e*y2e);
601                                                 surface_pen.put_value(color);
602                                         }
603                                         surface_pen.dec_y();
604                                 }
605                                 else
606                                         surface_pen.move_to(x2,y2-1);
607
608                                 if (x2e!=0)     // maybe draw right edge
609                                 {
610                                         surface_pen.set_alpha(x2e);
611                                         for(int i=y1; i<y2; i++) // maybe draw pixels along the right edge
612                                         {
613                                                 surface_pen.put_value(color);
614                                                 surface_pen.dec_y();
615                                         }
616                                         if (y1e!=0)     // maybe draw top right pixel
617                                         {
618                                                 surface_pen.set_alpha(x2e*y1e);
619                                                 surface_pen.put_value(color);
620                                         }
621                                         surface_pen.dec_x();
622                                 }
623                                 else
624                                         surface_pen.move_to(x2-1,y1-1);
625
626                                 if (y1e!=0)     // maybe draw top edge
627                                 {
628                                         surface_pen.set_alpha(y1e);
629                                         for(int i=x1; i<x2; i++) // maybe draw pixels along the top edge
630                                         {
631                                                 surface_pen.put_value(color);
632                                                 surface_pen.dec_x();
633                                         }
634                                 }
635                         }
636                 }
637         }
638
639         Surface::alpha_pen pen(surface->get_pen(0,0),get_amount(),get_blend_method());
640         dest_surface.blit_to(pen);
641
642         return true;
643 }
644
645 Rect
646 Plant::get_bounding_rect(Context context)const
647 {
648         if(needs_sync_==true)
649                 sync();
650
651         if(is_disabled())
652                 return Rect::zero();
653
654         if(Color::is_onto(get_blend_method()))
655                 return context.get_full_bounding_rect() & bounding_rect;
656
657         //if(get_blend_method()==Color::BLEND_BEHIND)
658         //      return context.get_full_bounding_rect() | bounding_rect;
659         return bounding_rect;
660 }