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