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