soc-2008-mxcurioni: merged changes to revision 23516
[blender.git] / release / scripts / io / engine_render_pov.py
1 import bpy
2
3 from math import atan, pi, degrees
4 import subprocess
5 import os
6 import sys
7 import time
8
9 import platform as pltfrm
10
11 if pltfrm.architecture()[0] == '64bit':
12         bitness = 64
13 else:
14         bitness = 32
15
16 def write_pov(filename, scene=None, info_callback = None):
17         file = open(filename, 'w')
18         
19         # Only for testing
20         if not scene:
21                 scene = bpy.data.scenes[0]
22         
23         render = scene.render_data
24         world = scene.world
25         
26         # --- taken from fbx exporter 
27         ## This was used to make V, but faster not to do all that
28         ##valid = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_,.()[]{}'
29         ##v = range(255)
30         ##for c in valid: v.remove(ord(c))
31         v = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,42,43,46,47,58,59,60,61,62,63,64,92,94,96,124,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254]
32         invalid = ''.join([chr(i) for i in v])
33         def cleanName(name):
34                 for ch in invalid:      name = name.replace(ch, '_')
35                 return name
36         del v
37         
38         # --- done with clean name.
39         
40         def uniqueName(name, nameSeq):
41                 
42                 if name not in nameSeq:
43                         return name
44                 
45                 name_orig = name
46                 i = 1
47                 while name in nameSeq:
48                         name = '%s_%.3d' % (name_orig, i)
49                         i+=1
50                 
51                 return name
52                 
53         
54         def writeMatrix(matrix):
55                 file.write('\tmatrix <%.6f, %.6f, %.6f,  %.6f, %.6f, %.6f,  %.6f, %.6f, %.6f,  %.6f, %.6f, %.6f>\n' %\
56                 (matrix[0][0], matrix[0][1], matrix[0][2],  matrix[1][0], matrix[1][1], matrix[1][2],  matrix[2][0], matrix[2][1], matrix[2][2],  matrix[3][0], matrix[3][1], matrix[3][2]) )
57         
58         def writeObjectMaterial(material):
59                 if material and material.transparency_method=='RAYTRACE':
60                         file.write('\tinterior { ior %.6f }\n' % material.raytrace_transparency.ior)
61                         
62                         # Other interior args
63                         # fade_distance 2
64                         # fade_power [Value]
65                         # fade_color
66                         
67                         # dispersion
68                         # dispersion_samples
69         
70         materialNames = {}
71         DEF_MAT_NAME = 'Default'
72         def writeMaterial(material):
73                 # Assumes only called once on each material
74                 
75                 if material:
76                         name_orig = material.name
77                 else:
78                         name_orig = DEF_MAT_NAME
79                 
80                 name = materialNames[name_orig] = uniqueName(cleanName(name_orig), materialNames)
81                 
82                 file.write('#declare %s = finish {\n' % name)
83                 
84                 if material:
85                         file.write('\tdiffuse %.3g\n' % material.diffuse_intensity)
86                         file.write('\tspecular %.3g\n' % material.specular_intensity)
87                         
88                         file.write('\tambient %.3g\n' % material.ambient)
89                         #file.write('\tambient rgb <%.3g, %.3g, %.3g>\n' % tuple([c*material.ambient for c in world.ambient_color])) # povray blends the global value
90                         
91                         # map hardness between 0.0 and 1.0
92                         roughness = ((1.0 - ((material.specular_hardness-1.0)/510.0)))
93                         # scale from 0.0 to 0.1
94                         roughness *= 0.1
95                         # add a small value because 0.0 is invalid
96                         roughness += (1/511.0)
97                         
98                         file.write('\troughness %.3g\n' % roughness)
99                         
100                         # 'phong 70.0 '
101                         
102                         if material.raytrace_mirror.enabled:
103                                 raytrace_mirror= material.raytrace_mirror
104                                 if raytrace_mirror.reflect_factor:
105                                         file.write('\treflection {\n')
106                                         file.write('\t\trgb <%.3g, %.3g, %.3g>' % tuple(material.mirror_color))
107                                         file.write('\t\tfresnel 1 falloff %.3g exponent %.3g metallic %.3g} ' % (raytrace_mirror.fresnel, raytrace_mirror.fresnel_factor, raytrace_mirror.reflect_factor))
108                 
109                 else:
110                         file.write('\tdiffuse 0.8\n')
111                         file.write('\tspecular 0.2\n')
112                         
113
114                 # This is written into the object
115                 '''
116                 if material and material.transparency_method=='RAYTRACE':
117                         'interior { ior %.3g} ' % material.raytrace_transparency.ior
118                 '''
119                 
120                 #file.write('\t\t\tcrand 1.0\n') # Sand granyness
121                 #file.write('\t\t\tmetallic %.6f\n' % material.spec)
122                 #file.write('\t\t\tphong %.6f\n' % material.spec)
123                 #file.write('\t\t\tphong_size %.6f\n' % material.spec)
124                 #file.write('\t\t\tbrilliance %.6f ' % (material.specular_hardness/256.0) # Like hardness
125                 
126                 file.write('}\n')
127         
128         def exportCamera():
129                 camera = scene.camera
130                 matrix = camera.matrix
131                 
132                 # compute resolution
133                 Qsize=float(render.resolution_x)/float(render.resolution_y)
134                 
135                 file.write('camera {\n')
136                 file.write('\tlocation  <0, 0, 0>\n')
137                 file.write('\tlook_at  <0, 0, -1>\n')
138                 file.write('\tright <%s, 0, 0>\n' % -Qsize)
139                 file.write('\tup <0, 1, 0>\n')
140                 file.write('\tangle  %f \n' % (360.0*atan(16.0/camera.data.lens)/pi))
141                 
142                 file.write('\trotate  <%.6f, %.6f, %.6f>\n' % tuple([degrees(e) for e in matrix.rotationPart().toEuler()]))
143                 file.write('\ttranslate <%.6f, %.6f, %.6f>\n' % (matrix[3][0], matrix[3][1], matrix[3][2]))
144                 file.write('}\n')
145
146         def exportLamps(lamps):
147                 # Get all lamps
148                 for ob in lamps:
149                         lamp = ob.data
150                         
151                         matrix = ob.matrix
152                         
153                         color = tuple([c * lamp.energy for c in lamp.color]) # Colour is modified by energy
154                         
155                         file.write('light_source {\n')
156                         file.write('\t< 0,0,0 >\n')
157                         file.write('\tcolor rgb<%.3g, %.3g, %.3g>\n' % color)
158                         
159                         if lamp.type == 'POINT': # Point Lamp 
160                                 pass
161                         elif lamp.type == 'SPOT': # Spot
162                                 file.write('\tspotlight\n')
163                                 
164                                 # Falloff is the main radius from the centre line
165                                 file.write('\tfalloff %.2f\n' % (lamp.spot_size/2.0) ) # 1 TO 179 FOR BOTH
166                                 file.write('\tradius %.6f\n' % ((lamp.spot_size/2.0) * (1-lamp.spot_blend)) ) 
167                                 
168                                 # Blender does not have a tightness equivilent, 0 is most like blender default.
169                                 file.write('\ttightness 0\n') # 0:10f
170                                 
171                                 file.write('\tpoint_at  <0, 0, -1>\n')
172                         elif lamp.type == 'SUN':
173                                 file.write('\tparallel\n')
174                                 file.write('\tpoint_at  <0, 0, -1>\n') # *must* be after 'parallel'
175                                 
176                         elif lamp.type == 'AREA':
177                                 
178                                 size_x = lamp.size
179                                 samples_x = lamp.shadow_ray_samples_x
180                                 if lamp.shape == 'SQUARE':
181                                         size_y = size_x
182                                         samples_y = samples_x
183                                 else:
184                                         size_y = lamp.size_y
185                                         samples_y = lamp.shadow_ray_samples_y
186
187                                 file.write('\tarea_light <%d,0,0>,<0,0,%d> %d, %d\n' % (size_x, size_y, samples_x, samples_y))
188                                 if lamp.shadow_ray_sampling_method == 'CONSTANT_JITTERED':
189                                         if lamp.jitter:
190                                                 file.write('\tjitter\n')
191                                 else:
192                                         file.write('\tadaptive 1\n')
193                                         file.write('\tjitter\n')
194                         
195                         if lamp.shadow_method == 'NOSHADOW':
196                                 file.write('\tshadowless\n')    
197                         
198                         file.write('\tfade_distance %.6f\n' % lamp.distance)
199                         file.write('\tfade_power %d\n' % 1) # Could use blenders lamp quad?
200                         writeMatrix(matrix)
201                         
202                         file.write('}\n')
203         
204         def exportMeta(metas):
205                 
206                 # TODO - blenders 'motherball' naming is not supported.
207                 
208                 for ob in metas:
209                         meta = ob.data
210                         
211                         file.write('blob {\n')
212                         file.write('\t\tthreshold %.4g\n' % meta.threshold)
213                         
214                         try:
215                                 material= meta.materials[0] # lame! - blender cant do enything else.
216                         except:
217                                 material= None
218                         
219                         for elem in meta.elements:
220                                 
221                                 if elem.type not in ('BALL', 'ELLIPSOID'):
222                                         continue # Not supported
223                                 
224                                 loc = elem.location
225                                 
226                                 stiffness= elem.stiffness
227                                 if elem.negative:
228                                         stiffness = -stiffness
229                                 
230                                 if elem.type == 'BALL':
231                                         
232                                         file.write('\tsphere { <%.6g, %.6g, %.6g>, %.4g, %.4g ' % (loc.x, loc.y, loc.z, elem.radius, stiffness))
233                                         
234                                         # After this wecould do something simple like...
235                                         #       "pigment {Blue} }"
236                                         # except we'll write the color
237                                 
238                                 elif elem.type == 'ELLIPSOID':
239                                         # location is modified by scale
240                                         file.write('\tsphere { <%.6g, %.6g, %.6g>, %.4g, %.4g ' % (loc.x/elem.size_x, loc.y/elem.size_y, loc.z/elem.size_z, elem.radius, stiffness))
241                                         file.write(     'scale <%.6g, %.6g, %.6g> ' % (elem.size_x, elem.size_y, elem.size_z))
242                                 
243                                 if material:
244                                         diffuse_color = material.diffuse_color
245                                         
246                                         if material.transparency and material.transparency_method=='RAYTRACE':  trans = 1-material.raytrace_transparency.filter
247                                         else:                                                                                                                                   trans = 0.0
248                                         
249                                         file.write(
250                                                 'pigment {rgbft<%.3g, %.3g, %.3g, %.3g, %.3g>} finish {%s} }\n' % \
251                                                 (diffuse_color[0], diffuse_color[1], diffuse_color[2], 1-material.alpha, trans, materialNames[material.name])
252                                         )
253                                         
254                                 else:
255                                         file.write('pigment {rgb<1 1 1>} finish {%s} }\n' % DEF_MAT_NAME)               # Write the finish last.
256                         
257                         writeObjectMaterial(material)
258
259                         writeMatrix(ob.matrix)
260                         
261                         file.write('}\n')
262
263         def exportMeshs(sel):
264                 
265                 ob_num = 0
266                 
267                 for ob in sel:
268                         ob_num+= 1
269                         
270                         if ob.type in ('LAMP', 'CAMERA', 'EMPTY', 'META'):
271                                 continue
272                         
273                         me = ob.data
274                         me_materials= me.materials
275                         
276                         me = ob.create_mesh(True, 'RENDER')
277                         
278                         if not me:
279                                 continue
280                         
281                         if info_callback:
282                                 info_callback('Object %2.d of %2.d (%s)' % (ob_num, len(sel), ob.name))
283                         
284                         #if ob.type!='MESH':
285                         #       continue
286                         # me = ob.data
287                         
288                         matrix = ob.matrix
289                         try:    uv_layer = me.active_uv_texture.data
290                         except:uv_layer = None
291                                 
292                         try:    vcol_layer = me.active_vertex_color.data
293                         except:vcol_layer = None
294                         
295                         faces_verts = [f.verts for f in me.faces]
296                         faces_normals = [tuple(f.normal) for f in me.faces]
297                         verts_normals = [tuple(v.normal) for v in me.verts]
298                         
299                         # quads incur an extra face
300                         quadCount = len([f for f in faces_verts if len(f)==4])
301                         
302                         file.write('mesh2 {\n')
303                         file.write('\tvertex_vectors {\n')
304                         file.write('\t\t%s' % (len(me.verts))) # vert count
305                         for v in me.verts:
306                                 file.write(',\n\t\t<%.6f, %.6f, %.6f>' % tuple(v.co)) # vert count
307                         file.write('\n  }\n')
308                         
309                         
310                         # Build unique Normal list
311                         uniqueNormals = {}
312                         for fi, f in enumerate(me.faces):
313                                 fv = faces_verts[fi]
314                                 # [-1] is a dummy index, use a list so we can modify in place
315                                 if f.smooth: # Use vertex normals
316                                         for v in fv:
317                                                 key = verts_normals[v]
318                                                 uniqueNormals[key] = [-1]
319                                 else: # Use face normal
320                                         key = faces_normals[fi]
321                                         uniqueNormals[key] = [-1]
322                         
323                         file.write('\tnormal_vectors {\n')
324                         file.write('\t\t%d' % len(uniqueNormals)) # vert count
325                         idx = 0
326                         for no, index in uniqueNormals.items():
327                                 file.write(',\n\t\t<%.6f, %.6f, %.6f>' % no) # vert count
328                                 index[0] = idx
329                                 idx +=1
330                         file.write('\n  }\n')
331                         
332                         
333                         # Vertex colours
334                         vertCols = {} # Use for material colours also.
335                         
336                         if uv_layer:
337                                 # Generate unique UV's
338                                 uniqueUVs = {}
339                                 
340                                 for fi, uv in enumerate(uv_layer):
341                                         
342                                         if len(faces_verts[fi])==4:
343                                                 uvs = uv.uv1, uv.uv2, uv.uv3, uv.uv4
344                                         else:
345                                                 uvs = uv.uv1, uv.uv2, uv.uv3
346                                         
347                                         for uv in uvs:
348                                                 uniqueUVs[tuple(uv)] = [-1]
349                                 
350                                 file.write('\tuv_vectors {\n')
351                                 #print unique_uvs
352                                 file.write('\t\t%s' % (len(uniqueUVs))) # vert count
353                                 idx = 0
354                                 for uv, index in uniqueUVs.items():
355                                         file.write(',\n\t\t<%.6f, %.6f>' % uv)
356                                         index[0] = idx
357                                         idx +=1
358                                 '''
359                                 else:
360                                         # Just add 1 dummy vector, no real UV's
361                                         file.write('\t\t1') # vert count
362                                         file.write(',\n\t\t<0.0, 0.0>')
363                                 '''
364                                 file.write('\n  }\n')
365                         
366                         
367                         if me.vertex_colors:
368                                 
369                                 for fi, f in enumerate(me.faces):
370                                         material_index = f.material_index
371                                         material = me_materials[material_index]
372                                         
373                                         if material and material.vertex_color_paint:
374                                                 
375                                                 col = vcol_layer[fi]
376                                                 
377                                                 if len(faces_verts[fi])==4:
378                                                         cols = col.color1, col.color2, col.color3, col.color4
379                                                 else:
380                                                         cols = col.color1, col.color2, col.color3
381                                                 
382                                                 for col in cols:                                        
383                                                         key = col[0], col[1], col[2], material_index # Material index!
384                                                         vertCols[key] = [-1]
385                                                 
386                                         else:
387                                                 if material:
388                                                         diffuse_color = tuple(material.diffuse_color)
389                                                         key = diffuse_color[0], diffuse_color[1], diffuse_color[2], material_index
390                                                         vertCols[key] = [-1]
391                                                 
392                         
393                         else:
394                                 # No vertex colours, so write material colours as vertex colours
395                                 for i, material in enumerate(me_materials):
396                                         
397                                         if material:
398                                                 diffuse_color = tuple(material.diffuse_color)
399                                                 key = diffuse_color[0], diffuse_color[1], diffuse_color[2], i # i == f.mat
400                                                 vertCols[key] = [-1]
401                                 
402                         
403                         # Vert Colours
404                         file.write('\ttexture_list {\n')
405                         file.write('\t\t%s' % (len(vertCols))) # vert count
406                         idx=0
407                         for col, index in vertCols.items():
408                                 
409                                 if me_materials:
410                                         material = me_materials[col[3]]
411                                         material_finish = materialNames[material.name]
412                                         
413                                         if material.transparency and material.transparency_method=='RAYTRACE':  trans = 1-material.raytrace_transparency.filter
414                                         else:                                                                                                                                   trans = 0.0
415                                         
416                                 else:
417                                         material_finish = DEF_MAT_NAME # not working properly,
418                                         trans = 0.0
419                                 
420                                 #print material.apl
421                                 file.write(     ',\n\t\ttexture { pigment {rgbft<%.3g, %.3g, %.3g, %.3g, %.3g>} finish {%s}}' %
422                                                         (col[0], col[1], col[2], 1-material.alpha, trans, material_finish) )
423                                 
424                                 index[0] = idx
425                                 idx+=1
426                         
427                         file.write( '\n  }\n' )
428                         
429                         # Face indicies
430                         file.write('\tface_indices {\n')
431                         file.write('\t\t%d' % (len(me.faces) + quadCount)) # faces count
432                         for fi, f in enumerate(me.faces):
433                                 fv = faces_verts[fi]
434                                 material_index= f.material_index
435                                 if len(fv) == 4:        indicies = (0,1,2), (0,2,3)
436                                 else:                           indicies = ((0,1,2),)
437                                 
438                                 if vcol_layer:
439                                         col = vcol_layer[fi]
440                                         
441                                         if len(fv) == 4:
442                                                 cols = col.color1, col.color2, col.color3, col.color4
443                                         else:
444                                                 cols = col.color1, col.color2, col.color3
445                                 
446                                 
447                                 if not me_materials or me_materials[material_index] == None: # No materials
448                                         for i1, i2, i3 in indicies:
449                                                 file.write(',\n\t\t<%d,%d,%d>' % (fv[i1], fv[i2], fv[i3])) # vert count
450                                 else:
451                                         material = me_materials[material_index]
452                                         for i1, i2, i3 in indicies:
453                                                 if me.vertex_colors and material.vertex_color_paint:
454                                                         # Colour per vertex - vertex colour
455                                                         
456                                                         col1 = cols[i1]
457                                                         col2 = cols[i2]
458                                                         col3 = cols[i3]
459                                                 
460                                                         ci1 = vertCols[col1[0], col1[1], col1[2], material_index][0]
461                                                         ci2 = vertCols[col2[0], col2[1], col2[2], material_index][0]
462                                                         ci3 = vertCols[col3[0], col3[1], col3[2], material_index][0]
463                                                 else:
464                                                         # Colour per material - flat material colour
465                                                         diffuse_color= material.diffuse_color
466                                                         ci1 = ci2 = ci3 = vertCols[diffuse_color[0], diffuse_color[1], diffuse_color[2], f.material_index][0]
467                                                 
468                                                 file.write(',\n\t\t<%d,%d,%d>, %d,%d,%d' % (fv[i1], fv[i2], fv[i3], ci1, ci2, ci3)) # vert count
469                                         
470         
471                         file.write('\n  }\n')
472                         
473                         # normal_indices indicies
474                         file.write('\tnormal_indices {\n')
475                         file.write('\t\t%d' % (len(me.faces) + quadCount)) # faces count
476                         for fi, fv in enumerate(faces_verts):
477                                 
478                                 if len(fv) == 4:        indicies = (0,1,2), (0,2,3)
479                                 else:                           indicies = ((0,1,2),)
480                                 
481                                 for i1, i2, i3 in indicies:
482                                         if f.smooth:
483                                                 file.write(',\n\t\t<%d,%d,%d>' %\
484                                                 (uniqueNormals[verts_normals[fv[i1]]][0],\
485                                                  uniqueNormals[verts_normals[fv[i2]]][0],\
486                                                  uniqueNormals[verts_normals[fv[i3]]][0])) # vert count
487                                         else:
488                                                 idx = uniqueNormals[faces_normals[fi]][0]
489                                                 file.write(',\n\t\t<%d,%d,%d>' % (idx, idx, idx)) # vert count
490                                                 
491                         file.write('\n  }\n')
492                         
493                         if uv_layer:
494                                 file.write('\tuv_indices {\n')
495                                 file.write('\t\t%d' % (len(me.faces) + quadCount)) # faces count
496                                 for fi, fv in enumerate(faces_verts):
497                                         
498                                         if len(fv) == 4:        indicies = (0,1,2), (0,2,3)
499                                         else:                           indicies = ((0,1,2),)
500                                         
501                                         uv = uv_layer[fi]
502                                         if len(faces_verts[fi])==4:
503                                                 uvs = tuple(uv.uv1), tuple(uv.uv2), tuple(uv.uv3), tuple(uv.uv4)
504                                         else:
505                                                 uvs = tuple(uv.uv1), tuple(uv.uv2), tuple(uv.uv3)
506                                         
507                                         for i1, i2, i3 in indicies:
508                                                 file.write(',\n\t\t<%d,%d,%d>' %\
509                                                 (uniqueUVs[uvs[i1]][0],\
510                                                  uniqueUVs[uvs[i2]][0],\
511                                                  uniqueUVs[uvs[i2]][0])) # vert count
512                                 file.write('\n  }\n')
513                         
514                         if me.materials:
515                                 material = me.materials[0] # dodgy
516                                 writeObjectMaterial(material)
517                         
518                         writeMatrix(matrix)
519                         file.write('}\n')
520                         
521                         bpy.data.remove_mesh(me)
522         
523         def exportWorld(world):
524                 if not world:
525                         return
526                 
527                 mist = world.mist
528                 
529                 if mist.enabled:
530                         file.write('fog {\n')
531                         file.write('\tdistance %.6f\n' % mist.depth)
532                         file.write('\tcolor rgbt<%.3g, %.3g, %.3g, %.3g>\n' % (tuple(world.horizon_color) + (1-mist.intensity,)))
533                         #file.write('\tfog_offset %.6f\n' % mist.start)
534                         #file.write('\tfog_alt 5\n')
535                         #file.write('\tturbulence 0.2\n')
536                         #file.write('\tturb_depth 0.3\n')
537                         file.write('\tfog_type 1\n')
538                         file.write('}\n')
539         
540         def exportGlobalSettings(scene):
541                 
542                 file.write('global_settings {\n')
543
544                 if scene.pov_radio_enable:
545                         file.write('\tradiosity {\n')
546                         file.write("\t\tadc_bailout %.4g\n" % scene.pov_radio_adc_bailout)
547                         file.write("\t\talways_sample %d\n" % scene.pov_radio_always_sample)
548                         file.write("\t\tbrightness %.4g\n" % scene.pov_radio_brightness)
549                         file.write("\t\tcount %d\n" % scene.pov_radio_count)
550                         file.write("\t\terror_bound %.4g\n" % scene.pov_radio_error_bound)
551                         file.write("\t\tgray_threshold %.4g\n" % scene.pov_radio_gray_threshold)
552                         file.write("\t\tlow_error_factor %.4g\n" % scene.pov_radio_low_error_factor)
553                         file.write("\t\tmedia %d\n" % scene.pov_radio_media)
554                         file.write("\t\tminimum_reuse %.4g\n" % scene.pov_radio_minimum_reuse)
555                         file.write("\t\tnearest_count %d\n" % scene.pov_radio_nearest_count)
556                         file.write("\t\tnormal %d\n" % scene.pov_radio_normal)
557                         file.write("\t\trecursion_limit %d\n" % scene.pov_radio_recursion_limit)
558                         file.write('\t}\n')
559                 
560                 if world:
561                         file.write("\tambient_light rgb<%.3g, %.3g, %.3g>\n" % tuple(world.ambient_color))
562                 
563                 file.write('}\n')
564         
565         
566         # Convert all materials to strings we can access directly per vertex.
567         writeMaterial(None) # default material
568         
569         for material in bpy.data.materials:
570                 writeMaterial(material)
571         
572         exportCamera()
573         #exportMaterials()
574         sel = scene.objects
575         exportLamps([l for l in sel if l.type == 'LAMP'])
576         exportMeta([l for l in sel if l.type == 'META'])
577         exportMeshs(sel)
578         exportWorld(scene.world)
579         exportGlobalSettings(scene)
580         
581         file.close()
582
583 def write_pov_ini(filename_ini, filename_pov, filename_image):
584         scene = bpy.data.scenes[0]
585         render = scene.render_data
586         
587         x= int(render.resolution_x*render.resolution_percentage*0.01)
588         y= int(render.resolution_y*render.resolution_percentage*0.01)
589         
590         file = open(filename_ini, 'w')
591         
592         file.write('Input_File_Name="%s"\n' % filename_pov)
593         file.write('Output_File_Name="%s"\n' % filename_image)
594         
595         file.write('Width=%d\n' % x)
596         file.write('Height=%d\n' % y)
597         
598         # Needed for border render.
599         '''
600         file.write('Start_Column=%d\n' % part.x)
601         file.write('End_Column=%d\n' % (part.x+part.w))
602         
603         file.write('Start_Row=%d\n' % (part.y))
604         file.write('End_Row=%d\n' % (part.y+part.h))
605         '''
606         
607         file.write('Display=0\n')
608         file.write('Pause_When_Done=0\n')
609         file.write('Output_File_Type=T\n') # TGA, best progressive loading
610         file.write('Output_Alpha=1\n')
611         
612         if render.antialiasing: 
613                 aa_mapping = {'OVERSAMPLE_5':2, 'OVERSAMPLE_8':3, 'OVERSAMPLE_11':4, 'OVERSAMPLE_16':5} # method 1 assumed
614                 file.write('Antialias=1\n')
615                 file.write('Antialias_Depth=%d\n' % aa_mapping[render.antialiasing_samples])
616         else:
617                 file.write('Antialias=0\n')
618         
619         file.close()
620
621 # Radiosity panel, use in the scene for now.
622 FloatProperty= bpy.types.Scene.FloatProperty
623 IntProperty= bpy.types.Scene.IntProperty
624 BoolProperty= bpy.types.Scene.BoolProperty
625
626 # Not a real pov option, just to know if we should write
627 BoolProperty(   attr="pov_radio_enable",
628                                 name="Enable Radiosity",
629                                 description="Enable povrays radiosity calculation.",
630                                 default= False)
631 BoolProperty(   attr="pov_radio_display_advanced",
632                                 name="Advanced Options",
633                                 description="Show advanced options.",
634                                 default= False)
635
636 # Real pov options
637 FloatProperty(  attr="pov_radio_adc_bailout",
638                                 name="ADC Bailout",
639                                 description="The adc_bailout for radiosity rays. Use adc_bailout = 0.01 / brightest_ambient_object for good results.",
640                                 min=0.0, max=1000.0, soft_min=0.0, soft_max=1.0, default= 0.01)
641
642 BoolProperty(   attr="pov_radio_always_sample",
643                                 name="Always Sample",
644                                 description="Only use the data from the pretrace step and not gather any new samples during the final radiosity pass..",
645                                 default= True)
646
647 FloatProperty(  attr="pov_radio_brightness",
648                                 name="Brightness",
649                                 description="Ammount objects are brightened before being returned upwards to the rest of the system.",
650                                 min=0.0, max=1000.0, soft_min=0.0, soft_max=10.0, default= 1.0)
651
652 IntProperty(    attr="pov_radio_count",
653                                 name="Ray Count",
654                                 description="number of rays that are sent out whenever a new radiosity value has to be calculated.",
655                                 min=1, max=1600, default= 35)
656
657 FloatProperty(  attr="pov_radio_error_bound",
658                                 name="Error Bound",
659                                 description="one of the two main speed/quality tuning values, lower values are more accurate.",
660                                 min=0.0, max=1000.0, soft_min=0.1, soft_max=10.0, default= 1.8)
661
662 FloatProperty(  attr="pov_radio_gray_threshold",
663                                 name="Gray Threshold",
664                                 description="one of the two main speed/quality tuning values, lower values are more accurate.",
665                                 min=0.0, max=1.0, soft_min=0, soft_max=1, default= 0.0)
666                                                                 
667 FloatProperty(  attr="pov_radio_low_error_factor",
668                                 name="Low Error Factor",
669                                 description="If you calculate just enough samples, but no more, you will get an image which has slightly blotchy lighting.",
670                                 min=0.0, max=1.0, soft_min=0.0, soft_max=1.0, default= 0.5)
671
672 # max_sample - not available yet
673 BoolProperty(   attr="pov_radio_media", 
674                                 name="Media",
675                                 description="Radiosity estimation can be affected by media.",
676                                 default= False)
677
678 FloatProperty(  attr="pov_radio_minimum_reuse",
679                                 name="Minimum Reuse",
680                                 description="Fraction of the screen width which sets the minimum radius of reuse for each sample point (At values higher than 2% expect errors).",
681                                 min=0.0, max=1.0, soft_min=0.1, soft_max=0.1, default= 0.015)
682                                 
683 IntProperty(    attr="pov_radio_nearest_count",
684                                 name="Nearest Count",
685                                 description="Number of old ambient values blended together to create a new interpolated value.",
686                                 min=1, max=20, default= 5)
687                                 
688 BoolProperty(   attr="pov_radio_normal",
689                                 name="Normals",
690                                 description="Radiosity estimation can be affected by normals.",
691                                 default= False)
692
693 IntProperty(    attr="pov_radio_recursion_limit",
694                                 name="Recursion Limit",
695                                 description="how many recursion levels are used to calculate the diffuse inter-reflection.",
696                                 min=1, max=20, default= 3)
697         
698
699 class PovrayRender(bpy.types.RenderEngine):
700         __idname__ = 'POVRAY_RENDER'
701         __label__ = "Povray"
702         DELAY = 0.02
703         
704         def _export(self, scene):
705                 import tempfile
706                 
707                 self.temp_file_in = tempfile.mktemp(suffix='.pov')
708                 self.temp_file_out = tempfile.mktemp(suffix='.tga')
709                 self.temp_file_ini = tempfile.mktemp(suffix='.ini')
710                 '''
711                 self.temp_file_in = '/test.pov'
712                 self.temp_file_out = '/test.tga'
713                 self.temp_file_ini = '/test.ini'
714                 '''
715                 
716                 def info_callback(txt):
717                         self.update_stats("", "POVRAY: " + txt)
718                         
719                 write_pov(self.temp_file_in, scene, info_callback)
720                 
721         def _render(self):
722                 
723                 try:            os.remove(self.temp_file_out) # so as not to load the old file
724                 except: pass
725                 
726                 write_pov_ini(self.temp_file_ini, self.temp_file_in, self.temp_file_out)
727                 
728                 print ("***-STARTING-***")
729                 
730                 pov_binary = "povray"
731                 
732                 if sys.platform=='win32':
733                         import winreg
734                         regKey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Software\\POV-Ray\\v3.6\\Windows')
735                         
736                         if bitness == 64:
737                                 pov_binary = winreg.QueryValueEx(regKey, 'Home')[0] + '\\bin\\pvengine64'
738                         else:
739                                 pov_binary = winreg.QueryValueEx(regKey, 'Home')[0] + '\\bin\\pvengine'
740                         
741                 if 1:
742                         self.process = subprocess.Popen([pov_binary, self.temp_file_ini]) # stdout=subprocess.PIPE, stderr=subprocess.PIPE
743                 else:
744                         # This works too but means we have to wait until its done
745                         os.system('%s %s' % (pov_binary, self.temp_file_ini))
746                 
747                 print ("***-DONE-***")
748         
749         def _cleanup(self):
750                 for f in (self.temp_file_in, self.temp_file_ini, self.temp_file_out):
751                         try:            os.remove(f)
752                         except: pass
753                 
754                 self.update_stats("", "")
755         
756         def render(self, scene):
757                 
758                 self.update_stats("", "POVRAY: Exporting data from Blender")
759                 self._export(scene)
760                 self.update_stats("", "POVRAY: Parsing File")
761                 self._render()
762                 
763                 r = scene.render_data
764                 
765                 # compute resolution
766                 x= int(r.resolution_x*r.resolution_percentage*0.01)
767                 y= int(r.resolution_y*r.resolution_percentage*0.01)
768
769                 # Wait for the file to be created
770                 while not os.path.exists(self.temp_file_out):
771                         if self.test_break():
772                                 try:            self.process.terminate()
773                                 except: pass
774                                 break
775                         
776                         if self.process.poll() != None:
777                                 self.update_stats("", "POVRAY: Failed")
778                                 break
779                         
780                         time.sleep(self.DELAY)
781                 
782                 if os.path.exists(self.temp_file_out):
783                         
784                         self.update_stats("", "POVRAY: Rendering")
785                         
786                         prev_size = -1
787                         
788                         def update_image():
789                                 result = self.begin_result(0, 0, x, y)
790                                 lay = result.layers[0]
791                                 # possible the image wont load early on.
792                                 try:            lay.load_from_file(self.temp_file_out)
793                                 except: pass
794                                 self.end_result(result)
795                         
796                         # Update while povray renders
797                         while True:
798                                 
799                                 # test if povray exists
800                                 if self.process.poll() != None:
801                                         update_image();
802                                         break
803                                 
804                                 # user exit
805                                 if self.test_break():
806                                         try:            self.process.terminate()
807                                         except: pass
808                                         
809                                         break
810                                 
811                                 # Would be nice to redirect the output
812                                 # stdout_value, stderr_value = self.process.communicate() # locks
813                                 
814                                 
815                                 # check if the file updated
816                                 new_size = os.path.getsize(self.temp_file_out)
817                                 
818                                 if new_size != prev_size:
819                                         update_image()
820                                         prev_size = new_size
821                                 
822                                 time.sleep(self.DELAY)
823                 
824                 self._cleanup()
825
826 bpy.types.register(PovrayRender)
827
828 # Use some of the existing buttons.
829 import buttons_scene
830 buttons_scene.SCENE_PT_render.COMPAT_ENGINES.add('POVRAY_RENDER')
831 buttons_scene.SCENE_PT_dimensions.COMPAT_ENGINES.add('POVRAY_RENDER')
832 buttons_scene.SCENE_PT_antialiasing.COMPAT_ENGINES.add('POVRAY_RENDER')
833 buttons_scene.SCENE_PT_output.COMPAT_ENGINES.add('POVRAY_RENDER')
834 del buttons_scene
835
836 # Use only a subset of the world panels
837 import buttons_world
838 buttons_world.WORLD_PT_preview.COMPAT_ENGINES.add('POVRAY_RENDER')
839 buttons_world.WORLD_PT_context_world.COMPAT_ENGINES.add('POVRAY_RENDER')
840 buttons_world.WORLD_PT_world.COMPAT_ENGINES.add('POVRAY_RENDER')
841 buttons_world.WORLD_PT_mist.COMPAT_ENGINES.add('POVRAY_RENDER')
842 del buttons_world
843
844 # Example of wrapping every class 'as is'
845 import buttons_material
846 for member in dir(buttons_material):
847         subclass = getattr(buttons_material, member)
848         try:            subclass.COMPAT_ENGINES.add('POVRAY_RENDER')
849         except: pass
850 del buttons_material
851
852 class RenderButtonsPanel(bpy.types.Panel):
853         __space_type__ = 'PROPERTIES'
854         __region_type__ = 'WINDOW'
855         __context__ = "scene"
856         # COMPAT_ENGINES must be defined in each subclass, external engines can add themselves here
857         
858         def poll(self, context):
859                 rd = context.scene.render_data
860                 return (rd.use_game_engine==False) and (rd.engine in self.COMPAT_ENGINES)
861
862 class SCENE_PT_povray_radiosity(RenderButtonsPanel):
863         __label__ = "Radiosity"
864         COMPAT_ENGINES = set(['POVRAY_RENDER'])
865
866         def draw_header(self, context):
867                 scene = context.scene
868
869                 self.layout.itemR(scene, "pov_radio_enable", text="")
870
871         def draw(self, context):
872                 layout = self.layout
873
874                 scene = context.scene
875                 rd = scene.render_data
876                 
877                 layout.active = scene.pov_radio_enable
878                 
879                 split = layout.split()
880                 
881                 col = split.column()
882                 col.itemR(scene, "pov_radio_count", text="Rays")
883                 col.itemR(scene, "pov_radio_recursion_limit", text="Recursions")
884                 col = split.column()
885                 col.itemR(scene, "pov_radio_error_bound", text="Error")
886                 
887                 layout.itemR(scene, "pov_radio_display_advanced")
888                 
889                 if scene.pov_radio_display_advanced:
890                         split = layout.split()
891                 
892                         col = split.column()
893                         col.itemR(scene, "pov_radio_adc_bailout", slider=True)
894                         col.itemR(scene, "pov_radio_gray_threshold", slider=True)
895                         col.itemR(scene, "pov_radio_low_error_factor", slider=True)
896
897                         col = split.column()
898                         col.itemR(scene, "pov_radio_brightness")
899                         col.itemR(scene, "pov_radio_minimum_reuse", text="Min Reuse")
900                         col.itemR(scene, "pov_radio_nearest_count")
901
902                         split = layout.split()
903                 
904                         col = split.column()
905                         col.itemL(text="Estimation Influence:")
906                         col.itemR(scene, "pov_radio_media")
907                         col.itemR(scene, "pov_radio_normal")
908                         
909                         col = split.column()
910                         col.itemR(scene, "pov_radio_always_sample")
911
912 bpy.types.register(SCENE_PT_povray_radiosity)