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