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