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