db242b0b1d974f9f09c722a8291b48a8ccc6ab7b
[blender-staging.git] / source / blender / render / intern / source / convertblender.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  * Contributors: 2004/2005/2006 Blender Foundation, full recode
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 #include <math.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <limits.h>
33
34
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_math.h"
39 #include "BLI_blenlib.h"
40 #include "BLI_rand.h"
41 #include "BLI_memarena.h"
42 #include "BLI_ghash.h"
43
44 #include "DNA_armature_types.h"
45 #include "DNA_camera_types.h"
46 #include "DNA_material_types.h"
47 #include "DNA_curve_types.h"
48 #include "DNA_effect_types.h"
49 #include "DNA_group_types.h"
50 #include "DNA_lamp_types.h"
51 #include "DNA_image_types.h"
52 #include "DNA_lattice_types.h"
53 #include "DNA_mesh_types.h"
54 #include "DNA_meshdata_types.h"
55 #include "DNA_meta_types.h"
56 #include "DNA_modifier_types.h"
57 #include "DNA_node_types.h"
58 #include "DNA_object_types.h"
59 #include "DNA_object_force.h"
60 #include "DNA_object_fluidsim.h"
61 #include "DNA_particle_types.h"
62 #include "DNA_scene_types.h"
63 #include "DNA_texture_types.h"
64 #include "DNA_view3d_types.h"
65
66 #include "BKE_anim.h"
67 #include "BKE_armature.h"
68 #include "BKE_action.h"
69 #include "BKE_curve.h"
70 #include "BKE_customdata.h"
71 #include "BKE_colortools.h"
72 #include "BKE_constraint.h"
73 #include "BKE_displist.h"
74 #include "BKE_deform.h"
75 #include "BKE_DerivedMesh.h"
76 #include "BKE_effect.h"
77 #include "BKE_global.h"
78 #include "BKE_group.h"
79 #include "BKE_key.h"
80 #include "BKE_ipo.h"
81 #include "BKE_image.h"
82 #include "BKE_lattice.h"
83 #include "BKE_library.h"
84 #include "BKE_material.h"
85 #include "BKE_main.h"
86 #include "BKE_mball.h"
87 #include "BKE_mesh.h"
88 #include "BKE_modifier.h"
89 #include "BKE_node.h"
90 #include "BKE_object.h"
91 #include "BKE_particle.h"
92 #include "BKE_scene.h"
93 #include "BKE_subsurf.h"
94 #include "BKE_texture.h"
95 #include "BKE_utildefines.h"
96 #include "BKE_world.h"
97
98 #include "PIL_time.h"
99 #include "IMB_imbuf_types.h"
100
101 #include "envmap.h"
102 #include "occlusion.h"
103 #include "pointdensity.h"
104 #include "voxeldata.h"
105 #include "render_types.h"
106 #include "rendercore.h"
107 #include "renderdatabase.h"
108 #include "renderpipeline.h"
109 #include "shadbuf.h"
110 #include "shading.h"
111 #include "strand.h"
112 #include "texture.h"
113 #include "volume_precache.h"
114 #include "sss.h"
115 #include "strand.h"
116 #include "zbuf.h"
117 #include "sunsky.h"
118
119
120 /* 10 times larger than normal epsilon, test it on default nurbs sphere with ray_transp (for quad detection) */
121 /* or for checking vertex normal flips */
122 #define FLT_EPSILON10 1.19209290e-06F
123
124 /* ------------------------------------------------------------------------- */
125
126 /* Stuff for stars. This sits here because it uses gl-things. Part of
127 this code may move down to the converter.  */
128 /* ------------------------------------------------------------------------- */
129 /* this is a bad beast, since it is misused by the 3d view drawing as well. */
130
131 static HaloRen *initstar(Render *re, ObjectRen *obr, float *vec, float hasize)
132 {
133         HaloRen *har;
134         float hoco[4];
135         
136         projectverto(vec, re->winmat, hoco);
137         
138         har= RE_findOrAddHalo(obr, obr->tothalo++);
139         
140         /* projectvert is done in function zbufvlaggen again, because of parts */
141         VECCOPY(har->co, vec);
142         har->hasize= hasize;
143         
144         har->zd= 0.0;
145         
146         return har;
147 }
148
149 /* there must be a 'fixed' amount of stars generated between
150 *         near and far
151 * all stars must by preference lie on the far and solely
152 *        differ in clarity/color
153 */
154
155 void RE_make_stars(Render *re, Scene *scenev3d, void (*initfunc)(void),
156                                    void (*vertexfunc)(float*),  void (*termfunc)(void))
157 {
158         extern unsigned char hash[512];
159         ObjectRen *obr= NULL;
160         World *wrld= NULL;
161         HaloRen *har;
162         Scene *scene;
163         Camera *camera;
164         double dblrand, hlfrand;
165         float vec[4], fx, fy, fz;
166         float fac, starmindist, clipend;
167         float mat[4][4], stargrid, maxrand, maxjit, force, alpha;
168         int x, y, z, sx, sy, sz, ex, ey, ez, done = 0;
169         
170         if(initfunc) {
171                 scene= scenev3d;
172                 wrld= scene->world;
173         }
174         else {
175                 scene= re->scene;
176                 wrld= &(re->wrld);
177         }
178         
179         stargrid = wrld->stardist;                      /* distance between stars */
180         maxrand = 2.0;                                          /* amount a star can be shifted (in grid units) */
181         maxjit = (wrld->starcolnoise);          /* amount a color is being shifted */
182         
183         /* size of stars */
184         force = ( wrld->starsize );
185         
186         /* minimal free space (starting at camera) */
187         starmindist= wrld->starmindist;
188         
189         if (stargrid <= 0.10) return;
190         
191         if (re) re->flag |= R_HALO;
192         else stargrid *= 1.0;                           /* then it draws fewer */
193         
194         if(re) invert_m4_m4(mat, re->viewmat);
195         else unit_m4(mat);
196         
197         /* BOUNDING BOX CALCULATION
198                 * bbox goes from z = loc_near_var | loc_far_var,
199                 * x = -z | +z,
200                 * y = -z | +z
201                 */
202         
203         if(scene->camera==NULL)
204                 return;
205         camera = scene->camera->data;
206         clipend = camera->clipend;
207         
208         /* convert to grid coordinates */
209         
210         sx = ((mat[3][0] - clipend) / stargrid) - maxrand;
211         sy = ((mat[3][1] - clipend) / stargrid) - maxrand;
212         sz = ((mat[3][2] - clipend) / stargrid) - maxrand;
213         
214         ex = ((mat[3][0] + clipend) / stargrid) + maxrand;
215         ey = ((mat[3][1] + clipend) / stargrid) + maxrand;
216         ez = ((mat[3][2] + clipend) / stargrid) + maxrand;
217         
218         dblrand = maxrand * stargrid;
219         hlfrand = 2.0 * dblrand;
220         
221         if (initfunc) {
222                 initfunc();     
223         }
224
225         if(re) /* add render object for stars */
226                 obr= RE_addRenderObject(re, NULL, NULL, 0, 0, 0);
227         
228         for (x = sx, fx = sx * stargrid; x <= ex; x++, fx += stargrid) {
229                 for (y = sy, fy = sy * stargrid; y <= ey ; y++, fy += stargrid) {
230                         for (z = sz, fz = sz * stargrid; z <= ez; z++, fz += stargrid) {
231
232                                 BLI_srand((hash[z & 0xff] << 24) + (hash[y & 0xff] << 16) + (hash[x & 0xff] << 8));
233                                 vec[0] = fx + (hlfrand * BLI_drand()) - dblrand;
234                                 vec[1] = fy + (hlfrand * BLI_drand()) - dblrand;
235                                 vec[2] = fz + (hlfrand * BLI_drand()) - dblrand;
236                                 vec[3] = 1.0;
237                                 
238                                 if (vertexfunc) {
239                                         if(done & 1) vertexfunc(vec);
240                                         done++;
241                                 }
242                                 else {
243                                         mul_m4_v3(re->viewmat, vec);
244                                         
245                                         /* in vec are global coordinates
246                                         * calculate distance to camera
247                                         * and using that, define the alpha
248                                         */
249                                         
250                                         {
251                                                 float tx, ty, tz;
252                                                 
253                                                 tx = vec[0];
254                                                 ty = vec[1];
255                                                 tz = vec[2];
256                                                 
257                                                 alpha = sqrt(tx * tx + ty * ty + tz * tz);
258                                                 
259                                                 if (alpha >= clipend) alpha = 0.0;
260                                                 else if (alpha <= starmindist) alpha = 0.0;
261                                                 else if (alpha <= 2.0 * starmindist) {
262                                                         alpha = (alpha - starmindist) / starmindist;
263                                                 } else {
264                                                         alpha -= 2.0 * starmindist;
265                                                         alpha /= (clipend - 2.0 * starmindist);
266                                                         alpha = 1.0 - alpha;
267                                                 }
268                                         }
269                                         
270                                         
271                                         if (alpha != 0.0) {
272                                                 fac = force * BLI_drand();
273                                                 
274                                                 har = initstar(re, obr, vec, fac);
275                                                 
276                                                 if (har) {
277                                                         har->alfa = sqrt(sqrt(alpha));
278                                                         har->add= 255;
279                                                         har->r = har->g = har->b = 1.0;
280                                                         if (maxjit) {
281                                                                 har->r += ((maxjit * BLI_drand()) ) - maxjit;
282                                                                 har->g += ((maxjit * BLI_drand()) ) - maxjit;
283                                                                 har->b += ((maxjit * BLI_drand()) ) - maxjit;
284                                                         }
285                                                         har->hard = 32;
286                                                         har->lay= -1;
287                                                         har->type |= HA_ONLYSKY;
288                                                         done++;
289                                                 }
290                                         }
291                                 }
292                         }
293                         /* do not call blender_test_break() here, since it is used in UI as well, confusing the callback system */
294                         /* main cause is G.afbreek of course, a global again... (ton) */
295                 }
296         }
297         if (termfunc) termfunc();
298
299         if(obr)
300                 re->tothalo += obr->tothalo;
301 }
302
303
304 /* ------------------------------------------------------------------------- */
305 /* tool functions/defines for ad hoc simplification and possible future 
306    cleanup      */
307 /* ------------------------------------------------------------------------- */
308
309 #define UVTOINDEX(u,v) (startvlak + (u) * sizev + (v))
310 /*
311
312 NOTE THAT U/V COORDINATES ARE SOMETIMES SWAPPED !!
313         
314 ^       ()----p4----p3----()
315 |       |     |     |     |
316 u       |     |  F1 |  F2 |
317         |     |     |     |
318         ()----p1----p2----()
319                    v ->
320 */
321
322 /* ------------------------------------------------------------------------- */
323
324 static void split_v_renderfaces(ObjectRen *obr, int startvlak, int startvert, int usize, int vsize, int uIndex, int cyclu, int cyclv)
325 {
326         int vLen = vsize-1+(!!cyclv);
327         int v;
328
329         for (v=0; v<vLen; v++) {
330                 VlakRen *vlr = RE_findOrAddVlak(obr, startvlak + vLen*uIndex + v);
331                 VertRen *vert = RE_vertren_copy(obr, vlr->v2);
332
333                 if (cyclv) {
334                         vlr->v2 = vert;
335
336                         if (v==vLen-1) {
337                                 VlakRen *vlr = RE_findOrAddVlak(obr, startvlak + vLen*uIndex + 0);
338                                 vlr->v1 = vert;
339                         } else {
340                                 VlakRen *vlr = RE_findOrAddVlak(obr, startvlak + vLen*uIndex + v+1);
341                                 vlr->v1 = vert;
342                         }
343                 } else {
344                         vlr->v2 = vert;
345
346                         if (v<vLen-1) {
347                                 VlakRen *vlr = RE_findOrAddVlak(obr, startvlak + vLen*uIndex + v+1);
348                                 vlr->v1 = vert;
349                         }
350
351                         if (v==0) {
352                                 vlr->v1 = RE_vertren_copy(obr, vlr->v1);
353                         } 
354                 }
355         }
356 }
357
358 /* ------------------------------------------------------------------------- */
359
360 static int check_vnormal(float *n, float *veno)
361 {
362         float inp;
363
364         inp=n[0]*veno[0]+n[1]*veno[1]+n[2]*veno[2];
365         if(inp < -FLT_EPSILON10) return 1;
366         return 0;
367 }
368
369 /* ------------------------------------------------------------------------- */
370 /* Stress, tangents and normals                                              */
371 /* ------------------------------------------------------------------------- */
372
373 static void calc_edge_stress_add(float *accum, VertRen *v1, VertRen *v2)
374 {
375         float len= len_v3v3(v1->co, v2->co)/len_v3v3(v1->orco, v2->orco);
376         float *acc;
377         
378         acc= accum + 2*v1->index;
379         acc[0]+= len;
380         acc[1]+= 1.0f;
381         
382         acc= accum + 2*v2->index;
383         acc[0]+= len;
384         acc[1]+= 1.0f;
385 }
386
387 static void calc_edge_stress(Render *re, ObjectRen *obr, Mesh *me)
388 {
389         float loc[3], size[3], *accum, *acc, *accumoffs, *stress;
390         int a;
391         
392         if(obr->totvert==0) return;
393         
394         mesh_get_texspace(me, loc, NULL, size);
395         
396         accum= MEM_callocN(2*sizeof(float)*obr->totvert, "temp accum for stress");
397         
398         /* de-normalize orco */
399         for(a=0; a<obr->totvert; a++) {
400                 VertRen *ver= RE_findOrAddVert(obr, a);
401                 if(ver->orco) {
402                         ver->orco[0]= ver->orco[0]*size[0] +loc[0];
403                         ver->orco[1]= ver->orco[1]*size[1] +loc[1];
404                         ver->orco[2]= ver->orco[2]*size[2] +loc[2];
405                 }
406         }
407         
408         /* add stress values */
409         accumoffs= accum;       /* so we can use vertex index */
410         for(a=0; a<obr->totvlak; a++) {
411                 VlakRen *vlr= RE_findOrAddVlak(obr, a);
412
413                 if(vlr->v1->orco && vlr->v4) {
414                         calc_edge_stress_add(accumoffs, vlr->v1, vlr->v2);
415                         calc_edge_stress_add(accumoffs, vlr->v2, vlr->v3);
416                         calc_edge_stress_add(accumoffs, vlr->v3, vlr->v1);
417                         if(vlr->v4) {
418                                 calc_edge_stress_add(accumoffs, vlr->v3, vlr->v4);
419                                 calc_edge_stress_add(accumoffs, vlr->v4, vlr->v1);
420                                 calc_edge_stress_add(accumoffs, vlr->v2, vlr->v4);
421                         }
422                 }
423         }
424         
425         for(a=0; a<obr->totvert; a++) {
426                 VertRen *ver= RE_findOrAddVert(obr, a);
427                 if(ver->orco) {
428                         /* find stress value */
429                         acc= accumoffs + 2*ver->index;
430                         if(acc[1]!=0.0f)
431                                 acc[0]/= acc[1];
432                         stress= RE_vertren_get_stress(obr, ver, 1);
433                         *stress= *acc;
434                         
435                         /* restore orcos */
436                         ver->orco[0] = (ver->orco[0]-loc[0])/size[0];
437                         ver->orco[1] = (ver->orco[1]-loc[1])/size[1];
438                         ver->orco[2] = (ver->orco[2]-loc[2])/size[2];
439                 }
440         }
441         
442         MEM_freeN(accum);
443 }
444
445 /* gets tangent from tface or orco */
446 static void calc_tangent_vector(ObjectRen *obr, VertexTangent **vtangents, MemArena *arena, VlakRen *vlr, int do_nmap_tangent, int do_tangent)
447 {
448         MTFace *tface= RE_vlakren_get_tface(obr, vlr, obr->actmtface, NULL, 0);
449         VertRen *v1=vlr->v1, *v2=vlr->v2, *v3=vlr->v3, *v4=vlr->v4;
450         float tang[3], *tav;
451         float *uv1, *uv2, *uv3, *uv4;
452         float uv[4][2];
453         
454         if(tface) {
455                 uv1= tface->uv[0];
456                 uv2= tface->uv[1];
457                 uv3= tface->uv[2];
458                 uv4= tface->uv[3];
459         }
460         else if(v1->orco) {
461                 uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
462                 map_to_sphere( &uv[0][0], &uv[0][1],v1->orco[0], v1->orco[1], v1->orco[2]);
463                 map_to_sphere( &uv[1][0], &uv[1][1],v2->orco[0], v2->orco[1], v2->orco[2]);
464                 map_to_sphere( &uv[2][0], &uv[2][1],v3->orco[0], v3->orco[1], v3->orco[2]);
465                 if(v4)
466                         map_to_sphere( &uv[3][0], &uv[3][1],v4->orco[0], v4->orco[1], v4->orco[2]);
467         }
468         else return;
469
470         tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, vlr->n, tang);
471         
472         if(do_tangent) {
473                 tav= RE_vertren_get_tangent(obr, v1, 1);
474                 VECADD(tav, tav, tang);
475                 tav= RE_vertren_get_tangent(obr, v2, 1);
476                 VECADD(tav, tav, tang);
477                 tav= RE_vertren_get_tangent(obr, v3, 1);
478                 VECADD(tav, tav, tang);
479         }
480         
481         if(do_nmap_tangent) {
482                 sum_or_add_vertex_tangent(arena, &vtangents[v1->index], tang, uv1);
483                 sum_or_add_vertex_tangent(arena, &vtangents[v2->index], tang, uv2);
484                 sum_or_add_vertex_tangent(arena, &vtangents[v3->index], tang, uv3);
485         }
486
487         if(v4) {
488                 tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, vlr->n, tang);
489                 
490                 if(do_tangent) {
491                         tav= RE_vertren_get_tangent(obr, v1, 1);
492                         VECADD(tav, tav, tang);
493                         tav= RE_vertren_get_tangent(obr, v3, 1);
494                         VECADD(tav, tav, tang);
495                         tav= RE_vertren_get_tangent(obr, v4, 1);
496                         VECADD(tav, tav, tang);
497                 }
498
499                 if(do_nmap_tangent) {
500                         sum_or_add_vertex_tangent(arena, &vtangents[v1->index], tang, uv1);
501                         sum_or_add_vertex_tangent(arena, &vtangents[v3->index], tang, uv3);
502                         sum_or_add_vertex_tangent(arena, &vtangents[v4->index], tang, uv4);
503                 }
504         }
505 }
506
507
508 static void calc_vertexnormals(Render *re, ObjectRen *obr, int do_tangent, int do_nmap_tangent)
509 {
510         MemArena *arena= NULL;
511         VertexTangent **vtangents= NULL;
512         int a;
513
514         if(do_nmap_tangent) {
515                 arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
516                 BLI_memarena_use_calloc(arena);
517
518                 vtangents= MEM_callocN(sizeof(VertexTangent*)*obr->totvert, "VertexTangent");
519         }
520
521                 /* clear all vertex normals */
522         for(a=0; a<obr->totvert; a++) {
523                 VertRen *ver= RE_findOrAddVert(obr, a);
524                 ver->n[0]=ver->n[1]=ver->n[2]= 0.0f;
525         }
526
527                 /* calculate cos of angles and point-masses, use as weight factor to
528                    add face normal to vertex */
529         for(a=0; a<obr->totvlak; a++) {
530                 VlakRen *vlr= RE_findOrAddVlak(obr, a);
531                 if(vlr->flag & ME_SMOOTH) {
532                         VertRen *v1= vlr->v1;
533                         VertRen *v2= vlr->v2;
534                         VertRen *v3= vlr->v3;
535                         VertRen *v4= vlr->v4;
536                         float n1[3], n2[3], n3[3], n4[3];
537                         float fac1, fac2, fac3, fac4=0.0f;
538                         
539                         if(re->flag & R_GLOB_NOPUNOFLIP)
540                                 vlr->flag |= R_NOPUNOFLIP;
541                         
542                         sub_v3_v3v3(n1, v2->co, v1->co);
543                         normalize_v3(n1);
544                         sub_v3_v3v3(n2, v3->co, v2->co);
545                         normalize_v3(n2);
546                         if(v4==NULL) {
547                                 sub_v3_v3v3(n3, v1->co, v3->co);
548                                 normalize_v3(n3);
549
550                                 fac1= saacos(-n1[0]*n3[0]-n1[1]*n3[1]-n1[2]*n3[2]);
551                                 fac2= saacos(-n1[0]*n2[0]-n1[1]*n2[1]-n1[2]*n2[2]);
552                                 fac3= saacos(-n2[0]*n3[0]-n2[1]*n3[1]-n2[2]*n3[2]);
553                         }
554                         else {
555                                 sub_v3_v3v3(n3, v4->co, v3->co);
556                                 normalize_v3(n3);
557                                 sub_v3_v3v3(n4, v1->co, v4->co);
558                                 normalize_v3(n4);
559
560                                 fac1= saacos(-n4[0]*n1[0]-n4[1]*n1[1]-n4[2]*n1[2]);
561                                 fac2= saacos(-n1[0]*n2[0]-n1[1]*n2[1]-n1[2]*n2[2]);
562                                 fac3= saacos(-n2[0]*n3[0]-n2[1]*n3[1]-n2[2]*n3[2]);
563                                 fac4= saacos(-n3[0]*n4[0]-n3[1]*n4[1]-n3[2]*n4[2]);
564
565                                 if(!(vlr->flag & R_NOPUNOFLIP)) {
566                                         if( check_vnormal(vlr->n, v4->n) ) fac4= -fac4;
567                                 }
568
569                                 v4->n[0] +=fac4*vlr->n[0];
570                                 v4->n[1] +=fac4*vlr->n[1];
571                                 v4->n[2] +=fac4*vlr->n[2];
572                         }
573
574                         if(!(vlr->flag & R_NOPUNOFLIP)) {
575                                 if( check_vnormal(vlr->n, v1->n) ) fac1= -fac1;
576                                 if( check_vnormal(vlr->n, v2->n) ) fac2= -fac2;
577                                 if( check_vnormal(vlr->n, v3->n) ) fac3= -fac3;
578                         }
579
580                         v1->n[0] +=fac1*vlr->n[0];
581                         v1->n[1] +=fac1*vlr->n[1];
582                         v1->n[2] +=fac1*vlr->n[2];
583
584                         v2->n[0] +=fac2*vlr->n[0];
585                         v2->n[1] +=fac2*vlr->n[1];
586                         v2->n[2] +=fac2*vlr->n[2];
587
588                         v3->n[0] +=fac3*vlr->n[0];
589                         v3->n[1] +=fac3*vlr->n[1];
590                         v3->n[2] +=fac3*vlr->n[2];
591                         
592                 }
593                 if(do_nmap_tangent || do_tangent) {
594                         /* tangents still need to be calculated for flat faces too */
595                         /* weighting removed, they are not vertexnormals */
596                         calc_tangent_vector(obr, vtangents, arena, vlr, do_nmap_tangent, do_tangent);
597                 }
598         }
599
600                 /* do solid faces */
601         for(a=0; a<obr->totvlak; a++) {
602                 VlakRen *vlr= RE_findOrAddVlak(obr, a);
603                 if((vlr->flag & ME_SMOOTH)==0) {
604                         float *f1= vlr->v1->n;
605                         if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
606                         f1= vlr->v2->n;
607                         if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
608                         f1= vlr->v3->n;
609                         if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
610                         if(vlr->v4) {
611                                 f1= vlr->v4->n;
612                                 if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
613                         }
614                 }
615
616                 if(do_nmap_tangent) {
617                         VertRen *v1=vlr->v1, *v2=vlr->v2, *v3=vlr->v3, *v4=vlr->v4;
618                         MTFace *tface= RE_vlakren_get_tface(obr, vlr, obr->actmtface, NULL, 0);
619
620                         if(tface) {
621                                 float *vtang, *ftang= RE_vlakren_get_nmap_tangent(obr, vlr, 1);
622
623                                 vtang= find_vertex_tangent(vtangents[v1->index], tface->uv[0]);
624                                 VECCOPY(ftang, vtang);
625                                 normalize_v3(ftang);
626                                 vtang= find_vertex_tangent(vtangents[v2->index], tface->uv[1]);
627                                 VECCOPY(ftang+3, vtang);
628                                 normalize_v3(ftang+3);
629                                 vtang= find_vertex_tangent(vtangents[v3->index], tface->uv[2]);
630                                 VECCOPY(ftang+6, vtang);
631                                 normalize_v3(ftang+6);
632                                 if(v4) {
633                                         vtang= find_vertex_tangent(vtangents[v4->index], tface->uv[3]);
634                                         VECCOPY(ftang+9, vtang);
635                                         normalize_v3(ftang+9);
636                                 }
637                         }
638                 }
639         }
640         
641                 /* normalize vertex normals */
642         for(a=0; a<obr->totvert; a++) {
643                 VertRen *ver= RE_findOrAddVert(obr, a);
644                 normalize_v3(ver->n);
645                 if(do_tangent) {
646                         float *tav= RE_vertren_get_tangent(obr, ver, 0);
647                         if (tav) {
648                                 /* orthonorm. */
649                                 float tdn = tav[0]*ver->n[0] + tav[1]*ver->n[1] + tav[2]*ver->n[2];
650                                 tav[0] -= ver->n[0]*tdn;
651                                 tav[1] -= ver->n[1]*tdn;
652                                 tav[2] -= ver->n[2]*tdn;
653                                 normalize_v3(tav);
654                         }
655                 }
656         }
657
658
659         if(arena)
660                 BLI_memarena_free(arena);
661         if(vtangents)
662                 MEM_freeN(vtangents);
663 }
664
665 /* ------------------------------------------------------------------------- */
666 /* Autosmoothing:                                                            */
667 /* ------------------------------------------------------------------------- */
668
669 typedef struct ASvert {
670         int totface;
671         ListBase faces;
672 } ASvert;
673
674 typedef struct ASface {
675         struct ASface *next, *prev;
676         VlakRen *vlr[4];
677         VertRen *nver[4];
678 } ASface;
679
680 static void as_addvert(ASvert *asv, VertRen *v1, VlakRen *vlr)
681 {
682         ASface *asf;
683         int a;
684         
685         if(v1 == NULL) return;
686         
687         if(asv->faces.first==NULL) {
688                 asf= MEM_callocN(sizeof(ASface), "asface");
689                 BLI_addtail(&asv->faces, asf);
690         }
691         
692         asf= asv->faces.last;
693         for(a=0; a<4; a++) {
694                 if(asf->vlr[a]==NULL) {
695                         asf->vlr[a]= vlr;
696                         asv->totface++;
697                         break;
698                 }
699         }
700         
701         /* new face struct */
702         if(a==4) {
703                 asf= MEM_callocN(sizeof(ASface), "asface");
704                 BLI_addtail(&asv->faces, asf);
705                 asf->vlr[0]= vlr;
706                 asv->totface++;
707         }
708 }
709
710 static int as_testvertex(VlakRen *vlr, VertRen *ver, ASvert *asv, float thresh) 
711 {
712         /* return 1: vertex needs a copy */
713         ASface *asf;
714         float inp;
715         int a;
716         
717         if(vlr==0) return 0;
718         
719         asf= asv->faces.first;
720         while(asf) {
721                 for(a=0; a<4; a++) {
722                         if(asf->vlr[a] && asf->vlr[a]!=vlr) {
723                                 inp= fabs( vlr->n[0]*asf->vlr[a]->n[0] + vlr->n[1]*asf->vlr[a]->n[1] + vlr->n[2]*asf->vlr[a]->n[2] );
724                                 if(inp < thresh) return 1;
725                         }
726                 }
727                 asf= asf->next;
728         }
729         
730         return 0;
731 }
732
733 static VertRen *as_findvertex(VlakRen *vlr, VertRen *ver, ASvert *asv, float thresh) 
734 {
735         /* return when new vertex already was made */
736         ASface *asf;
737         float inp;
738         int a;
739         
740         asf= asv->faces.first;
741         while(asf) {
742                 for(a=0; a<4; a++) {
743                         if(asf->vlr[a] && asf->vlr[a]!=vlr) {
744                                 /* this face already made a copy for this vertex! */
745                                 if(asf->nver[a]) {
746                                         inp= fabs( vlr->n[0]*asf->vlr[a]->n[0] + vlr->n[1]*asf->vlr[a]->n[1] + vlr->n[2]*asf->vlr[a]->n[2] );
747                                         if(inp >= thresh) {
748                                                 return asf->nver[a];
749                                         }
750                                 }
751                         }
752                 }
753                 asf= asf->next;
754         }
755         
756         return NULL;
757 }
758
759 /* note; autosmooth happens in object space still, after applying autosmooth we rotate */
760 /* note2; actually, when original mesh and displist are equal sized, face normals are from original mesh */
761 static void autosmooth(Render *re, ObjectRen *obr, float mat[][4], int degr)
762 {
763         ASvert *asv, *asverts;
764         ASface *asf;
765         VertRen *ver, *v1;
766         VlakRen *vlr;
767         float thresh;
768         int a, b, totvert;
769         
770         if(obr->totvert==0) return;
771         asverts= MEM_callocN(sizeof(ASvert)*obr->totvert, "all smooth verts");
772         
773         thresh= cos( M_PI*(0.5f+(float)degr)/180.0 );
774         
775         /* step zero: give faces normals of original mesh, if this is provided */
776         
777         
778         /* step one: construct listbase of all vertices and pointers to faces */
779         for(a=0; a<obr->totvlak; a++) {
780                 vlr= RE_findOrAddVlak(obr, a);
781                 /* skip wire faces */
782                 if(vlr->v2 != vlr->v3) {
783                         as_addvert(asverts+vlr->v1->index, vlr->v1, vlr);
784                         as_addvert(asverts+vlr->v2->index, vlr->v2, vlr);
785                         as_addvert(asverts+vlr->v3->index, vlr->v3, vlr);
786                         if(vlr->v4) 
787                                 as_addvert(asverts+vlr->v4->index, vlr->v4, vlr);
788                 }
789         }
790         
791         totvert= obr->totvert;
792         /* we now test all vertices, when faces have a normal too much different: they get a new vertex */
793         for(a=0, asv=asverts; a<totvert; a++, asv++) {
794                 if(asv && asv->totface>1) {
795                         ver= RE_findOrAddVert(obr, a);
796
797                         asf= asv->faces.first;
798                         while(asf) {
799                                 for(b=0; b<4; b++) {
800                                 
801                                         /* is there a reason to make a new vertex? */
802                                         vlr= asf->vlr[b];
803                                         if( as_testvertex(vlr, ver, asv, thresh) ) {
804                                                 
805                                                 /* already made a new vertex within threshold? */
806                                                 v1= as_findvertex(vlr, ver, asv, thresh);
807                                                 if(v1==NULL) {
808                                                         /* make a new vertex */
809                                                         v1= RE_vertren_copy(obr, ver);
810                                                 }
811                                                 asf->nver[b]= v1;
812                                                 if(vlr->v1==ver) vlr->v1= v1;
813                                                 if(vlr->v2==ver) vlr->v2= v1;
814                                                 if(vlr->v3==ver) vlr->v3= v1;
815                                                 if(vlr->v4==ver) vlr->v4= v1;
816                                         }
817                                 }
818                                 asf= asf->next;
819                         }
820                 }
821         }
822         
823         /* free */
824         for(a=0; a<totvert; a++) {
825                 BLI_freelistN(&asverts[a].faces);
826         }
827         MEM_freeN(asverts);
828         
829         /* rotate vertices and calculate normal of faces */
830         for(a=0; a<obr->totvert; a++) {
831                 ver= RE_findOrAddVert(obr, a);
832                 mul_m4_v3(mat, ver->co);
833         }
834         for(a=0; a<obr->totvlak; a++) {
835                 vlr= RE_findOrAddVlak(obr, a);
836                 
837                 /* skip wire faces */
838                 if(vlr->v2 != vlr->v3) {
839                         if(vlr->v4) 
840                                 normal_quad_v3( vlr->n,vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co);
841                         else 
842                                 normal_tri_v3( vlr->n,vlr->v3->co, vlr->v2->co, vlr->v1->co);
843                 }
844         }               
845 }
846
847 /* ------------------------------------------------------------------------- */
848 /* Orco hash and Materials                                                   */
849 /* ------------------------------------------------------------------------- */
850
851 static float *get_object_orco(Render *re, Object *ob)
852 {
853         float *orco;
854         
855         if (!re->orco_hash)
856                 re->orco_hash = BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
857         
858         orco = BLI_ghash_lookup(re->orco_hash, ob);
859         
860         if (!orco) {
861                 if (ELEM(ob->type, OB_CURVE, OB_FONT)) {
862                         orco = make_orco_curve(re->scene, ob);
863                 } else if (ob->type==OB_SURF) {
864                         orco = make_orco_surf(ob);
865                 } else if (ob->type==OB_MBALL) {
866                         orco = make_orco_mball(ob);
867                 }
868                 
869                 if (orco)
870                         BLI_ghash_insert(re->orco_hash, ob, orco);
871         }
872         
873         return orco;
874 }
875
876 static void set_object_orco(Render *re, void *ob, float *orco)
877 {
878         if (!re->orco_hash)
879                 re->orco_hash = BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
880         
881         BLI_ghash_insert(re->orco_hash, ob, orco);
882 }
883
884 static void free_mesh_orco_hash(Render *re) 
885 {
886         if (re->orco_hash) {
887                 BLI_ghash_free(re->orco_hash, NULL, (GHashValFreeFP)MEM_freeN);
888                 re->orco_hash = NULL;
889         }
890 }
891
892 static void check_material_mapto(Material *ma)
893 {
894         int a;
895         ma->mapto_textured = 0;
896         
897         /* cache which inputs are actually textured.
898          * this can avoid a bit of time spent iterating through all the texture slots, map inputs and map tos
899          * every time a property which may or may not be textured is accessed */
900         
901         for(a=0; a<MAX_MTEX; a++) {
902                 if(ma->mtex[a] && ma->mtex[a]->tex) {
903                         /* currently used only in volume render, so we'll check for those flags */
904                         if(ma->mtex[a]->mapto & MAP_DENSITY) ma->mapto_textured |= MAP_DENSITY;
905                         if(ma->mtex[a]->mapto & MAP_EMISSION) ma->mapto_textured |= MAP_EMISSION;
906                         if(ma->mtex[a]->mapto & MAP_EMISSION_COL) ma->mapto_textured |= MAP_EMISSION_COL;
907                         if(ma->mtex[a]->mapto & MAP_SCATTERING) ma->mapto_textured |= MAP_SCATTERING;
908                         if(ma->mtex[a]->mapto & MAP_TRANSMISSION_COL) ma->mapto_textured |= MAP_TRANSMISSION_COL;
909                         if(ma->mtex[a]->mapto & MAP_REFLECTION) ma->mapto_textured |= MAP_REFLECTION;
910                         if(ma->mtex[a]->mapto & MAP_REFLECTION_COL) ma->mapto_textured |= MAP_REFLECTION_COL;
911                 }
912         }
913 }
914 static void flag_render_node_material(Render *re, bNodeTree *ntree)
915 {
916         bNode *node;
917
918         for(node=ntree->nodes.first; node; node= node->next) {
919                 if(node->id) {
920                         if(GS(node->id->name)==ID_MA) {
921                                 Material *ma= (Material *)node->id;
922
923                                 if((ma->mode & MA_TRANSP) && (ma->mode & MA_ZTRANSP))
924                                         re->flag |= R_ZTRA;
925
926                                 ma->flag |= MA_IS_USED;
927                         }
928                         else if(node->type==NODE_GROUP)
929                                 flag_render_node_material(re, (bNodeTree *)node->id);
930                 }
931         }
932 }
933
934 static Material *give_render_material(Render *re, Object *ob, int nr)
935 {
936         extern Material defmaterial;    /* material.c */
937         Material *ma;
938         
939         ma= give_current_material(ob, nr);
940         if(ma==NULL) 
941                 ma= &defmaterial;
942         
943         if(re->r.mode & R_SPEED) ma->texco |= NEED_UV;
944         
945         if(ma->material_type == MA_TYPE_VOLUME) {
946                 ma->mode |= MA_TRANSP;
947                 ma->mode &= ~MA_SHADBUF;
948         }
949         if((ma->mode & MA_TRANSP) && (ma->mode & MA_ZTRANSP))
950                 re->flag |= R_ZTRA;
951         
952         /* for light groups */
953         ma->flag |= MA_IS_USED;
954
955         if(ma->nodetree && ma->use_nodes)
956                 flag_render_node_material(re, ma->nodetree);
957         
958         check_material_mapto(ma);
959         
960         return ma;
961 }
962
963 /* ------------------------------------------------------------------------- */
964 /* Particles                                                                 */
965 /* ------------------------------------------------------------------------- */
966 typedef struct ParticleStrandData
967 {
968         struct MCol *mcol;
969         float *orco, *uvco, *surfnor;
970         float time, adapt_angle, adapt_pix, size;
971         int totuv, totcol;
972         int first, line, adapt, override_uv;
973 }
974 ParticleStrandData;
975 /* future thread problem... */
976 static void static_particle_strand(Render *re, ObjectRen *obr, Material *ma, ParticleStrandData *sd, float *vec, float *vec1)
977 {
978         static VertRen *v1= NULL, *v2= NULL;
979         VlakRen *vlr= NULL;
980         float nor[3], cross[3], crosslen, w, dx, dy, width;
981         static float anor[3], avec[3];
982         int flag, i;
983         static int second=0;
984         
985         sub_v3_v3v3(nor, vec, vec1);
986         normalize_v3(nor);              // nor needed as tangent 
987         cross_v3_v3v3(cross, vec, nor);
988
989         /* turn cross in pixelsize */
990         w= vec[2]*re->winmat[2][3] + re->winmat[3][3];
991         dx= re->winx*cross[0]*re->winmat[0][0];
992         dy= re->winy*cross[1]*re->winmat[1][1];
993         w= sqrt(dx*dx + dy*dy)/w;
994         
995         if(w!=0.0f) {
996                 float fac;
997                 if(ma->strand_ease!=0.0f) {
998                         if(ma->strand_ease<0.0f)
999                                 fac= pow(sd->time, 1.0+ma->strand_ease);
1000                         else
1001                                 fac= pow(sd->time, 1.0/(1.0f-ma->strand_ease));
1002                 }
1003                 else fac= sd->time;
1004
1005                 width= ((1.0f-fac)*ma->strand_sta + (fac)*ma->strand_end);
1006
1007                 /* use actual Blender units for strand width and fall back to minimum width */
1008                 if(ma->mode & MA_STR_B_UNITS){
1009                         crosslen= len_v3(cross);
1010                         w= 2.0f*crosslen*ma->strand_min/w;
1011
1012                         if(width < w)
1013                                 width= w;
1014
1015                         /*cross is the radius of the strand so we want it to be half of full width */
1016                         mul_v3_fl(cross,0.5/crosslen);
1017                 }
1018                 else
1019                         width/=w;
1020
1021                 mul_v3_fl(cross, width);
1022         }
1023         else width= 1.0f;
1024         
1025         if(ma->mode & MA_TANGENT_STR)
1026                 flag= R_SMOOTH|R_NOPUNOFLIP|R_TANGENT;
1027         else
1028                 flag= R_SMOOTH;
1029         
1030         /* only 1 pixel wide strands filled in as quads now, otherwise zbuf errors */
1031         if(ma->strand_sta==1.0f)
1032                 flag |= R_STRAND;
1033         
1034         /* single face line */
1035         if(sd->line) {
1036                 vlr= RE_findOrAddVlak(obr, obr->totvlak++);
1037                 vlr->flag= flag;
1038                 vlr->v1= RE_findOrAddVert(obr, obr->totvert++);
1039                 vlr->v2= RE_findOrAddVert(obr, obr->totvert++);
1040                 vlr->v3= RE_findOrAddVert(obr, obr->totvert++);
1041                 vlr->v4= RE_findOrAddVert(obr, obr->totvert++);
1042                 
1043                 VECCOPY(vlr->v1->co, vec);
1044                 add_v3_v3v3(vlr->v1->co, vlr->v1->co, cross);
1045                 VECCOPY(vlr->v1->n, nor);
1046                 vlr->v1->orco= sd->orco;
1047                 vlr->v1->accum= -1.0f;  // accum abuse for strand texco
1048                 
1049                 VECCOPY(vlr->v2->co, vec);
1050                 sub_v3_v3v3(vlr->v2->co, vlr->v2->co, cross);
1051                 VECCOPY(vlr->v2->n, nor);
1052                 vlr->v2->orco= sd->orco;
1053                 vlr->v2->accum= vlr->v1->accum;
1054
1055                 VECCOPY(vlr->v4->co, vec1);
1056                 add_v3_v3v3(vlr->v4->co, vlr->v4->co, cross);
1057                 VECCOPY(vlr->v4->n, nor);
1058                 vlr->v4->orco= sd->orco;
1059                 vlr->v4->accum= 1.0f;   // accum abuse for strand texco
1060                 
1061                 VECCOPY(vlr->v3->co, vec1);
1062                 sub_v3_v3v3(vlr->v3->co, vlr->v3->co, cross);
1063                 VECCOPY(vlr->v3->n, nor);
1064                 vlr->v3->orco= sd->orco;
1065                 vlr->v3->accum= vlr->v4->accum;
1066
1067                 normal_quad_v3( vlr->n,vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co);
1068                 
1069                 vlr->mat= ma;
1070                 vlr->ec= ME_V2V3;
1071
1072                 if(sd->surfnor) {
1073                         float *snor= RE_vlakren_get_surfnor(obr, vlr, 1);
1074                         VECCOPY(snor, sd->surfnor);
1075                 }
1076
1077                 if(sd->uvco){
1078                         for(i=0; i<sd->totuv; i++){
1079                                 MTFace *mtf;
1080                                 mtf=RE_vlakren_get_tface(obr,vlr,i,NULL,1);
1081                                 mtf->uv[0][0]=mtf->uv[1][0]=
1082                                 mtf->uv[2][0]=mtf->uv[3][0]=(sd->uvco+2*i)[0];
1083                                 mtf->uv[0][1]=mtf->uv[1][1]=
1084                                 mtf->uv[2][1]=mtf->uv[3][1]=(sd->uvco+2*i)[1];
1085                         }
1086                         if(sd->override_uv>=0){
1087                                 MTFace *mtf;
1088                                 mtf=RE_vlakren_get_tface(obr,vlr,sd->override_uv,NULL,0);
1089                                 
1090                                 mtf->uv[0][0]=mtf->uv[3][0]=0.0f;
1091                                 mtf->uv[1][0]=mtf->uv[2][0]=1.0f;
1092
1093                                 mtf->uv[0][1]=mtf->uv[1][1]=0.0f;
1094                                 mtf->uv[2][1]=mtf->uv[3][1]=1.0f;
1095                         }
1096                 }
1097                 if(sd->mcol){
1098                         for(i=0; i<sd->totcol; i++){
1099                                 MCol *mc;
1100                                 mc=RE_vlakren_get_mcol(obr,vlr,i,NULL,1);
1101                                 mc[0]=mc[1]=mc[2]=mc[3]=sd->mcol[i];
1102                                 mc[0]=mc[1]=mc[2]=mc[3]=sd->mcol[i];
1103                         }
1104                 }
1105         }
1106         /* first two vertices of a strand */
1107         else if(sd->first) {
1108                 if(sd->adapt){
1109                         VECCOPY(anor, nor);
1110                         VECCOPY(avec, vec);
1111                         second=1;
1112                 }
1113
1114                 v1= RE_findOrAddVert(obr, obr->totvert++);
1115                 v2= RE_findOrAddVert(obr, obr->totvert++);
1116                 
1117                 VECCOPY(v1->co, vec);
1118                 add_v3_v3v3(v1->co, v1->co, cross);
1119                 VECCOPY(v1->n, nor);
1120                 v1->orco= sd->orco;
1121                 v1->accum= -1.0f;       // accum abuse for strand texco
1122                 
1123                 VECCOPY(v2->co, vec);
1124                 sub_v3_v3v3(v2->co, v2->co, cross);
1125                 VECCOPY(v2->n, nor);
1126                 v2->orco= sd->orco;
1127                 v2->accum= v1->accum;
1128         }
1129         /* more vertices & faces to strand */
1130         else {
1131                 if(sd->adapt==0 || second){
1132                         vlr= RE_findOrAddVlak(obr, obr->totvlak++);
1133                         vlr->flag= flag;
1134                         vlr->v1= v1;
1135                         vlr->v2= v2;
1136                         vlr->v3= RE_findOrAddVert(obr, obr->totvert++);
1137                         vlr->v4= RE_findOrAddVert(obr, obr->totvert++);
1138                         
1139                         v1= vlr->v4; // cycle
1140                         v2= vlr->v3; // cycle
1141
1142                         
1143                         if(sd->adapt){
1144                                 second=0;
1145                                 VECCOPY(anor,nor);
1146                                 VECCOPY(avec,vec);
1147                         }
1148
1149                 }
1150                 else if(sd->adapt){
1151                         float dvec[3],pvec[3];
1152                         sub_v3_v3v3(dvec,avec,vec);
1153                         project_v3_v3v3(pvec,dvec,vec);
1154                         sub_v3_v3v3(dvec,dvec,pvec);
1155
1156                         w= vec[2]*re->winmat[2][3] + re->winmat[3][3];
1157                         dx= re->winx*dvec[0]*re->winmat[0][0]/w;
1158                         dy= re->winy*dvec[1]*re->winmat[1][1]/w;
1159                         w= sqrt(dx*dx + dy*dy);
1160                         if(dot_v3v3(anor,nor)<sd->adapt_angle && w>sd->adapt_pix){
1161                                 vlr= RE_findOrAddVlak(obr, obr->totvlak++);
1162                                 vlr->flag= flag;
1163                                 vlr->v1= v1;
1164                                 vlr->v2= v2;
1165                                 vlr->v3= RE_findOrAddVert(obr, obr->totvert++);
1166                                 vlr->v4= RE_findOrAddVert(obr, obr->totvert++);
1167                                 
1168                                 v1= vlr->v4; // cycle
1169                                 v2= vlr->v3; // cycle
1170
1171                                 VECCOPY(anor,nor);
1172                                 VECCOPY(avec,vec);
1173                         }
1174                         else{
1175                                 vlr= RE_findOrAddVlak(obr, obr->totvlak-1);
1176                         }
1177                 }
1178         
1179                 VECCOPY(vlr->v4->co, vec);
1180                 add_v3_v3v3(vlr->v4->co, vlr->v4->co, cross);
1181                 VECCOPY(vlr->v4->n, nor);
1182                 vlr->v4->orco= sd->orco;
1183                 vlr->v4->accum= -1.0f + 2.0f*sd->time;  // accum abuse for strand texco
1184                 
1185                 VECCOPY(vlr->v3->co, vec);
1186                 sub_v3_v3v3(vlr->v3->co, vlr->v3->co, cross);
1187                 VECCOPY(vlr->v3->n, nor);
1188                 vlr->v3->orco= sd->orco;
1189                 vlr->v3->accum= vlr->v4->accum;
1190                 
1191                 normal_quad_v3( vlr->n,vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co);
1192                 
1193                 vlr->mat= ma;
1194                 vlr->ec= ME_V2V3;
1195
1196                 if(sd->surfnor) {
1197                         float *snor= RE_vlakren_get_surfnor(obr, vlr, 1);
1198                         VECCOPY(snor, sd->surfnor);
1199                 }
1200
1201                 if(sd->uvco){
1202                         for(i=0; i<sd->totuv; i++){
1203                                 MTFace *mtf;
1204                                 mtf=RE_vlakren_get_tface(obr,vlr,i,NULL,1);
1205                                 mtf->uv[0][0]=mtf->uv[1][0]=
1206                                 mtf->uv[2][0]=mtf->uv[3][0]=(sd->uvco+2*i)[0];
1207                                 mtf->uv[0][1]=mtf->uv[1][1]=
1208                                 mtf->uv[2][1]=mtf->uv[3][1]=(sd->uvco+2*i)[1];
1209                         }
1210                         if(sd->override_uv>=0){
1211                                 MTFace *mtf;
1212                                 mtf=RE_vlakren_get_tface(obr,vlr,sd->override_uv,NULL,0);
1213                                 
1214                                 mtf->uv[0][0]=mtf->uv[3][0]=0.0f;
1215                                 mtf->uv[1][0]=mtf->uv[2][0]=1.0f;
1216
1217                                 mtf->uv[0][1]=mtf->uv[1][1]=(vlr->v1->accum+1.0f)/2.0f;
1218                                 mtf->uv[2][1]=mtf->uv[3][1]=(vlr->v3->accum+1.0f)/2.0f;
1219                         }
1220                 }
1221                 if(sd->mcol){
1222                         for(i=0; i<sd->totcol; i++){
1223                                 MCol *mc;
1224                                 mc=RE_vlakren_get_mcol(obr,vlr,i,NULL,1);
1225                                 mc[0]=mc[1]=mc[2]=mc[3]=sd->mcol[i];
1226                                 mc[0]=mc[1]=mc[2]=mc[3]=sd->mcol[i];
1227                         }
1228                 }
1229         }
1230 }
1231
1232 static void static_particle_wire(ObjectRen *obr, Material *ma, float *vec, float *vec1, int first, int line)
1233 {
1234         VlakRen *vlr;
1235         static VertRen *v1;
1236
1237         if(line) {
1238                 vlr= RE_findOrAddVlak(obr, obr->totvlak++);
1239                 vlr->v1= RE_findOrAddVert(obr, obr->totvert++);
1240                 vlr->v2= RE_findOrAddVert(obr, obr->totvert++);
1241                 vlr->v3= vlr->v2;
1242                 vlr->v4= NULL;
1243                 
1244                 VECCOPY(vlr->v1->co, vec);
1245                 VECCOPY(vlr->v2->co, vec1);
1246                 
1247                 sub_v3_v3v3(vlr->n, vec, vec1);
1248                 normalize_v3(vlr->n);
1249                 VECCOPY(vlr->v1->n, vlr->n);
1250                 VECCOPY(vlr->v2->n, vlr->n);
1251                 
1252                 vlr->mat= ma;
1253                 vlr->ec= ME_V1V2;
1254
1255         }
1256         else if(first) {
1257                 v1= RE_findOrAddVert(obr, obr->totvert++);
1258                 VECCOPY(v1->co, vec);
1259         }
1260         else {
1261                 vlr= RE_findOrAddVlak(obr, obr->totvlak++);
1262                 vlr->v1= v1;
1263                 vlr->v2= RE_findOrAddVert(obr, obr->totvert++);
1264                 vlr->v3= vlr->v2;
1265                 vlr->v4= NULL;
1266                 
1267                 v1= vlr->v2; // cycle
1268                 VECCOPY(v1->co, vec);
1269                 
1270                 sub_v3_v3v3(vlr->n, vec, vec1);
1271                 normalize_v3(vlr->n);
1272                 VECCOPY(v1->n, vlr->n);
1273                 
1274                 vlr->mat= ma;
1275                 vlr->ec= ME_V1V2;
1276         }
1277
1278 }
1279
1280 static void particle_curve(Render *re, ObjectRen *obr, DerivedMesh *dm, Material *ma, ParticleStrandData *sd, float *loc, float *loc1,  int seed)
1281 {
1282         HaloRen *har=0;
1283
1284         if(ma->material_type == MA_TYPE_WIRE)
1285                 static_particle_wire(obr, ma, loc, loc1, sd->first, sd->line);
1286         else if(ma->material_type == MA_TYPE_HALO) {
1287                 har= RE_inithalo_particle(re, obr, dm, ma, loc, loc1, sd->orco, sd->uvco, sd->size, 1.0, seed);
1288                 if(har) har->lay= obr->ob->lay;
1289         }
1290         else
1291                 static_particle_strand(re, obr, ma, sd, loc, loc1);
1292 }
1293 static void particle_billboard(Render *re, ObjectRen *obr, Material *ma, ParticleBillboardData *bb)
1294 {
1295         VlakRen *vlr;
1296         MTFace *mtf;
1297         float xvec[3], yvec[3], zvec[3], bb_center[3];
1298         float uvx = 0.0f, uvy = 0.0f, uvdx = 1.0f, uvdy = 1.0f, time = 0.0f;
1299
1300         vlr= RE_findOrAddVlak(obr, obr->totvlak++);
1301         vlr->v1= RE_findOrAddVert(obr, obr->totvert++);
1302         vlr->v2= RE_findOrAddVert(obr, obr->totvert++);
1303         vlr->v3= RE_findOrAddVert(obr, obr->totvert++);
1304         vlr->v4= RE_findOrAddVert(obr, obr->totvert++);
1305
1306         psys_make_billboard(bb, xvec, yvec, zvec, bb_center);
1307
1308         VECADD(vlr->v1->co, bb_center, xvec);
1309         VECADD(vlr->v1->co, vlr->v1->co, yvec);
1310         mul_m4_v3(re->viewmat, vlr->v1->co);
1311
1312         VECSUB(vlr->v2->co, bb_center, xvec);
1313         VECADD(vlr->v2->co, vlr->v2->co, yvec);
1314         mul_m4_v3(re->viewmat, vlr->v2->co);
1315
1316         VECSUB(vlr->v3->co, bb_center, xvec);
1317         VECSUB(vlr->v3->co, vlr->v3->co, yvec);
1318         mul_m4_v3(re->viewmat, vlr->v3->co);
1319
1320         VECADD(vlr->v4->co, bb_center, xvec);
1321         VECSUB(vlr->v4->co, vlr->v4->co, yvec);
1322         mul_m4_v3(re->viewmat, vlr->v4->co);
1323
1324         normal_quad_v3( vlr->n,vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co);
1325         VECCOPY(vlr->v1->n,vlr->n);
1326         VECCOPY(vlr->v2->n,vlr->n);
1327         VECCOPY(vlr->v3->n,vlr->n);
1328         VECCOPY(vlr->v4->n,vlr->n);
1329         
1330         vlr->mat= ma;
1331         vlr->ec= ME_V2V3;
1332
1333         if(bb->uv_split > 1){
1334                 uvdx = uvdy = 1.0f / (float)bb->uv_split;
1335                 if(bb->anim == PART_BB_ANIM_TIME) {
1336                         if(bb->split_offset == PART_BB_OFF_NONE)
1337                                 time = bb->time;
1338                         else if(bb->split_offset == PART_BB_OFF_LINEAR)
1339                                 time = (float)fmod(bb->time + (float)bb->num / (float)(bb->uv_split * bb->uv_split), 1.0f);
1340                         else /* split_offset==PART_BB_OFF_RANDOM */
1341                                 time = (float)fmod(bb->time + bb->random, 1.0f);
1342
1343                 }
1344                 else if(bb->anim == PART_BB_ANIM_ANGLE) {
1345                         if(bb->align == PART_BB_VIEW) {
1346                                 time = (float)fmod((bb->tilt + 1.0f) / 2.0f, 1.0);
1347                         }
1348                         else{
1349                                 float axis1[3] = {0.0f,0.0f,0.0f};
1350                                 float axis2[3] = {0.0f,0.0f,0.0f};
1351                                 axis1[(bb->align + 1) % 3] = 1.0f;
1352                                 axis2[(bb->align + 2) % 3] = 1.0f;
1353                                 if(bb->lock == 0) {
1354                                         zvec[bb->align] = 0.0f;
1355                                         normalize_v3(zvec);
1356                                 }
1357                                 time = saacos(dot_v3v3(zvec, axis1)) / (float)M_PI;
1358                                 if(dot_v3v3(zvec, axis2) < 0.0f)
1359                                         time = 1.0f - time / 2.0f;
1360                                 else
1361                                         time = time / 2.0f;
1362                         }
1363                         if(bb->split_offset == PART_BB_OFF_LINEAR)
1364                                 time = (float)fmod(bb->time + (float)bb->num / (float)(bb->uv_split * bb->uv_split), 1.0f);
1365                         else if(bb->split_offset == PART_BB_OFF_RANDOM)
1366                                 time = (float)fmod(bb->time + bb->random, 1.0f);
1367                 }
1368                 else{
1369                         if(bb->split_offset == PART_BB_OFF_NONE)
1370                                 time = 0.0f;
1371                         else if(bb->split_offset == PART_BB_OFF_LINEAR)
1372                                 time = (float)fmod((float)bb->num /(float)(bb->uv_split * bb->uv_split) , 1.0f);
1373                         else /* split_offset==PART_BB_OFF_RANDOM */
1374                                 time = bb->random;
1375                 }
1376                 uvx = uvdx * floor((float)(bb->uv_split * bb->uv_split) * (float)fmod((double)time, (double)uvdx));
1377                 uvy = uvdy * floor((1.0f - time) * (float)bb->uv_split);
1378                 if(fmod(time, 1.0f / bb->uv_split) == 0.0f)
1379                         uvy -= uvdy;
1380         }
1381
1382         /* normal UVs */
1383         if(bb->uv[0] >= 0){
1384                 mtf = RE_vlakren_get_tface(obr, vlr, bb->uv[0], NULL, 1);
1385                 mtf->uv[0][0] = 1.0f;
1386                 mtf->uv[0][1] = 1.0f;
1387                 mtf->uv[1][0] = 0.0f;
1388                 mtf->uv[1][1] = 1.0f;
1389                 mtf->uv[2][0] = 0.0f;
1390                 mtf->uv[2][1] = 0.0f;
1391                 mtf->uv[3][0] = 1.0f;
1392                 mtf->uv[3][1] = 0.0f;
1393         }
1394
1395         /* time-index UVs */
1396         if(bb->uv[1] >= 0){
1397                 mtf = RE_vlakren_get_tface(obr, vlr, bb->uv[1], NULL, 1);
1398                 mtf->uv[0][0] = mtf->uv[1][0] = mtf->uv[2][0] = mtf->uv[3][0] = bb->time;
1399                 mtf->uv[0][1] = mtf->uv[1][1] = mtf->uv[2][1] = mtf->uv[3][1] = (float)bb->num/(float)bb->totnum;
1400         }
1401
1402         /* split UVs */
1403         if(bb->uv_split > 1 && bb->uv[2] >= 0){
1404                 mtf = RE_vlakren_get_tface(obr, vlr, bb->uv[2], NULL, 1);
1405                 mtf->uv[0][0] = uvx + uvdx;
1406                 mtf->uv[0][1] = uvy + uvdy;
1407                 mtf->uv[1][0] = uvx;
1408                 mtf->uv[1][1] = uvy + uvdy;
1409                 mtf->uv[2][0] = uvx;
1410                 mtf->uv[2][1] = uvy;
1411                 mtf->uv[3][0] = uvx + uvdx;
1412                 mtf->uv[3][1] = uvy;
1413         }
1414 }
1415 static void particle_normal_ren(short ren_as, ParticleSettings *part, Render *re, ObjectRen *obr, DerivedMesh *dm, Material *ma, ParticleStrandData *sd, ParticleBillboardData *bb, ParticleKey *state, int seed, float hasize)
1416 {
1417         float loc[3], loc0[3], loc1[3], vel[3];
1418         
1419         VECCOPY(loc, state->co);
1420
1421         if(ren_as != PART_DRAW_BB)
1422                 mul_m4_v3(re->viewmat, loc);
1423
1424         switch(ren_as) {
1425                 case PART_DRAW_LINE:
1426                         sd->line = 1;
1427                         sd->time = 0.0f;
1428                         sd->size = hasize;
1429
1430                         VECCOPY(vel, state->vel);
1431                         mul_mat3_m4_v3(re->viewmat, vel);
1432                         normalize_v3(vel);
1433
1434                         if(part->draw & PART_DRAW_VEL_LENGTH)
1435                                 mul_v3_fl(vel, len_v3(state->vel));
1436
1437                         VECADDFAC(loc0, loc, vel, -part->draw_line[0]);
1438                         VECADDFAC(loc1, loc, vel, part->draw_line[1]);
1439
1440                         particle_curve(re, obr, dm, ma, sd, loc0, loc1, seed);
1441
1442                         break;
1443
1444                 case PART_DRAW_BB:
1445
1446                         VECCOPY(bb->vec, loc);
1447                         VECCOPY(bb->vel, state->vel);
1448
1449                         particle_billboard(re, obr, ma, bb);
1450
1451                         break;
1452
1453                 default:
1454                 {
1455                         HaloRen *har=0;
1456
1457                         har = RE_inithalo_particle(re, obr, dm, ma, loc, NULL, sd->orco, sd->uvco, hasize, 0.0, seed);
1458                         
1459                         if(har) har->lay= obr->ob->lay;
1460
1461                         break;
1462                 }
1463         }
1464 }
1465 static void get_particle_uvco_mcol(short from, DerivedMesh *dm, float *fuv, int num, ParticleStrandData *sd)
1466 {
1467         int i;
1468
1469         /* get uvco */
1470         if(sd->uvco && ELEM(from,PART_FROM_FACE,PART_FROM_VOLUME)) {
1471                 for(i=0; i<sd->totuv; i++) {
1472                         if(num != DMCACHE_NOTFOUND) {
1473                                 MFace *mface = dm->getFaceData(dm, num, CD_MFACE);
1474                                 MTFace *mtface = (MTFace*)CustomData_get_layer_n(&dm->faceData, CD_MTFACE, i);
1475                                 mtface += num;
1476                                 
1477                                 psys_interpolate_uvs(mtface, mface->v4, fuv, sd->uvco + 2 * i);
1478                         }
1479                         else {
1480                                 sd->uvco[2*i] = 0.0f;
1481                                 sd->uvco[2*i + 1] = 0.0f;
1482                         }
1483                 }
1484         }
1485
1486         /* get mcol */
1487         if(sd->mcol && ELEM(from,PART_FROM_FACE,PART_FROM_VOLUME)) {
1488                 for(i=0; i<sd->totcol; i++) {
1489                         if(num != DMCACHE_NOTFOUND) {
1490                                 MFace *mface = dm->getFaceData(dm, num, CD_MFACE);
1491                                 MCol *mc = (MCol*)CustomData_get_layer_n(&dm->faceData, CD_MCOL, i);
1492                                 mc += num * 4;
1493
1494                                 psys_interpolate_mcol(mc, mface->v4, fuv, sd->mcol + i);
1495                         }
1496                         else
1497                                 memset(&sd->mcol[i], 0, sizeof(MCol));
1498                 }
1499         }
1500 }
1501 static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem *psys, int timeoffset)
1502 {
1503         Object *ob= obr->ob;
1504 //      Object *tob=0;
1505         Material *ma=0;
1506         ParticleSystemModifierData *psmd;
1507         ParticleSystem *tpsys=0;
1508         ParticleSettings *part, *tpart=0;
1509         ParticleData *pars, *pa=0,*tpa=0;
1510         ParticleKey *states=0;
1511         ParticleKey state;
1512         ParticleCacheKey *cache=0;
1513         ParticleBillboardData bb;
1514         ParticleSimulationData sim = {re->scene, ob, psys, NULL};
1515         ParticleStrandData sd;
1516         StrandBuffer *strandbuf=0;
1517         StrandVert *svert=0;
1518         StrandBound *sbound= 0;
1519         StrandRen *strand=0;
1520         RNG *rng= 0;
1521         float loc[3],loc1[3],loc0[3],mat[4][4],nmat[3][3],co[3],nor[3],time;
1522         float strandlen=0.0f, curlen=0.0f;
1523         float hasize, pa_size, r_tilt, r_length, cfra=bsystem_time(re->scene, ob, (float)re->scene->r.cfra, 0.0);
1524         float pa_time, pa_birthtime, pa_dietime;
1525         float random, simplify[2];
1526         int i, a, k, max_k=0, totpart, dosimplify = 0, dosurfacecache = 0;
1527         int totchild=0;
1528         int seed, path_nbr=0, orco1=0, num;
1529         int totface, *origindex = 0;
1530         char **uv_name=0;
1531
1532 /* 1. check that everything is ok & updated */
1533         if(psys==NULL)
1534                 return 0;
1535         
1536         totchild=psys->totchild;
1537
1538         part=psys->part;
1539         pars=psys->particles;
1540
1541         if(part==NULL || pars==NULL || !psys_check_enabled(ob, psys))
1542                 return 0;
1543         
1544         if(part->ren_as==PART_DRAW_OB || part->ren_as==PART_DRAW_GR || part->ren_as==PART_DRAW_NOT)
1545                 return 1;
1546
1547 /* 2. start initialising things */
1548
1549         /* last possibility to bail out! */
1550         sim.psmd = psmd = psys_get_modifier(ob,psys);
1551         if(!(psmd->modifier.mode & eModifierMode_Render))
1552                 return 0;
1553
1554         if(part->phystype==PART_PHYS_KEYED)
1555                 psys_count_keyed_targets(&sim);
1556
1557
1558         if(G.rendering == 0) { /* preview render */
1559                 totchild = (int)((float)totchild * (float)part->disp / 100.0f);
1560         }
1561
1562         psys->flag |= PSYS_DRAWING;
1563
1564         rng= rng_new(psys->seed);
1565
1566         totpart=psys->totpart;
1567
1568         memset(&sd, 0, sizeof(ParticleStrandData));
1569         sd.override_uv = -1;
1570
1571 /* 2.1 setup material stff */
1572         ma= give_render_material(re, ob, part->omat);
1573         
1574 #if 0 // XXX old animation system
1575         if(ma->ipo){
1576                 calc_ipo(ma->ipo, cfra);
1577                 execute_ipo((ID *)ma, ma->ipo);
1578         }
1579 #endif // XXX old animation system
1580
1581         hasize = ma->hasize;
1582         seed = ma->seed1;
1583
1584         re->flag |= R_HALO;
1585
1586         RE_set_customdata_names(obr, &psmd->dm->faceData);
1587         sd.totuv = CustomData_number_of_layers(&psmd->dm->faceData, CD_MTFACE);
1588         sd.totcol = CustomData_number_of_layers(&psmd->dm->faceData, CD_MCOL);
1589
1590         if(ma->texco & TEXCO_UV && sd.totuv) {
1591                 sd.uvco = MEM_callocN(sd.totuv * 2 * sizeof(float), "particle_uvs");
1592
1593                 if(ma->strand_uvname[0]) {
1594                         sd.override_uv = CustomData_get_named_layer_index(&psmd->dm->faceData, CD_MTFACE, ma->strand_uvname);
1595                         sd.override_uv -= CustomData_get_layer_index(&psmd->dm->faceData, CD_MTFACE);
1596                 }
1597         }
1598         else
1599                 sd.uvco = NULL;
1600
1601         if(sd.totcol)
1602                 sd.mcol = MEM_callocN(sd.totcol * sizeof(MCol), "particle_mcols");
1603
1604 /* 2.2 setup billboards */
1605         if(part->ren_as == PART_DRAW_BB) {
1606                 int first_uv = CustomData_get_layer_index(&psmd->dm->faceData, CD_MTFACE);
1607
1608                 bb.uv[0] = CustomData_get_named_layer_index(&psmd->dm->faceData, CD_MTFACE, psys->bb_uvname[0]);
1609                 if(bb.uv[0] < 0)
1610                         bb.uv[0] = CustomData_get_active_layer_index(&psmd->dm->faceData, CD_MTFACE);
1611
1612                 bb.uv[1] = CustomData_get_named_layer_index(&psmd->dm->faceData, CD_MTFACE, psys->bb_uvname[1]);
1613
1614                 bb.uv[2] = CustomData_get_named_layer_index(&psmd->dm->faceData, CD_MTFACE, psys->bb_uvname[2]);
1615
1616                 if(first_uv >= 0) {
1617                         bb.uv[0] -= first_uv;
1618                         bb.uv[1] -= first_uv;
1619                         bb.uv[2] -= first_uv;
1620                 }
1621
1622                 bb.align = part->bb_align;
1623                 bb.anim = part->bb_anim;
1624                 bb.lock = part->draw & PART_DRAW_BB_LOCK;
1625                 bb.ob = (part->bb_ob ? part->bb_ob : re->scene->camera);
1626                 bb.offset[0] = part->bb_offset[0];
1627                 bb.offset[1] = part->bb_offset[1];
1628                 bb.split_offset = part->bb_split_offset;
1629                 bb.totnum = totpart+totchild;
1630                 bb.uv_split = part->bb_uv_split;
1631         }
1632
1633 #if 0 // XXX old animation system
1634 /* 2.3 setup time */
1635         if(part->flag&PART_ABS_TIME && part->ipo) {
1636                 calc_ipo(part->ipo, cfra);
1637                 execute_ipo((ID *)part, part->ipo);
1638         }
1639
1640         if(part->flag & PART_GLOB_TIME)
1641 #endif // XXX old animation system
1642         cfra = bsystem_time(re->scene, 0, (float)re->scene->r.cfra, 0.0);
1643
1644 ///* 2.4 setup reactors */
1645 //      if(part->type == PART_REACTOR){
1646 //              psys_get_reactor_target(ob, psys, &tob, &tpsys);
1647 //              if(tpsys && (part->from==PART_FROM_PARTICLE || part->phystype==PART_PHYS_NO)){
1648 //                      psmd = psys_get_modifier(tob,tpsys);
1649 //                      tpart = tpsys->part;
1650 //              }
1651 //      }
1652         
1653 /* 2.5 setup matrices */
1654         mul_m4_m4m4(mat, ob->obmat, re->viewmat);
1655         invert_m4_m4(ob->imat, mat);    /* need to be that way, for imat texture */
1656         copy_m3_m4(nmat, ob->imat);
1657         transpose_m3(nmat);
1658
1659 /* 2.6 setup strand rendering */
1660         if(part->ren_as == PART_DRAW_PATH && psys->pathcache){
1661                 path_nbr=(int)pow(2.0,(double) part->ren_step);
1662
1663                 if(path_nbr) {
1664                         if(!ELEM(ma->material_type, MA_TYPE_HALO, MA_TYPE_WIRE)) {
1665                                 sd.orco = MEM_mallocN(3*sizeof(float)*(totpart+totchild), "particle orcos");
1666                                 set_object_orco(re, psys, sd.orco);
1667                         }
1668                 }
1669
1670                 if(part->draw & PART_DRAW_REN_ADAPT) {
1671                         sd.adapt = 1;
1672                         sd.adapt_pix = (float)part->adapt_pix;
1673                         sd.adapt_angle = cos((float)part->adapt_angle * (float)(M_PI / 180.0));
1674                 }
1675
1676                 if(re->r.renderer==R_INTERN && part->draw&PART_DRAW_REN_STRAND) {
1677                         strandbuf= RE_addStrandBuffer(obr, (totpart+totchild)*(path_nbr+1));
1678                         strandbuf->ma= ma;
1679                         strandbuf->lay= ob->lay;
1680                         copy_m4_m4(strandbuf->winmat, re->winmat);
1681                         strandbuf->winx= re->winx;
1682                         strandbuf->winy= re->winy;
1683                         strandbuf->maxdepth= 2;
1684                         strandbuf->adaptcos= cos((float)part->adapt_angle*(float)(M_PI/180.0));
1685                         strandbuf->overrideuv= sd.override_uv;
1686                         strandbuf->minwidth= ma->strand_min;
1687
1688                         if(ma->strand_widthfade == 0.0f)
1689                                 strandbuf->widthfade= 0.0f;
1690                         else if(ma->strand_widthfade >= 1.0f)
1691                                 strandbuf->widthfade= 2.0f - ma->strand_widthfade;
1692                         else
1693                                 strandbuf->widthfade= 1.0f/MAX2(ma->strand_widthfade, 1e-5f);
1694
1695                         if(part->flag & PART_HAIR_BSPLINE)
1696                                 strandbuf->flag |= R_STRAND_BSPLINE;
1697                         if(ma->mode & MA_STR_B_UNITS)
1698                                 strandbuf->flag |= R_STRAND_B_UNITS;
1699
1700                         svert= strandbuf->vert;
1701
1702                         if(re->r.mode & R_SPEED)
1703                                 dosurfacecache= 1;
1704                         else if((re->wrld.mode & (WO_AMB_OCC|WO_ENV_LIGHT|WO_INDIRECT_LIGHT)) && (re->wrld.ao_gather_method == WO_AOGATHER_APPROX))
1705                                 if(ma->amb != 0.0f)
1706                                         dosurfacecache= 1;
1707
1708                         totface= psmd->dm->getNumFaces(psmd->dm);
1709                         origindex= psmd->dm->getFaceDataArray(psmd->dm, CD_ORIGINDEX);
1710                         for(a=0; a<totface; a++)
1711                                 strandbuf->totbound= MAX2(strandbuf->totbound, (origindex)? origindex[a]: a);
1712
1713                         strandbuf->totbound++;
1714                         strandbuf->bound= MEM_callocN(sizeof(StrandBound)*strandbuf->totbound, "StrandBound");
1715                         sbound= strandbuf->bound;
1716                         sbound->start= sbound->end= 0;
1717                 }
1718         }
1719
1720         if(sd.orco == 0) {
1721                 sd.orco = MEM_mallocN(3 * sizeof(float), "particle orco");
1722                 orco1 = 1;
1723         }
1724
1725         if(path_nbr == 0)
1726                 psys->lattice = psys_get_lattice(&sim);
1727
1728 /* 3. start creating renderable things */
1729         for(a=0,pa=pars; a<totpart+totchild; a++, pa++, seed++) {
1730                 random = rng_getFloat(rng);
1731                 /* setup per particle individual stuff */
1732                 if(a<totpart){
1733                         if(pa->flag & PARS_UNEXIST) continue;
1734
1735                         pa_time=(cfra-pa->time)/pa->lifetime;
1736                         pa_birthtime = pa->time;
1737                         pa_dietime = pa->dietime;
1738 #if 0 // XXX old animation system
1739                         if((part->flag&PART_ABS_TIME) == 0){
1740                                 if(ma->ipo) {
1741                                         /* correction for lifetime */
1742                                         calc_ipo(ma->ipo, 100.0f * pa_time);
1743                                         execute_ipo((ID *)ma, ma->ipo);
1744                                 }
1745                                 if(part->ipo){
1746                                         /* correction for lifetime */
1747                                         calc_ipo(part->ipo, 100.0f*pa_time);
1748                                         execute_ipo((ID *)part, part->ipo);
1749                                 }
1750                         }
1751 #endif // XXX old animation system
1752
1753                         hasize = ma->hasize;
1754
1755                         /* get orco */
1756                         if(tpsys && (part->from==PART_FROM_PARTICLE || part->phystype==PART_PHYS_NO)){
1757                                 tpa=tpsys->particles+pa->num;
1758                                 psys_particle_on_emitter(psmd,tpart->from,tpa->num,pa->num_dmcache,tpa->fuv,tpa->foffset,co,nor,0,0,sd.orco,0);
1759                         }
1760                         else
1761                                 psys_particle_on_emitter(psmd,part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,nor,0,0,sd.orco,0);
1762
1763                         /* get uvco & mcol */
1764                         num= pa->num_dmcache;
1765
1766                         if(num == DMCACHE_NOTFOUND)
1767                                 if(pa->num < psmd->dm->getNumFaces(psmd->dm))
1768                                         num= pa->num;
1769
1770                         get_particle_uvco_mcol(part->from, psmd->dm, pa->fuv, num, &sd);
1771
1772                         pa_size = pa->size;
1773
1774                         BLI_srandom(psys->seed+a);
1775
1776                         r_tilt = 2.0f*(BLI_frand() - 0.5f);
1777                         r_length = BLI_frand();
1778
1779                         if(path_nbr) {
1780                                 cache = psys->pathcache[a];
1781                                 max_k = (int)cache->steps;
1782                         }
1783
1784                         if(totchild && (part->draw&PART_DRAW_PARENT)==0) continue;
1785                 }
1786                 else {
1787                         ChildParticle *cpa= psys->child+a-totpart;
1788
1789                         if(path_nbr) {
1790                                 cache = psys->childcache[a-totpart];
1791
1792                                 if(cache->steps < 0)
1793                                         continue;
1794
1795                                 max_k = (int)cache->steps;
1796                         }
1797                         
1798                         pa_time = psys_get_child_time(psys, cpa, cfra, &pa_birthtime, &pa_dietime);
1799
1800 #if 0 // XXX old animation system
1801                         if((part->flag & PART_ABS_TIME) == 0) {
1802                                 if(ma->ipo){
1803                                         /* correction for lifetime */
1804                                         calc_ipo(ma->ipo, 100.0f * pa_time);
1805                                         execute_ipo((ID *)ma, ma->ipo);
1806                                 }
1807                                 if(part->ipo) {
1808                                         /* correction for lifetime */
1809                                         calc_ipo(part->ipo, 100.0f * pa_time);
1810                                         execute_ipo((ID *)part, part->ipo);
1811                                 }
1812                         }
1813 #endif // XXX old animation system
1814
1815                         pa_size = psys_get_child_size(psys, cpa, cfra, &pa_time);
1816
1817                         r_tilt = 2.0f*(PSYS_FRAND(a + 21) - 0.5f);
1818                         r_length = PSYS_FRAND(a + 22);
1819
1820                         num = cpa->num;
1821
1822                         /* get orco */
1823                         if(part->childtype == PART_CHILD_FACES) {
1824                                 psys_particle_on_emitter(psmd,
1825                                         PART_FROM_FACE, cpa->num,DMCACHE_ISCHILD,
1826                                         cpa->fuv,cpa->foffset,co,nor,0,0,sd.orco,0);
1827                         }
1828                         else {
1829                                 ParticleData *par = psys->particles + cpa->parent;
1830                                 psys_particle_on_emitter(psmd, part->from,
1831                                         par->num,DMCACHE_ISCHILD,par->fuv,
1832                                         par->foffset,co,nor,0,0,sd.orco,0);
1833                         }
1834
1835                         /* get uvco & mcol */
1836                         if(part->from!=PART_FROM_PARTICLE && part->childtype==PART_CHILD_FACES) {
1837                                 get_particle_uvco_mcol(PART_FROM_FACE, psmd->dm, cpa->fuv, cpa->num, &sd);
1838                         }
1839                         else {
1840                                 ParticleData *parent = psys->particles + cpa->parent;
1841                                 num = parent->num_dmcache;
1842
1843                                 if(num == DMCACHE_NOTFOUND)
1844                                         if(parent->num < psmd->dm->getNumFaces(psmd->dm))
1845                                                 num = parent->num;
1846
1847                                 get_particle_uvco_mcol(part->from, psmd->dm, parent->fuv, num, &sd);
1848                         }
1849
1850                         dosimplify = psys_render_simplify_params(psys, cpa, simplify);
1851
1852                         if(strandbuf) {
1853                                 int orignum= (origindex)? origindex[cpa->num]: cpa->num;
1854
1855                                 if(orignum > sbound - strandbuf->bound) {
1856                                         sbound= strandbuf->bound + orignum;
1857                                         sbound->start= sbound->end= obr->totstrand;
1858                                 }
1859                         }
1860                 }
1861
1862                 /* surface normal shading setup */
1863                 if(ma->mode_l & MA_STR_SURFDIFF) {
1864                         mul_m3_v3(nmat, nor);
1865                         sd.surfnor= nor;
1866                 }
1867                 else
1868                         sd.surfnor= NULL;
1869
1870                 /* strand render setup */
1871                 if(strandbuf) {
1872                         strand= RE_findOrAddStrand(obr, obr->totstrand++);
1873                         strand->buffer= strandbuf;
1874                         strand->vert= svert;
1875                         VECCOPY(strand->orco, sd.orco);
1876
1877                         if(dosimplify) {
1878                                 float *ssimplify= RE_strandren_get_simplify(obr, strand, 1);
1879                                 ssimplify[0]= simplify[0];
1880                                 ssimplify[1]= simplify[1];
1881                         }
1882
1883                         if(sd.surfnor) {
1884                                 float *snor= RE_strandren_get_surfnor(obr, strand, 1);
1885                                 VECCOPY(snor, sd.surfnor);
1886                         }
1887
1888                         if(dosurfacecache && num >= 0) {
1889                                 int *facenum= RE_strandren_get_face(obr, strand, 1);
1890                                 *facenum= num;
1891                         }
1892
1893                         if(sd.uvco) {
1894                                 for(i=0; i<sd.totuv; i++) {
1895                                         if(i != sd.override_uv) {
1896                                                 float *uv= RE_strandren_get_uv(obr, strand, i, NULL, 1);
1897
1898                                                 uv[0]= sd.uvco[2*i];
1899                                                 uv[1]= sd.uvco[2*i+1];
1900                                         }
1901                                 }
1902                         }
1903                         if(sd.mcol) {
1904                                 for(i=0; i<sd.totcol; i++) {
1905                                         MCol *mc= RE_strandren_get_mcol(obr, strand, i, NULL, 1);
1906                                         *mc = sd.mcol[i];
1907                                 }
1908                         }
1909
1910                         sbound->end++;
1911                 }
1912
1913                 /* strandco computation setup */
1914                 if(path_nbr) {
1915                         strandlen= 0.0f;
1916                         curlen= 0.0f;
1917                         for(k=1; k<=path_nbr; k++)
1918                                 if(k<=max_k)
1919                                         strandlen += len_v3v3((cache+k-1)->co, (cache+k)->co);
1920                 }
1921
1922                 if(path_nbr) {
1923                         /* render strands */
1924                         for(k=0; k<=path_nbr; k++){
1925                                 if(k<=max_k){
1926                                         VECCOPY(state.co,(cache+k)->co);
1927                                         VECCOPY(state.vel,(cache+k)->vel);
1928                                 }
1929                                 else
1930                                         continue;       
1931
1932                                 if(k > 0)
1933                                         curlen += len_v3v3((cache+k-1)->co, (cache+k)->co);
1934                                 time= curlen/strandlen;
1935
1936                                 VECCOPY(loc,state.co);
1937                                 mul_m4_v3(re->viewmat,loc);
1938
1939                                 if(strandbuf) {
1940                                         VECCOPY(svert->co, loc);
1941                                         svert->strandco= -1.0f + 2.0f*time;
1942                                         svert++;
1943                                         strand->totvert++;
1944                                 }
1945                                 else{
1946                                         sd.size = hasize;
1947
1948                                         if(k==1){
1949                                                 sd.first = 1;
1950                                                 sd.time = 0.0f;
1951                                                 VECSUB(loc0,loc1,loc);
1952                                                 VECADD(loc0,loc1,loc0);
1953
1954                                                 particle_curve(re, obr, psmd->dm, ma, &sd, loc1, loc0, seed);
1955                                         }
1956
1957                                         sd.first = 0;
1958                                         sd.time = time;
1959
1960                                         if(k)
1961                                                 particle_curve(re, obr, psmd->dm, ma, &sd, loc, loc1, seed);
1962
1963                                         VECCOPY(loc1,loc);
1964                                 }
1965                         }
1966
1967                 }
1968                 else {
1969                         /* render normal particles */
1970                         if(part->trail_count > 1) {
1971                                 float length = part->path_end * (1.0 - part->randlength * r_length);
1972                                 int trail_count = part->trail_count * (1.0 - part->randlength * r_length);
1973                                 float ct = (part->draw & PART_ABS_PATH_TIME) ? cfra : pa_time;
1974                                 float dt = length / (trail_count ? (float)trail_count : 1.0f);
1975
1976                                 for(i=0; i < trail_count; i++, ct -= dt) {
1977                                         if(part->draw & PART_ABS_PATH_TIME) {
1978                                                 if(ct < pa_birthtime || ct > pa_dietime)
1979                                                         continue;
1980                                         }
1981                                         else if(ct < 0.0f || ct > 1.0f)
1982                                                 continue;
1983
1984                                         state.time = (part->draw & PART_ABS_PATH_TIME) ? -ct : ct;
1985                                         psys_get_particle_on_path(&sim,a,&state,1);
1986
1987                                         if(psys->parent)
1988                                                 mul_m4_v3(psys->parent->obmat, state.co);
1989
1990                                         if(part->ren_as == PART_DRAW_BB) {
1991                                                 bb.random = random;
1992                                                 bb.size = pa_size;
1993                                                 bb.tilt = part->bb_tilt * (1.0f - part->bb_rand_tilt * r_tilt);
1994                                                 bb.time = ct;
1995                                                 bb.num = a;
1996                                         }
1997
1998                                         particle_normal_ren(part->ren_as, part, re, obr, psmd->dm, ma, &sd, &bb, &state, seed, hasize);
1999                                 }
2000                         }
2001                         else {
2002                                 time=0.0f;
2003                                 state.time=cfra;
2004                                 if(psys_get_particle_state(&sim,a,&state,0)==0)
2005                                         continue;
2006
2007                                 if(psys->parent)
2008                                         mul_m4_v3(psys->parent->obmat, state.co);
2009
2010                                 if(part->ren_as == PART_DRAW_BB) {
2011                                         bb.random = random;
2012                                         bb.size = pa_size;
2013                                         bb.tilt = part->bb_tilt * (1.0f - part->bb_rand_tilt * r_tilt);
2014                                         bb.time = pa_time;
2015                                         bb.num = a;
2016                                 }
2017
2018                                 particle_normal_ren(part->ren_as, part, re, obr, psmd->dm, ma, &sd, &bb, &state, seed, hasize);
2019                         }
2020                 }
2021
2022                 if(orco1==0)
2023                         sd.orco+=3;
2024
2025                 if(re->test_break(re->tbh))
2026                         break;
2027         }
2028
2029         if(dosurfacecache)
2030                 strandbuf->surface= cache_strand_surface(re, obr, psmd->dm, mat, timeoffset);
2031
2032 /* 4. clean up */
2033 #if 0 // XXX old animation system
2034         if(ma) do_mat_ipo(re->scene, ma);
2035 #endif // XXX old animation system
2036         
2037         if(orco1)
2038                 MEM_freeN(sd.orco);
2039
2040         if(sd.uvco)
2041                 MEM_freeN(sd.uvco);
2042         
2043         if(sd.mcol)
2044                 MEM_freeN(sd.mcol);
2045
2046         if(uv_name)
2047                 MEM_freeN(uv_name);
2048
2049         if(states)
2050                 MEM_freeN(states);
2051         
2052         rng_free(rng);
2053
2054         psys->flag &= ~PSYS_DRAWING;
2055
2056         if(psys->lattice){
2057                 end_latt_deform(psys->lattice);
2058                 psys->lattice= NULL;
2059         }
2060
2061         if(path_nbr && (ma->mode_l & MA_TANGENT_STR)==0)
2062                 calc_vertexnormals(re, obr, 0, 0);
2063
2064         return 1;
2065 }
2066
2067 /* ------------------------------------------------------------------------- */
2068 /* Halo's                                                                                                                                */
2069 /* ------------------------------------------------------------------------- */
2070
2071 static void make_render_halos(Render *re, ObjectRen *obr, Mesh *me, int totvert, MVert *mvert, Material *ma, float *orco)
2072 {
2073         Object *ob= obr->ob;
2074         HaloRen *har;
2075         float xn, yn, zn, nor[3], view[3];
2076         float vec[3], hasize, mat[4][4], imat[3][3];
2077         int a, ok, seed= ma->seed1;
2078
2079         mul_m4_m4m4(mat, ob->obmat, re->viewmat);
2080         copy_m3_m4(imat, ob->imat);
2081
2082         re->flag |= R_HALO;
2083
2084         for(a=0; a<totvert; a++, mvert++) {
2085                 ok= 1;
2086
2087                 if(ok) {
2088                         hasize= ma->hasize;
2089
2090                         VECCOPY(vec, mvert->co);
2091                         mul_m4_v3(mat, vec);
2092
2093                         if(ma->mode & MA_HALOPUNO) {
2094                                 xn= mvert->no[0];
2095                                 yn= mvert->no[1];
2096                                 zn= mvert->no[2];
2097
2098                                 /* transpose ! */
2099                                 nor[0]= imat[0][0]*xn+imat[0][1]*yn+imat[0][2]*zn;
2100                                 nor[1]= imat[1][0]*xn+imat[1][1]*yn+imat[1][2]*zn;
2101                                 nor[2]= imat[2][0]*xn+imat[2][1]*yn+imat[2][2]*zn;
2102                                 normalize_v3(nor);
2103
2104                                 VECCOPY(view, vec);
2105                                 normalize_v3(view);
2106
2107                                 zn= nor[0]*view[0]+nor[1]*view[1]+nor[2]*view[2];
2108                                 if(zn>=0.0) hasize= 0.0;
2109                                 else hasize*= zn*zn*zn*zn;
2110                         }
2111
2112                         if(orco) har= RE_inithalo(re, obr, ma, vec, NULL, orco, hasize, 0.0, seed);
2113                         else har= RE_inithalo(re, obr, ma, vec, NULL, mvert->co, hasize, 0.0, seed);
2114                         if(har) har->lay= ob->lay;
2115                 }
2116                 if(orco) orco+= 3;
2117                 seed++;
2118         }
2119 }
2120
2121 static int verghalo(const void *a1, const void *a2)
2122 {
2123         const HaloRen *har1= *(const HaloRen**)a1;
2124         const HaloRen *har2= *(const HaloRen**)a2;
2125         
2126         if(har1->zs < har2->zs) return 1;
2127         else if(har1->zs > har2->zs) return -1;
2128         return 0;
2129 }
2130
2131 static void sort_halos(Render *re, int totsort)
2132 {
2133         ObjectRen *obr;
2134         HaloRen *har= NULL, **haso;
2135         int a;
2136
2137         if(re->tothalo==0) return;
2138
2139         re->sortedhalos= MEM_callocN(sizeof(HaloRen*)*re->tothalo, "sorthalos");
2140         haso= re->sortedhalos;
2141
2142         for(obr=re->objecttable.first; obr; obr=obr->next) {
2143                 for(a=0; a<obr->tothalo; a++) {
2144                         if((a & 255)==0) har= obr->bloha[a>>8];
2145                         else har++;
2146
2147                         *(haso++)= har;
2148                 }
2149         }
2150
2151         qsort(re->sortedhalos, totsort, sizeof(HaloRen*), verghalo);
2152 }
2153
2154 /* ------------------------------------------------------------------------- */
2155 /* Displacement Mapping                                                                                                          */
2156 /* ------------------------------------------------------------------------- */
2157
2158 static short test_for_displace(Render *re, Object *ob)
2159 {
2160         /* return 1 when this object uses displacement textures. */
2161         Material *ma;
2162         int i;
2163         
2164         for (i=1; i<=ob->totcol; i++) {
2165                 ma=give_render_material(re, ob, i);
2166                 /* ma->mapto is ORed total of all mapto channels */
2167                 if(ma && (ma->mapto & MAP_DISPLACE)) return 1;
2168         }
2169         return 0;
2170 }
2171
2172 static void displace_render_vert(Render *re, ObjectRen *obr, ShadeInput *shi, VertRen *vr, int vindex, float *scale, float mat[][4], float imat[][3])
2173 {
2174         MTFace *tface;
2175         short texco= shi->mat->texco;
2176         float sample=0, displace[3];
2177         char *name;
2178         int i;
2179
2180         /* shi->co is current render coord, just make sure at least some vector is here */
2181         VECCOPY(shi->co, vr->co);
2182         /* vertex normal is used for textures type 'col' and 'var' */
2183         VECCOPY(shi->vn, vr->n);
2184
2185         if(mat)
2186                 mul_m4_v3(mat, shi->co);
2187
2188         if(imat) {
2189                 shi->vn[0]= imat[0][0]*vr->n[0]+imat[0][1]*vr->n[1]+imat[0][2]*vr->n[2];
2190                 shi->vn[1]= imat[1][0]*vr->n[0]+imat[1][1]*vr->n[1]+imat[1][2]*vr->n[2];
2191                 shi->vn[2]= imat[2][0]*vr->n[0]+imat[2][1]*vr->n[1]+imat[2][2]*vr->n[2];
2192         }
2193
2194         if (texco & TEXCO_UV) {
2195                 shi->totuv= 0;
2196                 shi->actuv= obr->actmtface;
2197
2198                 for (i=0; (tface=RE_vlakren_get_tface(obr, shi->vlr, i, &name, 0)); i++) {
2199                         ShadeInputUV *suv= &shi->uv[i];
2200
2201                         /* shi.uv needs scale correction from tface uv */
2202                         suv->uv[0]= 2*tface->uv[vindex][0]-1.0f;
2203                         suv->uv[1]= 2*tface->uv[vindex][1]-1.0f;
2204                         suv->uv[2]= 0.0f;
2205                         suv->name= name;
2206                         shi->totuv++;
2207                 }
2208         }
2209
2210         /* set all rendercoords, 'texco' is an ORed value for all textures needed */
2211         if ((texco & TEXCO_ORCO) && (vr->orco)) {
2212                 VECCOPY(shi->lo, vr->orco);
2213         }
2214         if (texco & TEXCO_STICKY) {
2215                 float *sticky= RE_vertren_get_sticky(obr, vr, 0);
2216                 if(sticky) {
2217                         shi->sticky[0]= sticky[0];
2218                         shi->sticky[1]= sticky[1];
2219                         shi->sticky[2]= 0.0f;
2220                 }
2221         }
2222         if (texco & TEXCO_GLOB) {
2223                 VECCOPY(shi->gl, shi->co);
2224                 mul_m4_v3(re->viewinv, shi->gl);
2225         }
2226         if (texco & TEXCO_NORM) {
2227                 VECCOPY(shi->orn, shi->vn);
2228         }
2229         if(texco & TEXCO_REFL) {
2230                 /* not (yet?) */
2231         }
2232         
2233         shi->displace[0]= shi->displace[1]= shi->displace[2]= 0.0;
2234         
2235         do_material_tex(shi);
2236         
2237         //printf("no=%f, %f, %f\nbefore co=%f, %f, %f\n", vr->n[0], vr->n[1], vr->n[2], 
2238         //vr->co[0], vr->co[1], vr->co[2]);
2239
2240         displace[0]= shi->displace[0] * scale[0];
2241         displace[1]= shi->displace[1] * scale[1];
2242         displace[2]= shi->displace[2] * scale[2];
2243         
2244         if(mat)
2245                 mul_m3_v3(imat, displace);
2246
2247         /* 0.5 could become button once?  */
2248         vr->co[0] += displace[0]; 
2249         vr->co[1] += displace[1];
2250         vr->co[2] += displace[2];
2251         
2252         //printf("after co=%f, %f, %f\n", vr->co[0], vr->co[1], vr->co[2]); 
2253         
2254         /* we just don't do this vertex again, bad luck for other face using same vertex with
2255                 different material... */
2256         vr->flag |= 1;
2257         
2258         /* Pass sample back so displace_face can decide which way to split the quad */
2259         sample  = shi->displace[0]*shi->displace[0];
2260         sample += shi->displace[1]*shi->displace[1];
2261         sample += shi->displace[2]*shi->displace[2];
2262         
2263         vr->accum=sample; 
2264         /* Should be sqrt(sample), but I'm only looking for "bigger".  Save the cycles. */
2265         return;
2266 }
2267
2268 static void displace_render_face(Render *re, ObjectRen *obr, VlakRen *vlr, float *scale, float mat[][4], float imat[][3])
2269 {
2270         ShadeInput shi;
2271
2272         /* Warning, This is not that nice, and possibly a bit slow,
2273         however some variables were not initialized properly in, unless using shade_input_initialize(...), we need to do a memset */
2274         memset(&shi, 0, sizeof(ShadeInput)); 
2275         /* end warning! - Campbell */
2276         
2277         /* set up shadeinput struct for multitex() */
2278         
2279         /* memset above means we dont need this */
2280         /*shi.osatex= 0;*/              /* signal not to use dx[] and dy[] texture AA vectors */
2281
2282         shi.obr= obr;
2283         shi.vlr= vlr;           /* current render face */
2284         shi.mat= vlr->mat;              /* current input material */
2285         shi.thread= 0;
2286         
2287         /* TODO, assign these, displacement with new bumpmap is skipped without - campbell */
2288 #if 0
2289         /* order is not known ? */
2290         shi.v1= vlr->v1;
2291         shi.v2= vlr->v2;
2292         shi.v3= vlr->v3;
2293 #endif
2294
2295         /* Displace the verts, flag is set when done */
2296         if (!vlr->v1->flag)
2297                 displace_render_vert(re, obr, &shi, vlr->v1,0,  scale, mat, imat);
2298         
2299         if (!vlr->v2->flag)
2300                 displace_render_vert(re, obr, &shi, vlr->v2, 1, scale, mat, imat);
2301
2302         if (!vlr->v3->flag)
2303                 displace_render_vert(re, obr, &shi, vlr->v3, 2, scale, mat, imat);
2304
2305         if (vlr->v4) {
2306                 if (!vlr->v4->flag)
2307                         displace_render_vert(re, obr, &shi, vlr->v4, 3, scale, mat, imat);
2308
2309                 /*      closest in displace value.  This will help smooth edges.   */ 
2310                 if ( fabs(vlr->v1->accum - vlr->v3->accum) > fabs(vlr->v2->accum - vlr->v4->accum)) 
2311                         vlr->flag |= R_DIVIDE_24;
2312                 else vlr->flag &= ~R_DIVIDE_24;
2313         }
2314         
2315         /* Recalculate the face normal  - if flipped before, flip now */
2316         if(vlr->v4) {
2317                 normal_quad_v3( vlr->n,vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co);
2318         }       
2319         else {
2320                 normal_tri_v3( vlr->n,vlr->v3->co, vlr->v2->co, vlr->v1->co);
2321         }
2322 }
2323
2324 static void do_displacement(Render *re, ObjectRen *obr, float mat[][4], float imat[][3])
2325 {
2326         VertRen *vr;
2327         VlakRen *vlr;
2328 //      float min[3]={1e30, 1e30, 1e30}, max[3]={-1e30, -1e30, -1e30};
2329         float scale[3]={1.0f, 1.0f, 1.0f}, temp[3];//, xn
2330         int i; //, texflag=0;
2331         Object *obt;
2332                 
2333         /* Object Size with parenting */
2334         obt=obr->ob;
2335         while(obt){
2336                 add_v3_v3v3(temp, obt->size, obt->dsize);
2337                 scale[0]*=temp[0]; scale[1]*=temp[1]; scale[2]*=temp[2];
2338                 obt=obt->parent;
2339         }
2340         
2341         /* Clear all flags */
2342         for(i=0; i<obr->totvert; i++){ 
2343                 vr= RE_findOrAddVert(obr, i);
2344                 vr->flag= 0;
2345         }
2346
2347         for(i=0; i<obr->totvlak; i++){
2348                 vlr=RE_findOrAddVlak(obr, i);
2349                 displace_render_face(re, obr, vlr, scale, mat, imat);
2350         }
2351         
2352         /* Recalc vertex normals */
2353         calc_vertexnormals(re, obr, 0, 0);
2354 }
2355
2356 /* ------------------------------------------------------------------------- */
2357 /* Metaball                                                                                                                              */
2358 /* ------------------------------------------------------------------------- */
2359
2360 static void init_render_mball(Render *re, ObjectRen *obr)
2361 {
2362         Object *ob= obr->ob;
2363         DispList *dl;
2364         VertRen *ver;
2365         VlakRen *vlr, *vlr1;
2366         Material *ma;
2367         float *data, *nors, *orco, mat[4][4], imat[3][3], xn, yn, zn;
2368         int a, need_orco, vlakindex, *index;
2369
2370         if (ob!=find_basis_mball(re->scene, ob))
2371                 return;
2372
2373         mul_m4_m4m4(mat, ob->obmat, re->viewmat);
2374         invert_m4_m4(ob->imat, mat);
2375         copy_m3_m4(imat, ob->imat);
2376
2377         ma= give_render_material(re, ob, 1);
2378
2379         need_orco= 0;
2380         if(ma->texco & TEXCO_ORCO) {
2381                 need_orco= 1;
2382         }
2383         
2384         makeDispListMBall(re->scene, ob);
2385         dl= ob->disp.first;
2386         if(dl==0) return;
2387
2388         data= dl->verts;
2389         nors= dl->nors;
2390         orco= get_object_orco(re, ob);
2391
2392         for(a=0; a<dl->nr; a++, data+=3, nors+=3, orco+=3) {
2393
2394                 ver= RE_findOrAddVert(obr, obr->totvert++);
2395                 VECCOPY(ver->co, data);
2396                 mul_m4_v3(mat, ver->co);
2397
2398                 /* render normals are inverted */
2399                 xn= -nors[0];
2400                 yn= -nors[1];
2401                 zn= -nors[2];
2402
2403                 /* transpose ! */
2404                 ver->n[0]= imat[0][0]*xn+imat[0][1]*yn+imat[0][2]*zn;
2405                 ver->n[1]= imat[1][0]*xn+imat[1][1]*yn+imat[1][2]*zn;
2406                 ver->n[2]= imat[2][0]*xn+imat[2][1]*yn+imat[2][2]*zn;
2407                 normalize_v3(ver->n);
2408                 //if(ob->transflag & OB_NEG_SCALE) negate_v3(ver->n);
2409                 
2410                 if(need_orco) ver->orco= orco;
2411         }
2412
2413         index= dl->index;
2414         for(a=0; a<dl->parts; a++, index+=4) {
2415
2416                 vlr= RE_findOrAddVlak(obr, obr->totvlak++);
2417                 vlr->v1= RE_findOrAddVert(obr, index[0]);
2418                 vlr->v2= RE_findOrAddVert(obr, index[1]);
2419                 vlr->v3= RE_findOrAddVert(obr, index[2]);
2420                 vlr->v4= 0;
2421
2422                 if(ob->transflag & OB_NEG_SCALE) 
2423                         normal_tri_v3( vlr->n,vlr->v1->co, vlr->v2->co, vlr->v3->co);
2424                 else
2425                         normal_tri_v3( vlr->n,vlr->v3->co, vlr->v2->co, vlr->v1->co);
2426
2427                 vlr->mat= ma;
2428                 vlr->flag= ME_SMOOTH+R_NOPUNOFLIP;
2429                 vlr->ec= 0;
2430
2431                 /* mball -too bad- always has triangles, because quads can be non-planar */
2432                 if(index[3] && index[3]!=index[2]) {
2433                         vlr1= RE_findOrAddVlak(obr, obr->totvlak++);
2434                         vlakindex= vlr1->index;
2435                         *vlr1= *vlr;
2436                         vlr1->index= vlakindex;
2437                         vlr1->v2= vlr1->v3;
2438                         vlr1->v3= RE_findOrAddVert(obr, index[3]);
2439                         if(ob->transflag & OB_NEG_SCALE) 
2440                                 normal_tri_v3( vlr1->n,vlr1->v1->co, vlr1->v2->co, vlr1->v3->co);
2441                         else
2442                                 normal_tri_v3( vlr1->n,vlr1->v3->co, vlr1->v2->co, vlr1->v1->co);
2443                 }
2444         }
2445
2446         /* enforce display lists remade */
2447         freedisplist(&ob->disp);
2448         
2449         /* this enforces remake for real, orco displist is small (in scale) */
2450         ob->recalc |= OB_RECALC_DATA;
2451 }
2452
2453 /* ------------------------------------------------------------------------- */
2454 /* Surfaces and Curves                                                                                                           */
2455 /* ------------------------------------------------------------------------- */
2456
2457 /* returns amount of vertices added for orco */
2458 static int dl_surf_to_renderdata(ObjectRen *obr, DispList *dl, Material **matar, float *orco, float mat[4][4])
2459 {
2460         Object *ob= obr->ob;
2461         VertRen *v1, *v2, *v3, *v4, *ver;
2462         VlakRen *vlr, *vlr1, *vlr2, *vlr3;
2463         Curve *cu= ob->data;
2464         float *data, n1[3];
2465         int u, v, orcoret= 0;
2466         int p1, p2, p3, p4, a;
2467         int sizeu, nsizeu, sizev, nsizev;
2468         int startvert, startvlak;
2469         
2470         startvert= obr->totvert;
2471         nsizeu = sizeu = dl->parts; nsizev = sizev = dl->nr; 
2472         
2473         data= dl->verts;
2474         for (u = 0; u < sizeu; u++) {
2475                 v1 = RE_findOrAddVert(obr, obr->totvert++); /* save this for possible V wrapping */
2476                 VECCOPY(v1->co, data); data += 3;
2477                 if(orco) {
2478                         v1->orco= orco; orco+= 3; orcoret++;
2479                 }       
2480                 mul_m4_v3(mat, v1->co);
2481                 
2482                 for (v = 1; v < sizev; v++) {
2483                         ver= RE_findOrAddVert(obr, obr->totvert++);
2484                         VECCOPY(ver->co, data); data += 3;
2485                         if(orco) {
2486                                 ver->orco= orco; orco+= 3; orcoret++;
2487                         }       
2488                         mul_m4_v3(mat, ver->co);
2489                 }
2490                 /* if V-cyclic, add extra vertices at end of the row */
2491                 if (dl->flag & DL_CYCL_U) {
2492                         ver= RE_findOrAddVert(obr, obr->totvert++);
2493                         VECCOPY(ver->co, v1->co);
2494                         if(orco) {
2495                                 ver->orco= orco; orco+=3; orcoret++; //orcobase + 3*(u*sizev + 0);
2496                         }
2497                 }       
2498         }       
2499         
2500         /* Done before next loop to get corner vert */
2501         if (dl->flag & DL_CYCL_U) nsizev++;
2502         if (dl->flag & DL_CYCL_V) nsizeu++;
2503         
2504         /* if U cyclic, add extra row at end of column */
2505         if (dl->flag & DL_CYCL_V) {
2506                 for (v = 0; v < nsizev; v++) {
2507                         v1= RE_findOrAddVert(obr, startvert + v);
2508                         ver= RE_findOrAddVert(obr, obr->totvert++);
2509                         VECCOPY(ver->co, v1->co);
2510                         if(orco) {
2511                                 ver->orco= orco; orco+=3; orcoret++; //ver->orco= orcobase + 3*(0*sizev + v);
2512                         }
2513                 }
2514         }
2515         
2516         sizeu = nsizeu;
2517         sizev = nsizev;
2518         
2519         startvlak= obr->totvlak;
2520         
2521         for(u = 0; u < sizeu - 1; u++) {
2522                 p1 = startvert + u * sizev; /* walk through face list */
2523                 p2 = p1 + 1;
2524                 p3 = p2 + sizev;
2525                 p4 = p3 - 1;
2526                 
2527                 for(v = 0; v < sizev - 1; v++) {
2528                         v1= RE_findOrAddVert(obr, p1);
2529                         v2= RE_findOrAddVert(obr, p2);
2530                         v3= RE_findOrAddVert(obr, p3);
2531                         v4= RE_findOrAddVert(obr, p4);
2532                         
2533                         vlr= RE_findOrAddVlak(obr, obr->totvlak++);
2534                         vlr->v1= v1; vlr->v2= v2; vlr->v3= v3; vlr->v4= v4;
2535                         
2536                         normal_quad_v3( n1,vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co);
2537                         
2538                         VECCOPY(vlr->n, n1);
2539                         
2540                         vlr->mat= matar[ dl->col];
2541                         vlr->ec= ME_V1V2+ME_V2V3;
2542                         vlr->flag= dl->rt;
2543                         if( (cu->flag & CU_NOPUNOFLIP) ) {
2544                                 vlr->flag |= R_NOPUNOFLIP;
2545                         }
2546                         
2547                         add_v3_v3v3(v1->n, v1->n, n1);
2548                         add_v3_v3v3(v2->n, v2->n, n1);
2549                         add_v3_v3v3(v3->n, v3->n, n1);
2550                         add_v3_v3v3(v4->n, v4->n, n1);
2551                         
2552                         p1++; p2++; p3++; p4++;
2553                 }
2554         }       
2555         /* fix normals for U resp. V cyclic faces */
2556         sizeu--; sizev--;  /* dec size for face array */
2557         if (dl->flag & DL_CYCL_V) {
2558                 
2559                 for (v = 0; v < sizev; v++)
2560                 {
2561                         /* optimize! :*/
2562                         vlr= RE_findOrAddVlak(obr, UVTOINDEX(sizeu - 1, v));
2563                         vlr1= RE_findOrAddVlak(obr, UVTOINDEX(0, v));
2564                         add_v3_v3v3(vlr1->v1->n, vlr1->v1->n, vlr->n);
2565                         add_v3_v3v3(vlr1->v2->n, vlr1->v2->n, vlr->n);
2566                         add_v3_v3v3(vlr->v3->n, vlr->v3->n, vlr1->n);
2567                         add_v3_v3v3(vlr->v4->n, vlr->v4->n, vlr1->n);
2568                 }
2569         }
2570         if (dl->flag & DL_CYCL_U) {
2571                 
2572                 for (u = 0; u < sizeu; u++)
2573                 {
2574                         /* optimize! :*/
2575                         vlr= RE_findOrAddVlak(obr, UVTOINDEX(u, 0));
2576                         vlr1= RE_findOrAddVlak(obr, UVTOINDEX(u, sizev-1));
2577                         add_v3_v3v3(vlr1->v2->n, vlr1->v2->n, vlr->n);
2578                         add_v3_v3v3(vlr1->v3->n, vlr1->v3->n, vlr->n);
2579                         add_v3_v3v3(vlr->v1->n, vlr->v1->n, vlr1->n);
2580                         add_v3_v3v3(vlr->v4->n, vlr->v4->n, vlr1->n);
2581                 }
2582         }
2583         /* last vertex is an extra case: 
2584                 
2585                 ^       ()----()----()----()
2586                 |       |     |     ||     |
2587                 u       |     |(0,n)||(0,0)|
2588                 |     |     ||     |
2589                 ()====()====[]====()
2590                 |     |     ||     |
2591                 |     |(m,n)||(m,0)|
2592                 |     |     ||     |
2593                 ()----()----()----()
2594                 v ->
2595                 
2596                 vertex [] is no longer shared, therefore distribute
2597                 normals of the surrounding faces to all of the duplicates of []
2598                 */
2599         
2600         if ((dl->flag & DL_CYCL_V) && (dl->flag & DL_CYCL_U))
2601         {
2602                 vlr= RE_findOrAddVlak(obr, UVTOINDEX(sizeu - 1, sizev - 1)); /* (m,n) */
2603                 vlr1= RE_findOrAddVlak(obr, UVTOINDEX(0,0));  /* (0,0) */
2604                 add_v3_v3v3(n1, vlr->n, vlr1->n);
2605                 vlr2= RE_findOrAddVlak(obr, UVTOINDEX(0, sizev-1)); /* (0,n) */
2606                 add_v3_v3v3(n1, n1, vlr2->n);
2607                 vlr3= RE_findOrAddVlak(obr, UVTOINDEX(sizeu-1, 0)); /* (m,0) */
2608                 add_v3_v3v3(n1, n1, vlr3->n);
2609                 VECCOPY(vlr->v3->n, n1);
2610                 VECCOPY(vlr1->v1->n, n1);
2611                 VECCOPY(vlr2->v2->n, n1);
2612                 VECCOPY(vlr3->v4->n, n1);
2613         }
2614         for(a = startvert; a < obr->totvert; a++) {
2615                 ver= RE_findOrAddVert(obr, a);
2616                 normalize_v3(ver->n);
2617         }
2618         
2619         
2620         return orcoret;
2621 }
2622
2623 static void init_render_dm(DerivedMesh *dm, Render *re, ObjectRen *obr,
2624         int timeoffset, float *orco, float mat[4][4])
2625 {
2626         Object *ob= obr->ob;
2627         int a, a1, end, totvert, vertofs;
2628         VertRen *ver;
2629         VlakRen *vlr;
2630         Curve *cu= NULL;
2631         MVert *mvert = NULL;
2632         MFace *mface;
2633         Material *ma;
2634
2635         mvert= dm->getVertArray(dm);
2636         totvert= dm->getNumVerts(dm);
2637
2638         if ELEM(ob->type, OB_FONT, OB_CURVE) {
2639                 cu= ob->data;
2640         }
2641
2642         for(a=0; a<totvert; a++, mvert++) {
2643                 ver= RE_findOrAddVert(obr, obr->totvert++);
2644                 VECCOPY(ver->co, mvert->co);
2645                 mul_m4_v3(mat, ver->co);
2646
2647                 if(orco) {
2648                         ver->orco= orco;
2649                         orco+=3;
2650                 }
2651         }
2652
2653         if(!timeoffset) {
2654                 /* store customdata names, because DerivedMesh is freed */
2655                 RE_set_customdata_names(obr, &dm->faceData);
2656
2657                 /* still to do for keys: the correct local texture coordinate */
2658
2659                 /* faces in order of color blocks */
2660                 vertofs= obr->totvert - totvert;
2661                 for(a1=0; (a1<ob->totcol || (a1==0 && ob->totcol==0)); a1++) {
2662
2663                         ma= give_render_material(re, ob, a1+1);
2664                         end= dm->getNumFaces(dm);
2665                         mface= dm->getFaceArray(dm);
2666
2667                         for(a=0; a<end; a++, mface++) {
2668                                 int v1, v2, v3, v4, flag;
2669
2670                                 if( mface->mat_nr==a1 ) {
2671                                         float len;
2672
2673                                         v1= mface->v1;
2674                                         v2= mface->v2;
2675                                         v3= mface->v3;
2676                                         v4= mface->v4;
2677                                         flag= mface->flag & ME_SMOOTH;
2678
2679                                         vlr= RE_findOrAddVlak(obr, obr->totvlak++);
2680                                         vlr->v1= RE_findOrAddVert(obr, vertofs+v1);
2681                                         vlr->v2= RE_findOrAddVert(obr, vertofs+v2);
2682                                         vlr->v3= RE_findOrAddVert(obr, vertofs+v3);
2683                                         if(v4) vlr->v4= RE_findOrAddVert(obr, vertofs+v4);
2684                                         else vlr->v4= 0;
2685
2686                                         /* render normals are inverted in render */
2687                                         if(vlr->v4)
2688                                                 len= normal_quad_v3( vlr->n,vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co);
2689                                         else
2690                                                 len= normal_tri_v3( vlr->n,vlr->v3->co, vlr->v2->co, vlr->v1->co);
2691
2692                                         vlr->mat= ma;
2693                                         vlr->flag= flag;
2694                                         if(cu &&(cu->flag & ME_NOPUNOFLIP)) {
2695                                                 vlr->flag |= R_NOPUNOFLIP;
2696                                         }
2697                                         vlr->ec= 0; /* mesh edges rendered separately */
2698
2699                                         if(len==0) obr->totvlak--;
2700                                         else {
2701                                                 CustomDataLayer *layer;
2702                                                 MTFace *mtface, *mtf;
2703                                                 MCol *mcol, *mc;
2704                                                 int index, mtfn= 0, mcn= 0;
2705                                                 char *name;
2706
2707                                                 for(index=0; index<dm->faceData.totlayer; index++) {
2708                                                         layer= &dm->faceData.layers[index];
2709                                                         name= layer->name;
2710
2711                                                         if(layer->type == CD_MTFACE && mtfn < MAX_MTFACE) {
2712                                                                 mtf= RE_vlakren_get_tface(obr, vlr, mtfn++, &name, 1);
2713                                                                 mtface= (MTFace*)layer->data;
2714                                                                 *mtf= mtface[a];
2715                                                         }
2716                                                         else if(layer->type == CD_MCOL && mcn < MAX_MCOL) {
2717                                                                 mc= RE_vlakren_get_mcol(obr, vlr, mcn++, &name, 1);
2718                                                                 mcol= (MCol*)layer->data;
2719                                                                 memcpy(mc, &mcol[a*4], sizeof(MCol)*4);
2720                                                         }
2721                                                 }
2722                                         }
2723                                 }
2724                         }
2725                 }
2726
2727                 /* Normals */
2728                 calc_vertexnormals(re, obr, 0, 0);
2729         }
2730
2731 }
2732
2733 static void init_render_surf(Render *re, ObjectRen *obr, int timeoffset)
2734 {
2735         Object *ob= obr->ob;
2736         Nurb *nu=0;
2737         Curve *cu;
2738         ListBase displist= {NULL, NULL};
2739         DispList *dl;
2740         Material **matar;
2741         float *orco=NULL, *orcobase=NULL, mat[4][4];
2742         int a, totmat, need_orco=0;
2743         DerivedMesh *dm= NULL;
2744
2745         cu= ob->data;
2746         nu= cu->nurb.first;
2747         if(nu==0) return;
2748
2749         mul_m4_m4m4(mat, ob->obmat, re->viewmat);
2750         invert_m4_m4(ob->imat, mat);
2751
2752         /* material array */
2753         totmat= ob->totcol+1;
2754         matar= MEM_callocN(sizeof(Material*)*totmat, "init_render_surf matar");
2755
2756         for(a=0; a<totmat; a++) {
2757                 matar[a]= give_render_material(re, ob, a+1);
2758
2759                 if(matar[a] && matar[a]->texco & TEXCO_ORCO)
2760                         need_orco= 1;
2761         }
2762
2763         if(ob->parent && (ob->parent->type==OB_LATTICE)) need_orco= 1;
2764
2765         makeDispListSurf(re->scene, ob, &displist, &dm, 1, 0);
2766
2767         if (dm) {
2768                 if(need_orco) {
2769                         orco= makeOrcoDispList(re->scene, ob, dm, 1);
2770                         if(orco) {
2771                                 set_object_orco(re, ob, orco);
2772                         }
2773                 }
2774
2775                 init_render_dm(dm, re, obr, timeoffset, orco, mat);
2776                 dm->release(dm);
2777         } else {
2778                 if(need_orco) {
2779                         orcobase= orco= get_object_orco(re, ob);
2780                 }
2781
2782                 /* walk along displaylist and create rendervertices/-faces */
2783                 for(dl=displist.first; dl; dl=dl->next) {
2784                         /* watch out: u ^= y, v ^= x !! */
2785                         if(dl->type==DL_SURF)
2786                                 orco+= 3*dl_surf_to_renderdata(obr, dl, matar, orco, mat);
2787                 }
2788         }
2789
2790         freedisplist(&displist);
2791
2792         MEM_freeN(matar);
2793 }
2794
2795 static void init_render_curve(Render *re, ObjectRen *obr, int timeoffset)
2796 {
2797         Object *ob= obr->ob;
2798         Curve *cu;
2799         VertRen *ver;
2800         VlakRen *vlr;
2801         DispList *dl;
2802         DerivedMesh *dm = NULL;
2803         ListBase disp={NULL, NULL};
2804         Material **matar;
2805         float len, *data, *fp, *orco=NULL, *orcobase= NULL;
2806         float n[3], mat[4][4];
2807         int nr, startvert, startvlak, a, b;
2808         int frontside, need_orco=0, totmat;
2809
2810         cu= ob->data;
2811         if(ob->type==OB_FONT && cu->str==NULL) return;
2812         else if(ob->type==OB_CURVE && cu->nurb.first==NULL) return;
2813
2814         makeDispListCurveTypes_forRender(re->scene, ob, &disp, &dm, 0);
2815         dl= disp.first;
2816         if(dl==NULL) return;
2817         
2818         mul_m4_m4m4(mat, ob->obmat, re->viewmat);
2819         invert_m4_m4(ob->imat, mat);
2820
2821         /* material array */
2822         totmat= ob->totcol+1;
2823         matar= MEM_callocN(sizeof(Material*)*totmat, "init_render_surf matar");
2824
2825         for(a=0; a<totmat; a++) {
2826                 matar[a]= give_render_material(re, ob, a+1);
2827
2828                 if(matar[a] && matar[a]->texco & TEXCO_ORCO)
2829                         need_orco= 1;
2830         }
2831
2832         if (dm) {
2833                 if(need_orco) {
2834                         orco= makeOrcoDispList(re->scene, ob, dm, 1);
2835                         if(orco) {
2836                                 set_object_orco(re, ob, orco);
2837                         }
2838                 }
2839
2840                 init_render_dm(dm, re, obr, timeoffset, orco, mat);
2841                 dm->release(dm);
2842         } else {
2843                 if(need_orco) {
2844                   orcobase=orco= get_object_orco(re, ob);
2845                 }
2846
2847                 while(dl) {
2848                         if(dl->type==DL_INDEX3) {
2849                                 int *index;
2850
2851                                 startvert= obr->totvert;
2852                                 data= dl->verts;
2853
2854                                 n[0]= ob->imat[0][2];
2855                                 n[1]= ob->imat[1][2];
2856                                 n[2]= ob->imat[2][2];
2857                                 normalize_v3(n);
2858