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