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