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