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