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