converted more mixed tab/space indentations to tabs. only whitespace changes.
[blender.git] / source / blender / render / intern / source / strand.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: none of this file.
24  *
25  * Contributors: Brecht Van Lommel.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 /** \file blender/render/intern/source/strand.c
31  *  \ingroup render
32  */
33
34
35 #include <math.h>
36 #include <string.h>
37 #include <stdlib.h>
38
39 #include "MEM_guardedalloc.h"
40
41 #include "DNA_key_types.h"
42 #include "DNA_material_types.h"
43 #include "DNA_meshdata_types.h"
44
45 #include "BLI_math.h"
46 #include "BLI_blenlib.h"
47 #include "BLI_utildefines.h"
48 #include "BLI_ghash.h"
49 #include "BLI_memarena.h"
50 #include "BLI_rand.h"
51
52 #include "BKE_DerivedMesh.h"
53 #include "BKE_key.h"
54
55
56 #include "render_types.h"
57 #include "initrender.h"
58 #include "rendercore.h"
59 #include "renderdatabase.h"
60 #include "renderpipeline.h"
61 #include "pixelblending.h"
62 #include "shading.h"
63 #include "strand.h"
64 #include "zbuf.h"
65
66 /* to be removed */
67 void hoco_to_zco(ZSpan *zspan, float *zco, float *hoco);
68 void zspan_scanconvert_strand(ZSpan *zspan, void *handle, float *v1, float *v2, float *v3, void (*func)(void *, int, int, float, float, float) );
69 void zbufsinglewire(ZSpan *zspan, int obi, int zvlnr, float *ho1, float *ho2);
70
71 /* *************** */
72
73 static float strand_eval_width(Material *ma, float strandco)
74 {
75         float fac;
76
77         strandco= 0.5f*(strandco + 1.0f);
78
79         if(ma->strand_ease!=0.0f) {
80                 if(ma->strand_ease<0.0f)
81                         fac= pow(strandco, 1.0+ma->strand_ease);
82                 else
83                         fac= pow(strandco, 1.0/(1.0f-ma->strand_ease));
84         }
85         else fac= strandco;
86         
87         return ((1.0f-fac)*ma->strand_sta + (fac)*ma->strand_end);
88 }
89
90 void strand_eval_point(StrandSegment *sseg, StrandPoint *spoint)
91 {
92         Material *ma;
93         StrandBuffer *strandbuf;
94         float *simplify;
95         float p[4][3], data[4], cross[3], crosslen, w, dx, dy, t;
96         int type;
97
98         strandbuf= sseg->buffer;
99         ma= sseg->buffer->ma;
100         t= spoint->t;
101         type= (strandbuf->flag & R_STRAND_BSPLINE)? KEY_BSPLINE: KEY_CARDINAL;
102
103         VECCOPY(p[0], sseg->v[0]->co);
104         VECCOPY(p[1], sseg->v[1]->co);
105         VECCOPY(p[2], sseg->v[2]->co);
106         VECCOPY(p[3], sseg->v[3]->co);
107
108         if(sseg->obi->flag & R_TRANSFORMED) {
109                 mul_m4_v3(sseg->obi->mat, p[0]);
110                 mul_m4_v3(sseg->obi->mat, p[1]);
111                 mul_m4_v3(sseg->obi->mat, p[2]);
112                 mul_m4_v3(sseg->obi->mat, p[3]);
113         }
114
115         if(t == 0.0f) {
116                 VECCOPY(spoint->co, p[1]);
117                 spoint->strandco= sseg->v[1]->strandco;
118
119                 spoint->dtstrandco= (sseg->v[2]->strandco - sseg->v[0]->strandco);
120                 if(sseg->v[0] != sseg->v[1])
121                         spoint->dtstrandco *= 0.5f;
122         }
123         else if(t == 1.0f) {
124                 VECCOPY(spoint->co, p[2]);
125                 spoint->strandco= sseg->v[2]->strandco;
126
127                 spoint->dtstrandco= (sseg->v[3]->strandco - sseg->v[1]->strandco);
128                 if(sseg->v[3] != sseg->v[2])
129                         spoint->dtstrandco *= 0.5f;
130         }
131         else {
132                 key_curve_position_weights(t, data, type);
133                 spoint->co[0]= data[0]*p[0][0] + data[1]*p[1][0] + data[2]*p[2][0] + data[3]*p[3][0];
134                 spoint->co[1]= data[0]*p[0][1] + data[1]*p[1][1] + data[2]*p[2][1] + data[3]*p[3][1];
135                 spoint->co[2]= data[0]*p[0][2] + data[1]*p[1][2] + data[2]*p[2][2] + data[3]*p[3][2];
136                 spoint->strandco= (1.0f-t)*sseg->v[1]->strandco + t*sseg->v[2]->strandco;
137         }
138
139         key_curve_tangent_weights(t, data, type);
140         spoint->dtco[0]= data[0]*p[0][0] + data[1]*p[1][0] + data[2]*p[2][0] + data[3]*p[3][0];
141         spoint->dtco[1]= data[0]*p[0][1] + data[1]*p[1][1] + data[2]*p[2][1] + data[3]*p[3][1];
142         spoint->dtco[2]= data[0]*p[0][2] + data[1]*p[1][2] + data[2]*p[2][2] + data[3]*p[3][2];
143
144         VECCOPY(spoint->tan, spoint->dtco);
145         normalize_v3(spoint->tan);
146
147         VECCOPY(spoint->nor, spoint->co);
148         VECMUL(spoint->nor, -1.0f);
149         normalize_v3(spoint->nor);
150
151         spoint->width= strand_eval_width(ma, spoint->strandco);
152         
153         /* simplification */
154         simplify= RE_strandren_get_simplify(strandbuf->obr, sseg->strand, 0);
155         spoint->alpha= (simplify)? simplify[1]: 1.0f;
156
157         /* outer points */
158         cross_v3_v3v3(cross, spoint->co, spoint->tan);
159
160         w= spoint->co[2]*strandbuf->winmat[2][3] + strandbuf->winmat[3][3];
161         dx= strandbuf->winx*cross[0]*strandbuf->winmat[0][0]/w;
162         dy= strandbuf->winy*cross[1]*strandbuf->winmat[1][1]/w;
163         w= sqrt(dx*dx + dy*dy);
164
165         if(w > 0.0f) {
166                 if(strandbuf->flag & R_STRAND_B_UNITS) {
167                         crosslen= len_v3(cross);
168                         w= 2.0f*crosslen*strandbuf->minwidth/w;
169
170                         if(spoint->width < w) {
171                                 spoint->alpha= spoint->width/w;
172                                 spoint->width= w;
173                         }
174
175                         if(simplify)
176                                 /* squared because we only change width, not length */
177                                 spoint->width *= simplify[0]*simplify[0];
178
179                         mul_v3_fl(cross, spoint->width*0.5f/crosslen);
180                 }
181                 else
182                         mul_v3_fl(cross, spoint->width/w);
183         }
184
185         sub_v3_v3v3(spoint->co1, spoint->co, cross);
186         add_v3_v3v3(spoint->co2, spoint->co, cross);
187
188         VECCOPY(spoint->dsco, cross);
189 }
190
191 /* *************** */
192
193 static void interpolate_vec1(float *v1, float *v2, float t, float negt, float *v)
194 {
195         v[0]= negt*v1[0] + t*v2[0];
196 }
197
198 static void interpolate_vec3(float *v1, float *v2, float t, float negt, float *v)
199 {
200         v[0]= negt*v1[0] + t*v2[0];
201         v[1]= negt*v1[1] + t*v2[1];
202         v[2]= negt*v1[2] + t*v2[2];
203 }
204
205 static void interpolate_vec4(float *v1, float *v2, float t, float negt, float *v)
206 {
207         v[0]= negt*v1[0] + t*v2[0];
208         v[1]= negt*v1[1] + t*v2[1];
209         v[2]= negt*v1[2] + t*v2[2];
210         v[3]= negt*v1[3] + t*v2[3];
211 }
212
213 void interpolate_shade_result(ShadeResult *shr1, ShadeResult *shr2, float t, ShadeResult *shr, int addpassflag)
214 {
215         float negt= 1.0f - t;
216
217         interpolate_vec4(shr1->combined, shr2->combined, t, negt, shr->combined);
218
219         if(addpassflag & SCE_PASS_VECTOR) {
220                 interpolate_vec4(shr1->winspeed, shr2->winspeed, t, negt, shr->winspeed);
221         }
222         /* optim... */
223         if(addpassflag & ~(SCE_PASS_VECTOR)) {
224                 if(addpassflag & SCE_PASS_Z)
225                         interpolate_vec1(&shr1->z, &shr2->z, t, negt, &shr->z);
226                 if(addpassflag & SCE_PASS_RGBA)
227                         interpolate_vec4(shr1->col, shr2->col, t, negt, shr->col);
228                 if(addpassflag & SCE_PASS_NORMAL) {
229                         interpolate_vec3(shr1->nor, shr2->nor, t, negt, shr->nor);
230                         normalize_v3(shr->nor);
231                 }
232                 if(addpassflag & SCE_PASS_EMIT)
233                         interpolate_vec3(shr1->emit, shr2->emit, t, negt, shr->emit);
234                 if(addpassflag & SCE_PASS_DIFFUSE)
235                         interpolate_vec3(shr1->diff, shr2->diff, t, negt, shr->diff);
236                 if(addpassflag & SCE_PASS_SPEC)
237                         interpolate_vec3(shr1->spec, shr2->spec, t, negt, shr->spec);
238                 if(addpassflag & SCE_PASS_SHADOW)
239                         interpolate_vec3(shr1->shad, shr2->shad, t, negt, shr->shad);
240                 if(addpassflag & SCE_PASS_AO)
241                         interpolate_vec3(shr1->ao, shr2->ao, t, negt, shr->ao);
242                 if(addpassflag & SCE_PASS_ENVIRONMENT)
243                         interpolate_vec3(shr1->env, shr2->env, t, negt, shr->env);
244                 if(addpassflag & SCE_PASS_INDIRECT)
245                         interpolate_vec3(shr1->indirect, shr2->indirect, t, negt, shr->indirect);
246                 if(addpassflag & SCE_PASS_REFLECT)
247                         interpolate_vec3(shr1->refl, shr2->refl, t, negt, shr->refl);
248                 if(addpassflag & SCE_PASS_REFRACT)
249                         interpolate_vec3(shr1->refr, shr2->refr, t, negt, shr->refr);
250                 if(addpassflag & SCE_PASS_MIST)
251                         interpolate_vec1(&shr1->mist, &shr2->mist, t, negt, &shr->mist);
252         }
253 }
254
255 void strand_apply_shaderesult_alpha(ShadeResult *shr, float alpha)
256 {
257         if(alpha < 1.0f) {
258                 shr->combined[0] *= alpha;
259                 shr->combined[1] *= alpha;
260                 shr->combined[2] *= alpha;
261                 shr->combined[3] *= alpha;
262
263                 shr->col[0] *= alpha;
264                 shr->col[1] *= alpha;
265                 shr->col[2] *= alpha;
266                 shr->col[3] *= alpha;
267
268                 shr->alpha *= alpha;
269         }
270 }
271
272 static void strand_shade_point(Render *re, ShadeSample *ssamp, StrandSegment *sseg, StrandVert *svert, StrandPoint *spoint)
273 {
274         ShadeInput *shi= ssamp->shi;
275         ShadeResult *shr= ssamp->shr;
276         VlakRen vlr;
277         int seed;
278
279         memset(&vlr, 0, sizeof(vlr));
280         vlr.flag= R_SMOOTH;
281         if(sseg->buffer->ma->mode & MA_TANGENT_STR)
282                 vlr.flag |= R_TANGENT;
283
284         shi->vlr= &vlr;
285         shi->v1= NULL;
286         shi->v2= NULL;
287         shi->v3= NULL;
288         shi->strand= sseg->strand;
289         shi->obi= sseg->obi;
290         shi->obr= sseg->obi->obr;
291
292         /* cache for shadow */
293         shi->samplenr= re->shadowsamplenr[shi->thread]++;
294
295         /* all samples */
296         shi->mask= 0xFFFF;
297
298         /* seed RNG for consistent results across tiles */
299         seed = shi->strand->index + (svert - shi->strand->vert);
300         BLI_thread_srandom(shi->thread, seed);
301
302         shade_input_set_strand(shi, sseg->strand, spoint);
303         shade_input_set_strand_texco(shi, sseg->strand, sseg->v[1], spoint);
304         
305         /* init material vars */
306         shade_input_init_material(shi);
307         
308         /* shade */
309         shade_samples_do_AO(ssamp);
310         shade_input_do_shade(shi, shr);
311
312         /* apply simplification */
313         strand_apply_shaderesult_alpha(shr, spoint->alpha);
314
315         /* include lamphalos for strand, since halo layer was added already */
316         if(re->flag & R_LAMPHALO)
317                 if(shi->layflag & SCE_LAY_HALO)
318                         renderspothalo(shi, shr->combined, shr->combined[3]);
319         
320         shi->strand= NULL;
321 }
322
323 /* *************** */
324
325 struct StrandShadeCache {
326         GHash *resulthash;
327         GHash *refcounthash;
328         MemArena *memarena;
329 };
330
331 StrandShadeCache *strand_shade_cache_create(void)
332 {
333         StrandShadeCache *cache;
334
335         cache= MEM_callocN(sizeof(StrandShadeCache), "StrandShadeCache");
336         cache->resulthash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, "strand_shade_cache_create1 gh");
337         cache->refcounthash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, "strand_shade_cache_create2 gh");
338         cache->memarena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "strand shade cache arena");
339         
340         return cache;
341 }
342
343 void strand_shade_cache_free(StrandShadeCache *cache)
344 {
345         BLI_ghash_free(cache->refcounthash, NULL, NULL);
346         BLI_ghash_free(cache->resulthash, NULL, (GHashValFreeFP)MEM_freeN);
347         BLI_memarena_free(cache->memarena);
348         MEM_freeN(cache);
349 }
350
351 static void strand_shade_get(Render *re, StrandShadeCache *cache, ShadeSample *ssamp, StrandSegment *sseg, StrandVert *svert)
352 {
353         ShadeResult *hashshr;
354         StrandPoint p;
355         int *refcount;
356
357         hashshr= BLI_ghash_lookup(cache->resulthash, svert);
358         refcount= BLI_ghash_lookup(cache->refcounthash, svert);
359
360         if(!hashshr) {
361                 /* not shaded yet, shade and insert into hash */
362                 p.t= (sseg->v[1] == svert)? 0.0f: 1.0f;
363                 strand_eval_point(sseg, &p);
364                 strand_shade_point(re, ssamp, sseg, svert, &p);
365
366                 hashshr= MEM_callocN(sizeof(ShadeResult), "HashShadeResult");
367                 *hashshr= ssamp->shr[0];
368                 BLI_ghash_insert(cache->resulthash, svert, hashshr);
369         }
370         else
371                 /* already shaded, just copy previous result from hash */
372                 ssamp->shr[0]= *hashshr;
373         
374         /* lower reference count and remove if not needed anymore by any samples */
375         (*refcount)--;
376         if(*refcount == 0) {
377                 BLI_ghash_remove(cache->resulthash, svert, NULL, (GHashValFreeFP)MEM_freeN);
378                 BLI_ghash_remove(cache->refcounthash, svert, NULL, NULL);
379         }
380 }
381
382 void strand_shade_segment(Render *re, StrandShadeCache *cache, StrandSegment *sseg, ShadeSample *ssamp, float t, float s, int addpassflag)
383 {
384         ShadeResult shr1, shr2;
385
386         /* get shading for two endpoints and interpolate */
387         strand_shade_get(re, cache, ssamp, sseg, sseg->v[1]);
388         shr1= ssamp->shr[0];
389         strand_shade_get(re, cache, ssamp, sseg, sseg->v[2]);
390         shr2= ssamp->shr[0];
391
392         interpolate_shade_result(&shr1, &shr2, t, ssamp->shr, addpassflag);
393
394         /* apply alpha along width */
395         if(sseg->buffer->widthfade != 0.0f) {
396                 s = 1.0f - pow(fabs(s), sseg->buffer->widthfade);
397
398                 strand_apply_shaderesult_alpha(ssamp->shr, s);
399         }
400 }
401
402 void strand_shade_unref(StrandShadeCache *cache, StrandVert *svert)
403 {
404         int *refcount;
405
406         /* lower reference count and remove if not needed anymore by any samples */
407         refcount= BLI_ghash_lookup(cache->refcounthash, svert);
408
409         (*refcount)--;
410         if(*refcount == 0) {
411                 BLI_ghash_remove(cache->resulthash, svert, NULL, (GHashValFreeFP)MEM_freeN);
412                 BLI_ghash_remove(cache->refcounthash, svert, NULL, NULL);
413         }
414 }
415
416 static void strand_shade_refcount(StrandShadeCache *cache, StrandVert *svert)
417 {
418         int *refcount= BLI_ghash_lookup(cache->refcounthash, svert);
419
420         if(!refcount) {
421                 refcount= BLI_memarena_alloc(cache->memarena, sizeof(int));
422                 *refcount= 1;
423                 BLI_ghash_insert(cache->refcounthash, svert, refcount);
424         }
425         else
426                 (*refcount)++;
427 }
428
429 /* *************** */
430
431 typedef struct StrandPart {
432         Render *re;
433         ZSpan *zspan;
434
435         APixstrand *apixbuf;
436         int *totapixbuf;
437         int *rectz;
438         int *rectmask;
439         intptr_t *rectdaps;
440         int rectx, recty;
441         int sample;
442         int shadow;
443         float (*jit)[2];
444
445         StrandSegment *segment;
446         float t[3], s[3];
447
448         StrandShadeCache *cache;
449 } StrandPart;
450
451 typedef struct StrandSortSegment {
452         struct StrandSortSegment *next;
453         int obi, strand, segment;
454         float z;
455 } StrandSortSegment;
456
457 static int compare_strand_segment(const void *poin1, const void *poin2)
458 {
459         const StrandSortSegment *seg1= (const StrandSortSegment*)poin1;
460         const StrandSortSegment *seg2= (const StrandSortSegment*)poin2;
461
462         if(seg1->z < seg2->z)
463                 return -1;
464         else if(seg1->z == seg2->z)
465                 return 0;
466         else
467                 return 1;
468 }
469
470 static void do_strand_point_project(float winmat[][4], ZSpan *zspan, float *co, float *hoco, float *zco)
471 {
472         projectvert(co, winmat, hoco);
473         hoco_to_zco(zspan, zco, hoco);
474 }
475
476 static void strand_project_point(float winmat[][4], float winx, float winy, StrandPoint *spoint)
477 {
478         float div;
479
480         projectvert(spoint->co, winmat, spoint->hoco);
481
482         div= 1.0f/spoint->hoco[3];
483         spoint->x= spoint->hoco[0]*div*winx*0.5f;
484         spoint->y= spoint->hoco[1]*div*winy*0.5f;
485 }
486
487 static APixstrand *addpsmainAstrand(ListBase *lb)
488 {
489         APixstrMain *psm;
490
491         psm= MEM_mallocN(sizeof(APixstrMain), "addpsmainA");
492         BLI_addtail(lb, psm);
493         psm->ps= MEM_callocN(4096*sizeof(APixstrand),"pixstr");
494
495         return psm->ps;
496 }
497
498 static APixstrand *addpsAstrand(ZSpan *zspan)
499 {
500         /* make new PS */
501         if(zspan->apstrandmcounter==0) {
502                 zspan->curpstrand= addpsmainAstrand(zspan->apsmbase);
503                 zspan->apstrandmcounter= 4095;
504         }
505         else {
506                 zspan->curpstrand++;
507                 zspan->apstrandmcounter--;
508         }
509         return zspan->curpstrand;
510 }
511
512 #define MAX_ZROW        2000
513
514 static void do_strand_fillac(void *handle, int x, int y, float u, float v, float z)
515 {
516         StrandPart *spart= (StrandPart*)handle;
517         StrandShadeCache *cache= spart->cache;
518         StrandSegment *sseg= spart->segment;
519         APixstrand *apn, *apnew;
520         float t, s;
521         int offset, mask, obi, strnr, seg, zverg, bufferz, maskz=0;
522
523         offset = y*spart->rectx + x;
524         obi= sseg->obi - spart->re->objectinstance;
525         strnr= sseg->strand->index + 1;
526         seg= sseg->v[1] - sseg->strand->vert;
527         mask= (1<<spart->sample);
528
529         /* check against solid z-buffer */
530         zverg= (int)z;
531
532         if(spart->rectdaps) {
533                 /* find the z of the sample */
534                 PixStr *ps;
535                 intptr_t *rd= spart->rectdaps + offset;
536                 
537                 bufferz= 0x7FFFFFFF;
538                 if(spart->rectmask) maskz= 0x7FFFFFFF;
539                 
540                 if(*rd) {       
541                         for(ps= (PixStr *)(*rd); ps; ps= ps->next) {
542                                 if(mask & ps->mask) {
543                                         bufferz= ps->z;
544                                         if(spart->rectmask)
545                                                 maskz= ps->maskz;
546                                         break;
547                                 }
548                         }
549                 }
550         }
551         else {
552                 bufferz= (spart->rectz)? spart->rectz[offset]: 0x7FFFFFFF;
553                 if(spart->rectmask)
554                         maskz= spart->rectmask[offset];
555         }
556
557 #define CHECK_ADD(n) \
558         if(apn->p[n]==strnr && apn->obi[n]==obi && apn->seg[n]==seg) \
559         { if(!(apn->mask[n] & mask)) { apn->mask[n] |= mask; apn->v[n] += t; apn->u[n] += s; } break; }
560 #define CHECK_ASSIGN(n) \
561         if(apn->p[n]==0) \
562         {apn->obi[n]= obi; apn->p[n]= strnr; apn->z[n]= zverg; apn->mask[n]= mask; apn->v[n]= t; apn->u[n]= s; apn->seg[n]= seg; break; }
563
564         /* add to pixel list */
565         if(zverg < bufferz && (spart->totapixbuf[offset] < MAX_ZROW)) {
566                 if(!spart->rectmask || zverg > maskz) {
567                         t = u*spart->t[0] + v*spart->t[1] + (1.0f-u-v)*spart->t[2];
568                         s = fabs(u*spart->s[0] + v*spart->s[1] + (1.0f-u-v)*spart->s[2]);
569
570                         apn= spart->apixbuf + offset;
571                         while(apn) {
572                                 CHECK_ADD(0);
573                                 CHECK_ADD(1);
574                                 CHECK_ADD(2);
575                                 CHECK_ADD(3);
576                                 CHECK_ASSIGN(0);
577                                 CHECK_ASSIGN(1);
578                                 CHECK_ASSIGN(2);
579                                 CHECK_ASSIGN(3);
580
581                                 apnew= addpsAstrand(spart->zspan);
582                                 SWAP(APixstrand, *apnew, *apn);
583                                 apn->next= apnew;
584                                 CHECK_ASSIGN(0);
585                         }
586
587                         if(cache) {
588                                 strand_shade_refcount(cache, sseg->v[1]);
589                                 strand_shade_refcount(cache, sseg->v[2]);
590                         }
591                         spart->totapixbuf[offset]++;
592                 }
593         }
594 }
595
596 /* width is calculated in hoco space, to ensure strands are visible */
597 static int strand_test_clip(float winmat[][4], ZSpan *zspan, float *bounds, float *co, float *zcomp, float widthx, float widthy)
598 {
599         float hoco[4];
600         int clipflag= 0;
601
602         projectvert(co, winmat, hoco);
603
604         /* we compare z without perspective division for segment sorting */
605         *zcomp= hoco[2];
606
607         if(hoco[0]+widthx < bounds[0]*hoco[3]) clipflag |= 1;
608         else if(hoco[0]-widthx > bounds[1]*hoco[3]) clipflag |= 2;
609         
610         if(hoco[1]-widthy > bounds[3]*hoco[3]) clipflag |= 4;
611         else if(hoco[1]+widthy < bounds[2]*hoco[3]) clipflag |= 8;
612
613         clipflag |= testclip(hoco);
614
615         return clipflag;
616 }
617
618 static void do_scanconvert_strand(Render *re, StrandPart *spart, ZSpan *zspan, float t, float dt, float *co1, float *co2, float *co3, float *co4, int sample)
619 {
620         float jco1[3], jco2[3], jco3[3], jco4[3], jx, jy;
621
622         VECCOPY(jco1, co1);
623         VECCOPY(jco2, co2);
624         VECCOPY(jco3, co3);
625         VECCOPY(jco4, co4);
626
627         if(spart->jit) {
628                 jx= -spart->jit[sample][0];
629                 jy= -spart->jit[sample][1];
630
631                 jco1[0] += jx; jco1[1] += jy;
632                 jco2[0] += jx; jco2[1] += jy;
633                 jco3[0] += jx; jco3[1] += jy;
634                 jco4[0] += jx; jco4[1] += jy;
635
636                 /* XXX mblur? */
637         }
638
639         spart->sample= sample;
640
641         spart->t[0]= t-dt;
642         spart->s[0]= -1.0f;
643         spart->t[1]= t-dt;
644         spart->s[1]= 1.0f;
645         spart->t[2]= t;
646         spart->s[2]= 1.0f;
647         zspan_scanconvert_strand(zspan, spart, jco1, jco2, jco3, do_strand_fillac);
648         spart->t[0]= t-dt;
649         spart->s[0]= -1.0f;
650         spart->t[1]= t;
651         spart->s[1]= 1.0f;
652         spart->t[2]= t;
653         spart->s[2]= -1.0f;
654         zspan_scanconvert_strand(zspan, spart, jco1, jco3, jco4, do_strand_fillac);
655 }
656
657 static void strand_render(Render *re, StrandSegment *sseg, float winmat[][4], StrandPart *spart, ZSpan *zspan, int totzspan, StrandPoint *p1, StrandPoint *p2)
658 {
659         if(spart) {
660                 float t= p2->t;
661                 float dt= p2->t - p1->t;
662                 int a;
663
664                 if(re->osa) {
665                         for(a=0; a<re->osa; a++)
666                                 do_scanconvert_strand(re, spart, zspan, t, dt, p1->zco2, p1->zco1, p2->zco1, p2->zco2, a);
667                 }
668                 else
669                         do_scanconvert_strand(re, spart, zspan, t, dt, p1->zco2, p1->zco1, p2->zco1, p2->zco2, 0);
670         }
671         else {
672                 float hoco1[4], hoco2[4];
673                 int a, obi, index;
674   
675                 obi= sseg->obi - re->objectinstance;
676                 index= sseg->strand->index;
677
678                 projectvert(p1->co, winmat, hoco1);
679                 projectvert(p2->co, winmat, hoco2);
680
681   
682                 for(a=0; a<totzspan; a++) {
683 #if 0
684                         /* render both strand and single pixel wire to counter aliasing */
685                         zbufclip4(re, &zspan[a], obi, index, p1->hoco2, p1->hoco1, p2->hoco1, p2->hoco2, p1->clip2, p1->clip1, p2->clip1, p2->clip2);
686 #endif
687                         /* only render a line for now, which makes the shadow map more
688                            similiar across frames, and so reduces flicker */
689                         zbufsinglewire(&zspan[a], obi, index, hoco1, hoco2);
690                 }
691         }
692 }
693
694 static int strand_segment_recursive(Render *re, float winmat[][4], StrandPart *spart, ZSpan *zspan, int totzspan, StrandSegment *sseg, StrandPoint *p1, StrandPoint *p2, int depth)
695 {
696         StrandPoint p;
697         StrandBuffer *buffer= sseg->buffer;
698         float dot, d1[2], d2[2], len1, len2;
699
700         if(depth == buffer->maxdepth)
701                 return 0;
702
703         p.t= (p1->t + p2->t)*0.5f;
704         strand_eval_point(sseg, &p);
705         strand_project_point(buffer->winmat, buffer->winx, buffer->winy, &p);
706
707         d1[0]= (p.x - p1->x);
708         d1[1]= (p.y - p1->y);
709         len1= d1[0]*d1[0] + d1[1]*d1[1];
710
711         d2[0]= (p2->x - p.x);
712         d2[1]= (p2->y - p.y);
713         len2= d2[0]*d2[0] + d2[1]*d2[1];
714
715         if(len1 == 0.0f || len2 == 0.0f)
716                 return 0;
717         
718         dot= d1[0]*d2[0] + d1[1]*d2[1];
719         if(dot*dot > sseg->sqadaptcos*len1*len2)
720                 return 0;
721
722         if(spart) {
723                 do_strand_point_project(winmat, zspan, p.co1, p.hoco1, p.zco1);
724                 do_strand_point_project(winmat, zspan, p.co2, p.hoco2, p.zco2);
725         }
726         else {
727 #if 0
728                 projectvert(p.co1, winmat, p.hoco1);
729                 projectvert(p.co2, winmat, p.hoco2);
730                 p.clip1= testclip(p.hoco1);
731                 p.clip2= testclip(p.hoco2);
732 #endif
733         }
734
735         if(!strand_segment_recursive(re, winmat, spart, zspan, totzspan, sseg, p1, &p, depth+1))
736                 strand_render(re, sseg, winmat, spart, zspan, totzspan, p1, &p);
737         if(!strand_segment_recursive(re, winmat, spart, zspan, totzspan, sseg, &p, p2, depth+1))
738                 strand_render(re, sseg, winmat, spart, zspan, totzspan, &p, p2);
739         
740         return 1;
741 }
742
743 void render_strand_segment(Render *re, float winmat[][4], StrandPart *spart, ZSpan *zspan, int totzspan, StrandSegment *sseg)
744 {
745         StrandBuffer *buffer= sseg->buffer;
746         StrandPoint *p1= &sseg->point1;
747         StrandPoint *p2= &sseg->point2;
748
749         p1->t= 0.0f;
750         p2->t= 1.0f;
751
752         strand_eval_point(sseg, p1);
753         strand_project_point(buffer->winmat, buffer->winx, buffer->winy, p1);
754         strand_eval_point(sseg, p2);
755         strand_project_point(buffer->winmat, buffer->winx, buffer->winy, p2);
756
757         if(spart) {
758                 do_strand_point_project(winmat, zspan, p1->co1, p1->hoco1, p1->zco1);
759                 do_strand_point_project(winmat, zspan, p1->co2, p1->hoco2, p1->zco2);
760                 do_strand_point_project(winmat, zspan, p2->co1, p2->hoco1, p2->zco1);
761                 do_strand_point_project(winmat, zspan, p2->co2, p2->hoco2, p2->zco2);
762         }
763         else {
764 #if 0
765                 projectvert(p1->co1, winmat, p1->hoco1);
766                 projectvert(p1->co2, winmat, p1->hoco2);
767                 projectvert(p2->co1, winmat, p2->hoco1);
768                 projectvert(p2->co2, winmat, p2->hoco2);
769                 p1->clip1= testclip(p1->hoco1);
770                 p1->clip2= testclip(p1->hoco2);
771                 p2->clip1= testclip(p2->hoco1);
772                 p2->clip2= testclip(p2->hoco2);
773 #endif
774         }
775
776         if(!strand_segment_recursive(re, winmat, spart, zspan, totzspan, sseg, p1, p2, 0))
777                 strand_render(re, sseg, winmat, spart, zspan, totzspan, p1, p2);
778 }
779
780 /* render call to fill in strands */
781 int zbuffer_strands_abuf(Render *re, RenderPart *pa, APixstrand *apixbuf, ListBase *apsmbase, unsigned int lay, int negzmask, float winmat[][4], int winx, int winy, int sample, float (*jit)[2], float clipcrop, int shadow, StrandShadeCache *cache)
782 {
783         ObjectRen *obr;
784         ObjectInstanceRen *obi;
785         ZSpan zspan;
786         StrandRen *strand=0;
787         StrandVert *svert;
788         StrandBound *sbound;
789         StrandPart spart;
790         StrandSegment sseg;
791         StrandSortSegment *sortsegments = NULL, *sortseg, *firstseg;
792         MemArena *memarena;
793         float z[4], bounds[4], obwinmat[4][4];
794         int a, b, c, i, totsegment, clip[4];
795
796         if(re->test_break(re->tbh))
797                 return 0;
798         if(re->totstrand == 0)
799                 return 0;
800
801         /* setup StrandPart */
802         memset(&spart, 0, sizeof(spart));
803
804         spart.re= re;
805         spart.rectx= pa->rectx;
806         spart.recty= pa->recty;
807         spart.apixbuf= apixbuf;
808         spart.zspan= &zspan;
809         spart.rectdaps= pa->rectdaps;
810         spart.rectz= pa->rectz;
811         spart.rectmask= pa->rectmask;
812         spart.cache= cache;
813         spart.shadow= shadow;
814         spart.jit= jit;
815
816         zbuf_alloc_span(&zspan, pa->rectx, pa->recty, clipcrop);
817
818         /* needed for transform from hoco to zbuffer co */
819         zspan.zmulx= ((float)winx)/2.0;
820         zspan.zmuly= ((float)winy)/2.0;
821         
822         zspan.zofsx= -pa->disprect.xmin;
823         zspan.zofsy= -pa->disprect.ymin;
824
825         /* to center the sample position */
826         if(!shadow) {
827                 zspan.zofsx -= 0.5f;
828                 zspan.zofsy -= 0.5f;
829         }
830
831         zspan.apsmbase= apsmbase;
832
833         /* clipping setup */
834         bounds[0]= (2*pa->disprect.xmin - winx-1)/(float)winx;
835         bounds[1]= (2*pa->disprect.xmax - winx+1)/(float)winx;
836         bounds[2]= (2*pa->disprect.ymin - winy-1)/(float)winy;
837         bounds[3]= (2*pa->disprect.ymax - winy+1)/(float)winy;
838
839         memarena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "strand sort arena");
840         firstseg= NULL;
841         sortseg= sortsegments;
842         totsegment= 0;
843
844         /* for all object instances */
845         for(obi=re->instancetable.first, i=0; obi; obi=obi->next, i++) {
846                 Material *ma;
847                 float widthx, widthy;
848
849                 obr= obi->obr;
850
851                 if(!obr->strandbuf || !(obr->strandbuf->lay & lay))
852                         continue;
853
854                 /* compute matrix and try clipping whole object */
855                 if(obi->flag & R_TRANSFORMED)
856                         mul_m4_m4m4(obwinmat, obi->mat, winmat);
857                 else
858                         copy_m4_m4(obwinmat, winmat);
859
860                 /* test if we should skip it */
861                 ma = obr->strandbuf->ma;
862
863                 if(shadow && !(ma->mode & MA_SHADBUF))
864                         continue;
865                 else if(!shadow && (ma->mode & MA_ONLYCAST))
866                         continue;
867
868                 if(clip_render_object(obi->obr->boundbox, bounds, obwinmat))
869                         continue;
870                 
871                 widthx= obr->strandbuf->maxwidth*obwinmat[0][0];
872                 widthy= obr->strandbuf->maxwidth*obwinmat[1][1];
873
874                 /* for each bounding box containing a number of strands */
875                 sbound= obr->strandbuf->bound;
876                 for(c=0; c<obr->strandbuf->totbound; c++, sbound++) {
877                         if(clip_render_object(sbound->boundbox, bounds, obwinmat))
878                                 continue;
879
880                         /* for each strand in this bounding box */
881                         for(a=sbound->start; a<sbound->end; a++) {
882                                 strand= RE_findOrAddStrand(obr, a);
883                                 svert= strand->vert;
884
885                                 /* keep clipping and z depth for 4 control points */
886                                 clip[1]= strand_test_clip(obwinmat, &zspan, bounds, svert->co, &z[1], widthx, widthy);
887                                 clip[2]= strand_test_clip(obwinmat, &zspan, bounds, (svert+1)->co, &z[2], widthx, widthy);
888                                 clip[0]= clip[1]; z[0]= z[1];
889
890                                 for(b=0; b<strand->totvert-1; b++, svert++) {
891                                         /* compute 4th point clipping and z depth */
892                                         if(b < strand->totvert-2) {
893                                                 clip[3]= strand_test_clip(obwinmat, &zspan, bounds, (svert+2)->co, &z[3], widthx, widthy);
894                                         }
895                                         else {
896                                                 clip[3]= clip[2]; z[3]= z[2];
897                                         }
898
899                                         /* check clipping and add to sortsegments buffer */
900                                         if(!(clip[0] & clip[1] & clip[2] & clip[3])) {
901                                                 sortseg= BLI_memarena_alloc(memarena, sizeof(StrandSortSegment));
902                                                 sortseg->obi= i;
903                                                 sortseg->strand= strand->index;
904                                                 sortseg->segment= b;
905
906                                                 sortseg->z= 0.5f*(z[1] + z[2]);
907
908                                                 sortseg->next= firstseg;
909                                                 firstseg= sortseg;
910                                                 totsegment++;
911                                         }
912
913                                         /* shift clipping and z depth */
914                                         clip[0]= clip[1]; z[0]= z[1];
915                                         clip[1]= clip[2]; z[1]= z[2];
916                                         clip[2]= clip[3]; z[2]= z[3];
917                                 }
918                         }
919                 }
920         }
921
922         if(!re->test_break(re->tbh)) {
923                 /* convert list to array and sort */
924                 sortsegments= MEM_mallocN(sizeof(StrandSortSegment)*totsegment, "StrandSortSegment");
925                 for(a=0, sortseg=firstseg; a<totsegment; a++, sortseg=sortseg->next)
926                         sortsegments[a]= *sortseg;
927                 qsort(sortsegments, totsegment, sizeof(StrandSortSegment), compare_strand_segment);
928         }
929
930         BLI_memarena_free(memarena);
931
932         spart.totapixbuf= MEM_callocN(sizeof(int)*pa->rectx*pa->recty, "totapixbuf");
933
934         if(!re->test_break(re->tbh)) {
935                 /* render segments in sorted order */
936                 sortseg= sortsegments;
937                 for(a=0; a<totsegment; a++, sortseg++) {
938                         if(re->test_break(re->tbh))
939                                 break;
940
941                         obi= &re->objectinstance[sortseg->obi];
942                         obr= obi->obr;
943
944                         sseg.obi= obi;
945                         sseg.strand= RE_findOrAddStrand(obr, sortseg->strand);
946                         sseg.buffer= sseg.strand->buffer;
947                         sseg.sqadaptcos= sseg.buffer->adaptcos;
948                         sseg.sqadaptcos *= sseg.sqadaptcos;
949
950                         svert= sseg.strand->vert + sortseg->segment;
951                         sseg.v[0]= (sortseg->segment > 0)? (svert-1): svert;
952                         sseg.v[1]= svert;
953                         sseg.v[2]= svert+1;
954                         sseg.v[3]= (sortseg->segment < sseg.strand->totvert-2)? svert+2: svert+1;
955                         sseg.shaded= 0;
956
957                         spart.segment= &sseg;
958
959                         render_strand_segment(re, winmat, &spart, &zspan, 1, &sseg);
960                 }
961         }
962
963         if(sortsegments)
964                 MEM_freeN(sortsegments);
965         MEM_freeN(spart.totapixbuf);
966         
967         zbuf_free_span(&zspan);
968
969         return totsegment;
970 }
971
972 /* *************** */
973
974 StrandSurface *cache_strand_surface(Render *re, ObjectRen *obr, DerivedMesh *dm, float mat[][4], int timeoffset)
975 {
976         StrandSurface *mesh;
977         MFace *mface;
978         MVert *mvert;
979         float (*co)[3];
980         int a, totvert, totface;
981
982         totvert= dm->getNumVerts(dm);
983         totface= dm->getNumFaces(dm);
984
985         for(mesh=re->strandsurface.first; mesh; mesh=mesh->next)
986                 if(mesh->obr.ob == obr->ob && mesh->obr.par == obr->par
987                         && mesh->obr.index == obr->index && mesh->totvert==totvert && mesh->totface==totface)
988                         break;
989
990         if(!mesh) {
991                 mesh= MEM_callocN(sizeof(StrandSurface), "StrandSurface");
992                 mesh->obr= *obr;
993                 mesh->totvert= totvert;
994                 mesh->totface= totface;
995                 mesh->face= MEM_callocN(sizeof(int)*4*mesh->totface, "StrandSurfFaces");
996                 mesh->ao= MEM_callocN(sizeof(float)*3*mesh->totvert, "StrandSurfAO");
997                 mesh->env= MEM_callocN(sizeof(float)*3*mesh->totvert, "StrandSurfEnv");
998                 mesh->indirect= MEM_callocN(sizeof(float)*3*mesh->totvert, "StrandSurfIndirect");
999                 BLI_addtail(&re->strandsurface, mesh);
1000         }
1001
1002         if(timeoffset == -1 && !mesh->prevco)
1003                 mesh->prevco= co= MEM_callocN(sizeof(float)*3*mesh->totvert, "StrandSurfCo");
1004         else if(timeoffset == 0 && !mesh->co)
1005                 mesh->co= co= MEM_callocN(sizeof(float)*3*mesh->totvert, "StrandSurfCo");
1006         else if(timeoffset == 1 && !mesh->nextco)
1007                 mesh->nextco= co= MEM_callocN(sizeof(float)*3*mesh->totvert, "StrandSurfCo");
1008         else
1009                 return mesh;
1010
1011         mvert= dm->getVertArray(dm);
1012         for(a=0; a<mesh->totvert; a++, mvert++) {
1013                 VECCOPY(co[a], mvert->co);
1014                 mul_m4_v3(mat, co[a]);
1015         }
1016
1017         mface= dm->getFaceArray(dm);
1018         for(a=0; a<mesh->totface; a++, mface++) {
1019                 mesh->face[a][0]= mface->v1;
1020                 mesh->face[a][1]= mface->v2;
1021                 mesh->face[a][2]= mface->v3;
1022                 mesh->face[a][3]= mface->v4;
1023         }
1024
1025         return mesh;
1026 }
1027
1028 void free_strand_surface(Render *re)
1029 {
1030         StrandSurface *mesh;
1031
1032         for(mesh=re->strandsurface.first; mesh; mesh=mesh->next) {
1033                 if(mesh->co) MEM_freeN(mesh->co);
1034                 if(mesh->prevco) MEM_freeN(mesh->prevco);
1035                 if(mesh->nextco) MEM_freeN(mesh->nextco);
1036                 if(mesh->ao) MEM_freeN(mesh->ao);
1037                 if(mesh->env) MEM_freeN(mesh->env);
1038                 if(mesh->indirect) MEM_freeN(mesh->indirect);
1039                 if(mesh->face) MEM_freeN(mesh->face);
1040         }
1041
1042         BLI_freelistN(&re->strandsurface);
1043 }
1044
1045 void strand_minmax(StrandRen *strand, float *min, float *max, float width)
1046 {
1047         StrandVert *svert;
1048         float vec[3], width2= 2.0f*width;
1049         int a;
1050
1051         for(a=0, svert=strand->vert; a<strand->totvert; a++, svert++) {
1052                 VECCOPY(vec, svert->co);
1053                 DO_MINMAX(vec, min, max);
1054                 
1055                 if(width!=0.0f) {
1056                         vec[0]+= width; vec[1]+= width; vec[2]+= width;
1057                         DO_MINMAX(vec, min, max);
1058                         vec[0]-= width2; vec[1]-= width2; vec[2]-= width2;
1059                         DO_MINMAX(vec, min, max);
1060                 }
1061         }
1062 }
1063