Spread the sprouts out evenly along each bline. Previously they appeared at both...
[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(
123                         position,
124                         gradient(t)
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                         bounding_rect.expand(point);
223
224                         Real stunt_growth(random_factor * random(Random::SMOOTH_COSINE,i,f+seg,0.0f,0.0f)/2.0+0.5);
225                         stunt_growth*=stunt_growth;
226
227                         Vector branch_velocity(deriv(f).norm()*velocity);
228
229                         branch_velocity[0] += random_factor * random(Random::SMOOTH_COSINE, 1, f*splits, 0.0f, 0.0f);
230                         branch_velocity[1] += random_factor * random(Random::SMOOTH_COSINE, 2, f*splits, 0.0f, 0.0f);
231
232                         if((((i+1)*sprouts + steps/2) / steps) > branch_count) {
233                                 branch_count++;
234                                 branch(i, 0, 0,          // time
235                                            stunt_growth, // stunt growth
236                                            point, branch_velocity);
237                         }
238                 }
239         }
240
241         needs_sync_=false;
242 }
243
244 bool
245 Plant::set_param(const String & param, const ValueBase &value)
246 {
247         if(param=="bline" && value.get_type()==ValueBase::TYPE_LIST)
248         {
249                 bline=value;
250                 bline_loop=value.get_loop();
251                 needs_sync_=true;
252
253                 return true;
254         }
255         if(param=="seed" && value.same_type_as(int()))
256         {
257                 random.set_seed(value.get(int()));
258                 needs_sync_=true;
259                 return true;
260         }
261         IMPORT_PLUS(split_angle,needs_sync_=true);
262         IMPORT_PLUS(gravity,needs_sync_=true);
263         IMPORT_PLUS(gradient,needs_sync_=true);
264         IMPORT_PLUS(velocity,needs_sync_=true);
265         IMPORT_PLUS(step,needs_sync_=true);
266         IMPORT_PLUS(splits,needs_sync_=true);
267         IMPORT_PLUS(sprouts,needs_sync_=true);
268         IMPORT_PLUS(random_factor,needs_sync_=true);
269         IMPORT_PLUS(drag,needs_sync_=true);
270         IMPORT(size);
271         IMPORT(size_as_alpha);
272
273         return Layer_Composite::set_param(param,value);
274 }
275 /*
276 void
277 Plant::set_time(Context context, Time time)const
278 {
279         if(needs_sync==true)
280         {
281                 sync();
282                 needs_sync_=false;
283         }
284         //const_cast<Plant*>(this)->sync();
285         context.set_time(time);
286 }
287
288 void
289 Plant::set_time(Context context, Time time, Vector pos)const
290 {
291         if(needs_sync==true)
292         {
293                 sync();
294                 needs_sync_=false;
295         }
296         //const_cast<Plant*>(this)->sync();
297         context.set_time(time,pos);
298 }
299 */
300 ValueBase
301 Plant::get_param(const String& param)const
302 {
303         if(param=="seed")
304                 return random.get_seed();
305         EXPORT(bline);
306         EXPORT(split_angle);
307         EXPORT(gravity);
308         EXPORT(velocity);
309         EXPORT(step);
310         EXPORT(gradient);
311         EXPORT(splits);
312         EXPORT(sprouts);
313         EXPORT(random_factor);
314         EXPORT(drag);
315         EXPORT(size);
316
317         EXPORT(size_as_alpha);
318
319         EXPORT_NAME();
320         EXPORT_VERSION();
321
322         return Layer_Composite::get_param(param);
323 }
324
325 Layer::Vocab
326 Plant::get_param_vocab()const
327 {
328         Layer::Vocab ret(Layer_Composite::get_param_vocab());
329
330         ret.push_back(ParamDesc("bline")
331                 .set_local_name(_("Vertices"))
332                 //.set_origin("offset")
333                 //.set_scalar("width")
334                 .set_description(_("A list of BLine Points"))
335         );
336
337         ret.push_back(ParamDesc("gradient")
338                 .set_local_name(_("Gradient"))
339         );
340
341         ret.push_back(ParamDesc("split_angle")
342                 .set_local_name(_("Split Angle"))
343         );
344
345         ret.push_back(ParamDesc("gravity")
346                 .set_local_name(_("Gravity"))
347                 .set_is_distance()
348         );
349
350         ret.push_back(ParamDesc("velocity")
351                 .set_local_name(_("Velocity"))
352         );
353
354         ret.push_back(ParamDesc("size")
355                 .set_local_name(_("Stem Size"))
356                 .set_is_distance()
357         );
358
359         ret.push_back(ParamDesc("size_as_alpha")
360                 .set_local_name(_("Size As Alpha"))
361         );
362
363         ret.push_back(ParamDesc("step")
364                 .set_local_name(_("Step"))
365         );
366
367         ret.push_back(ParamDesc("seed")
368                 .set_local_name(_("Seed"))
369         );
370
371         ret.push_back(ParamDesc("splits")
372                 .set_local_name(_("Splits"))
373         );
374
375         ret.push_back(ParamDesc("sprouts")
376                 .set_local_name(_("Sprouts"))
377         );
378
379         ret.push_back(ParamDesc("random_factor")
380                 .set_local_name(_("Random Factor"))
381         );
382
383         ret.push_back(ParamDesc("drag")
384                 .set_local_name(_("Drag"))
385         );
386
387
388         return ret;
389 }
390
391 bool
392 Plant::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
393 {
394         bool ret(context.accelerated_render(surface,quality,renddesc,cb));
395         if(is_disabled() || !ret)
396                 return ret;
397
398         Surface dest_surface;
399         dest_surface.set_wh(surface->get_w(),surface->get_h());
400         dest_surface.clear();
401
402         const Point     tl(renddesc.get_tl());
403         const Point br(renddesc.get_br());
404
405         const int       w(renddesc.get_w());
406         const int       h(renddesc.get_h());
407
408         // Width and Height of a pixel
409         const Real pw = (br[0] - tl[0]) / w;
410         const Real ph = (br[1] - tl[1]) / h;
411
412         if(needs_sync_==true)
413                 sync();
414
415         std::vector<Particle>::reverse_iterator iter;
416         const float size_factor(1);
417         float radius(size_factor*size*sqrt(1.0f/(abs(pw)*abs(ph)))), temp_radius;
418
419         if(radius>1.0f)
420         {
421                 radius*=1.0;
422                 int x1,y1,x2,y2;
423                 for(iter=particle_list.rbegin();iter!=particle_list.rend();++iter)
424                 {
425                         temp_radius = radius;
426                         float radius(temp_radius);
427                         Color color(iter->color);
428                         if(size_as_alpha)
429                         {
430                                 radius*=color.get_a();
431                                 color.set_a(1);
432                         }
433
434                         x1=ceil_to_int((iter->point[0]-tl[0])/pw-(radius*0.5));
435                         y1=ceil_to_int((iter->point[1]-tl[1])/ph-(radius*0.5));
436                         x2=x1+round_to_int(radius);
437                         y2=y1+round_to_int(radius);
438
439                         if(x1>=surface->get_w() || y1>=surface->get_h())
440                                 continue;
441
442                         if(x2<0 || y2<0)
443                                 continue;
444
445                         if(x2>=surface->get_w())
446                                 x2=surface->get_w();
447                         if(y2>=surface->get_h())
448                                 y2=surface->get_h();
449
450                         if(x1<0)
451                                 x1=0;
452                         if(y1<0)
453                                 y1=0;
454
455                         int w(min(round_to_int(radius),x2-x1));
456                         int h(min(round_to_int(radius),y2-y1));
457
458                         if(w<=0 || h<=0)
459                                 continue;
460
461                         Surface::alpha_pen surface_pen(dest_surface.get_pen(x1,y1),1.0f);
462
463                         dest_surface.fill(color,surface_pen,w,h);
464                 }
465         }
466         else
467         {
468                 //radius/=0.01;
469                 radius*=sqrt(step)*12.0f;
470                 int x,y;
471                 float a,b,c,d;
472                 for(iter=particle_list.rbegin();iter!=particle_list.rend();++iter)
473                 {
474                         temp_radius = radius;
475                         float radius(temp_radius);
476                         Color color(iter->color);
477                         if(size_as_alpha)
478                         {
479                                 radius*=color.get_a();
480                                 color.set_a(1);
481                         }
482
483                         x=floor_to_int((iter->point[0]-tl[0])/pw-0.5f);
484                         y=floor_to_int((iter->point[1]-tl[1])/ph-0.5f);
485
486                         if(x>=surface->get_w()-1 || y>=surface->get_h()-1 || x<0 || y<0)
487                         {
488                                 continue;
489                         }
490
491                         a=((iter->point[0]-tl[0])/pw-0.5f-x)*radius;
492                         b=((iter->point[1]-tl[1])/ph-0.5f-y)*radius;
493                         c=radius-a;
494                         d=radius-b;
495
496                         Surface::alpha_pen surface_pen(dest_surface.get_pen(x,y),1.0f);
497
498                         surface_pen.set_alpha(c*d);
499                         surface_pen.put_value(color);
500                         surface_pen.inc_x();
501                         surface_pen.set_alpha(a*d);
502                         surface_pen.put_value(color);
503                         surface_pen.inc_y();
504                         surface_pen.set_alpha(a*b);
505                         surface_pen.put_value(color);
506                         surface_pen.dec_x();
507                         surface_pen.set_alpha(c*b);
508                         surface_pen.put_value(color);
509                 }
510         }
511
512         Surface::alpha_pen pen(surface->get_pen(0,0),get_amount(),get_blend_method());
513         dest_surface.blit_to(pen);
514
515         return true;
516 }
517
518 Rect
519 Plant::get_bounding_rect(Context context)const
520 {
521         if(needs_sync_==true)
522                 sync();
523
524         if(is_disabled())
525                 return Rect::zero();
526
527         if(Color::is_onto(get_blend_method()))
528                 return context.get_full_bounding_rect() & bounding_rect;
529
530         //if(get_blend_method()==Color::BLEND_BEHIND)
531         //      return context.get_full_bounding_rect() | bounding_rect;
532         return bounding_rect;
533 }