Welcome to mirror list, hosted at ThFree Co, Russian Federation.

git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBrecht Van Lommel <brechtvanlommel@pandora.be>2008-11-13 00:16:53 +0300
committerBrecht Van Lommel <brechtvanlommel@pandora.be>2008-11-13 00:16:53 +0300
commitbdfe7d89e2f1292644577972c716931b4ce3c6c3 (patch)
treed00eb50b749cb001e2b08272c91791e66740b05d /source/blender
parent78a1c27c4a6abe0ed31ca93ad21910f3df04da56 (diff)
parent7e4db234cee71ead34ee81a12e27da4bd548eb4b (diff)
Merge of trunk into blender 2.5:
svn merge https://svn.blender.org/svnroot/bf-blender/trunk/blender -r12987:17416 Issues: * GHOST/X11 had conflicting changes. Some code was added in 2.5, which was later added in trunk also, but reverted partially, specifically revision 16683. I have left out this reversion in the 2.5 branch since I think it is needed there. http://projects.blender.org/plugins/scmsvn/viewcvs.php?view=rev&root=bf-blender&revision=16683 * Scons had various conflicting changes, I decided to go with trunk version for everything except priorities and some library renaming. * In creator.c, there were various fixes and fixes for fixes related to the -w -W and -p options. In 2.5 -w and -W is not coded yet, and -p is done differently. Since this is changed so much, and I don't think those fixes would be needed in 2.5, I've left them out. * Also in creator.c: there was code for a python bugfix where the screen was not initialized when running with -P. The code that initializes the screen there I had to disable, that can't work in 2.5 anymore but left it commented as a reminder. Further I had to disable some new function calls. using src/ and python/, as was done already in this branch, disabled function calls: * bpath.c: error reporting * BME_conversions.c: editmesh conversion functions. * SHD_dynamic: disabled almost completely, there is no python/. * KX_PythonInit.cpp and Ketsji/ build files: Mathutils is not there, disabled. * text.c: clipboard copy call. * object.c: OB_SUPPORT_MATERIAL. * DerivedMesh.c and subsurf_ccg, stipple_quarttone. Still to be done: * Go over files and functions that were moved to a different location but could still use changes that were done in trunk.
Diffstat (limited to 'source/blender')
-rw-r--r--source/blender/CMakeLists.txt6
-rw-r--r--source/blender/Makefile5
-rw-r--r--source/blender/SConscript65
-rw-r--r--source/blender/avi/SConscript2
-rw-r--r--source/blender/avi/intern/avi.c192
-rw-r--r--source/blender/avi/intern/avirgb.c2
-rw-r--r--source/blender/avi/intern/endian.c4
-rw-r--r--source/blender/blenkernel/BKE_DerivedMesh.h72
-rw-r--r--source/blender/blenkernel/BKE_action.h14
-rw-r--r--source/blender/blenkernel/BKE_anim.h5
-rw-r--r--source/blender/blenkernel/BKE_armature.h2
-rw-r--r--source/blender/blenkernel/BKE_bmesh.h253
-rw-r--r--source/blender/blenkernel/BKE_bmeshCustomData.h108
-rw-r--r--source/blender/blenkernel/BKE_brush.h2
-rw-r--r--source/blender/blenkernel/BKE_bullet.h43
-rw-r--r--source/blender/blenkernel/BKE_bvhutils.h98
-rw-r--r--source/blender/blenkernel/BKE_cloth.h282
-rw-r--r--source/blender/blenkernel/BKE_collision.h150
-rw-r--r--source/blender/blenkernel/BKE_colortools.h1
-rw-r--r--source/blender/blenkernel/BKE_constraint.h10
-rw-r--r--source/blender/blenkernel/BKE_curve.h19
-rw-r--r--source/blender/blenkernel/BKE_customdata.h33
-rw-r--r--source/blender/blenkernel/BKE_deform.h4
-rw-r--r--source/blender/blenkernel/BKE_depsgraph.h2
-rw-r--r--source/blender/blenkernel/BKE_displist.h23
-rw-r--r--source/blender/blenkernel/BKE_effect.h14
-rw-r--r--source/blender/blenkernel/BKE_endian.h6
-rw-r--r--source/blender/blenkernel/BKE_fluidsim.h56
-rw-r--r--source/blender/blenkernel/BKE_font.h10
-rw-r--r--source/blender/blenkernel/BKE_global.h27
-rw-r--r--source/blender/blenkernel/BKE_group.h5
-rw-r--r--source/blender/blenkernel/BKE_idprop.h6
-rw-r--r--source/blender/blenkernel/BKE_image.h7
-rw-r--r--source/blender/blenkernel/BKE_ipo.h61
-rw-r--r--source/blender/blenkernel/BKE_key.h11
-rw-r--r--source/blender/blenkernel/BKE_lattice.h3
-rw-r--r--source/blender/blenkernel/BKE_main.h2
-rw-r--r--source/blender/blenkernel/BKE_mball.h7
-rw-r--r--source/blender/blenkernel/BKE_mesh.h7
-rw-r--r--source/blender/blenkernel/BKE_modifier.h2
-rw-r--r--source/blender/blenkernel/BKE_multires.h2
-rw-r--r--source/blender/blenkernel/BKE_node.h85
-rw-r--r--source/blender/blenkernel/BKE_object.h13
-rw-r--r--source/blender/blenkernel/BKE_particle.h39
-rw-r--r--source/blender/blenkernel/BKE_plugin_types.h5
-rw-r--r--source/blender/blenkernel/BKE_pointcache.h77
-rw-r--r--source/blender/blenkernel/BKE_property.h3
-rw-r--r--source/blender/blenkernel/BKE_scene.h11
-rw-r--r--source/blender/blenkernel/BKE_screen.h2
-rw-r--r--source/blender/blenkernel/BKE_sculpt.h26
-rw-r--r--source/blender/blenkernel/BKE_shrinkwrap.h150
-rw-r--r--source/blender/blenkernel/BKE_simple_deform.h39
-rw-r--r--source/blender/blenkernel/BKE_softbody.h8
-rw-r--r--source/blender/blenkernel/BKE_suggestions.h93
-rw-r--r--source/blender/blenkernel/BKE_text.h30
-rw-r--r--source/blender/blenkernel/BKE_texture.h3
-rw-r--r--source/blender/blenkernel/BKE_utildefines.h35
-rw-r--r--source/blender/blenkernel/BKE_writeffmpeg.h12
-rw-r--r--source/blender/blenkernel/BKE_writeframeserver.h2
-rw-r--r--source/blender/blenkernel/CMakeLists.txt16
-rw-r--r--source/blender/blenkernel/SConscript49
-rw-r--r--source/blender/blenkernel/depsgraph_private.h3
-rw-r--r--source/blender/blenkernel/intern/BME_Customdata.c199
-rw-r--r--source/blender/blenkernel/intern/BME_conversions.c646
-rw-r--r--source/blender/blenkernel/intern/BME_eulers.c977
-rw-r--r--source/blender/blenkernel/intern/BME_mesh.c285
-rw-r--r--source/blender/blenkernel/intern/BME_structure.c627
-rw-r--r--source/blender/blenkernel/intern/BME_tools.c1323
-rw-r--r--source/blender/blenkernel/intern/CCGSubSurf.c114
-rw-r--r--source/blender/blenkernel/intern/CCGSubSurf.h28
-rw-r--r--source/blender/blenkernel/intern/DerivedMesh.c1270
-rw-r--r--source/blender/blenkernel/intern/Makefile8
-rw-r--r--source/blender/blenkernel/intern/action.c200
-rw-r--r--source/blender/blenkernel/intern/anim.c552
-rw-r--r--source/blender/blenkernel/intern/armature.c244
-rw-r--r--source/blender/blenkernel/intern/blender.c76
-rw-r--r--source/blender/blenkernel/intern/bmesh_private.h70
-rw-r--r--source/blender/blenkernel/intern/brush.c24
-rw-r--r--source/blender/blenkernel/intern/bullet.c96
-rw-r--r--source/blender/blenkernel/intern/bvhutils.c577
-rw-r--r--source/blender/blenkernel/intern/cdderivedmesh.c165
-rw-r--r--source/blender/blenkernel/intern/cloth.c1290
-rw-r--r--source/blender/blenkernel/intern/collision.c1677
-rw-r--r--source/blender/blenkernel/intern/colortools.c57
-rw-r--r--source/blender/blenkernel/intern/constraint.c526
-rw-r--r--source/blender/blenkernel/intern/curve.c605
-rw-r--r--source/blender/blenkernel/intern/customdata.c432
-rw-r--r--source/blender/blenkernel/intern/deform.c25
-rw-r--r--source/blender/blenkernel/intern/depsgraph.c514
-rw-r--r--source/blender/blenkernel/intern/displist.c114
-rw-r--r--source/blender/blenkernel/intern/effect.c2107
-rw-r--r--source/blender/blenkernel/intern/exotic.c34
-rw-r--r--source/blender/blenkernel/intern/fluidsim.c660
-rw-r--r--source/blender/blenkernel/intern/font.c84
-rw-r--r--source/blender/blenkernel/intern/group.c75
-rw-r--r--source/blender/blenkernel/intern/icons.c17
-rw-r--r--source/blender/blenkernel/intern/idprop.c40
-rw-r--r--source/blender/blenkernel/intern/image.c588
-rw-r--r--source/blender/blenkernel/intern/implicit.c1709
-rw-r--r--source/blender/blenkernel/intern/ipo.c3733
-rw-r--r--source/blender/blenkernel/intern/key.c24
-rw-r--r--source/blender/blenkernel/intern/lattice.c61
-rw-r--r--source/blender/blenkernel/intern/library.c79
-rw-r--r--source/blender/blenkernel/intern/material.c29
-rw-r--r--source/blender/blenkernel/intern/mball.c198
-rw-r--r--source/blender/blenkernel/intern/mesh.c58
-rw-r--r--source/blender/blenkernel/intern/modifier.c4001
-rw-r--r--source/blender/blenkernel/intern/multires-firstlevel.c10
-rw-r--r--source/blender/blenkernel/intern/multires.c18
-rw-r--r--source/blender/blenkernel/intern/node.c579
-rw-r--r--source/blender/blenkernel/intern/object.c453
-rw-r--r--source/blender/blenkernel/intern/packedFile.c10
-rw-r--r--source/blender/blenkernel/intern/particle.c1482
-rw-r--r--source/blender/blenkernel/intern/particle_system.c2493
-rw-r--r--source/blender/blenkernel/intern/pointcache.c493
-rw-r--r--source/blender/blenkernel/intern/property.c16
-rw-r--r--source/blender/blenkernel/intern/sca.c16
-rw-r--r--source/blender/blenkernel/intern/scene.c139
-rw-r--r--source/blender/blenkernel/intern/screen.c4
-rw-r--r--source/blender/blenkernel/intern/script.c18
-rw-r--r--source/blender/blenkernel/intern/shrinkwrap.c599
-rw-r--r--source/blender/blenkernel/intern/simple_deform.c256
-rw-r--r--source/blender/blenkernel/intern/softbody.c2337
-rw-r--r--source/blender/blenkernel/intern/sound.c6
-rw-r--r--source/blender/blenkernel/intern/subsurf_ccg.c449
-rw-r--r--source/blender/blenkernel/intern/suggestions.c254
-rw-r--r--source/blender/blenkernel/intern/text.c610
-rw-r--r--source/blender/blenkernel/intern/texture.c77
-rw-r--r--source/blender/blenkernel/intern/world.c19
-rw-r--r--source/blender/blenkernel/intern/writeavi.c2
-rw-r--r--source/blender/blenkernel/intern/writeffmpeg.c136
-rw-r--r--source/blender/blenkernel/intern/writeframeserver.c2
-rw-r--r--source/blender/blenlib/BLI_arithb.h38
-rw-r--r--source/blender/blenlib/BLI_blenlib.h44
-rw-r--r--source/blender/blenlib/BLI_bpath.h38
-rw-r--r--source/blender/blenlib/BLI_edgehash.h3
-rw-r--r--source/blender/blenlib/BLI_editVert.h10
-rw-r--r--source/blender/blenlib/BLI_ghash.h16
-rw-r--r--source/blender/blenlib/BLI_graph.h125
-rw-r--r--source/blender/blenlib/BLI_kdopbvh.h97
-rw-r--r--source/blender/blenlib/BLI_mempool.h44
-rw-r--r--source/blender/blenlib/BLI_rand.h1
-rw-r--r--source/blender/blenlib/BLI_threads.h27
-rw-r--r--source/blender/blenlib/BLI_winstuff.h14
-rw-r--r--source/blender/blenlib/CMakeLists.txt7
-rw-r--r--source/blender/blenlib/SConscript15
-rw-r--r--source/blender/blenlib/intern/BLI_ghash.c25
-rw-r--r--source/blender/blenlib/intern/BLI_kdopbvh.c1526
-rw-r--r--source/blender/blenlib/intern/BLI_kdtree.c34
-rw-r--r--source/blender/blenlib/intern/BLI_mempool.c140
-rw-r--r--source/blender/blenlib/intern/BLI_storage.h7
-rw-r--r--source/blender/blenlib/intern/Makefile3
-rw-r--r--source/blender/blenlib/intern/arithb.c761
-rw-r--r--source/blender/blenlib/intern/boxpack2d.c12
-rw-r--r--source/blender/blenlib/intern/bpath.c355
-rw-r--r--source/blender/blenlib/intern/dynlib.c9
-rw-r--r--source/blender/blenlib/intern/edgehash.c19
-rw-r--r--source/blender/blenlib/intern/fileops.c108
-rw-r--r--source/blender/blenlib/intern/freetypefont.c4
-rw-r--r--source/blender/blenlib/intern/graph.c1087
-rw-r--r--source/blender/blenlib/intern/noise.c564
-rw-r--r--source/blender/blenlib/intern/psfont.c566
-rw-r--r--source/blender/blenlib/intern/rand.c18
-rw-r--r--source/blender/blenlib/intern/storage.c50
-rw-r--r--source/blender/blenlib/intern/threads.c173
-rw-r--r--source/blender/blenlib/intern/util.c505
-rw-r--r--source/blender/blenlib/intern/winstuff.c21
-rw-r--r--source/blender/blenloader/BLO_readfile.h4
-rw-r--r--source/blender/blenloader/BLO_soundfile.h2
-rw-r--r--source/blender/blenloader/BLO_sys_types.h29
-rw-r--r--source/blender/blenloader/SConscript3
-rw-r--r--source/blender/blenloader/intern/readblenentry.c7
-rw-r--r--source/blender/blenloader/intern/readfile.c1296
-rw-r--r--source/blender/blenloader/intern/readfile.h5
-rw-r--r--source/blender/blenloader/intern/writefile.c228
-rw-r--r--source/blender/blenpluginapi/SConscript4
-rw-r--r--source/blender/blenpluginapi/externdef.h5
-rw-r--r--source/blender/blenpluginapi/iff.h67
-rw-r--r--source/blender/blenpluginapi/intern/pluginapi.c80
-rw-r--r--source/blender/blenpluginapi/plugin.h19
-rw-r--r--source/blender/editors/datafiles/SConscript2
-rw-r--r--source/blender/editors/include/BIF_gl.h14
-rw-r--r--source/blender/editors/include/BIF_interface_icons.h0
-rw-r--r--source/blender/editors/include/BIF_resources.h0
-rw-r--r--source/blender/editors/include/BIF_view2d.h0
-rw-r--r--source/blender/editors/interface/Makefile6
-rw-r--r--source/blender/editors/interface/SConscript10
-rw-r--r--source/blender/editors/screen/Makefile1
-rw-r--r--source/blender/editors/screen/SConscript2
-rw-r--r--source/blender/editors/screen/glutil.c1
-rw-r--r--source/blender/editors/space_time/Makefile1
-rw-r--r--source/blender/editors/space_time/SConscript2
-rw-r--r--source/blender/editors/space_view3d/Makefile1
-rw-r--r--source/blender/editors/space_view3d/SConscript2
-rw-r--r--source/blender/ftfont/intern/FTF_TTFont.cpp44
-rw-r--r--source/blender/gpu/CMakeLists.txt34
-rw-r--r--source/blender/gpu/GPU_draw.h116
-rw-r--r--source/blender/gpu/GPU_extensions.h145
-rw-r--r--source/blender/gpu/GPU_material.h169
-rw-r--r--source/blender/gpu/Makefile37
-rw-r--r--source/blender/gpu/SConscript11
-rw-r--r--source/blender/gpu/intern/Makefile53
-rw-r--r--source/blender/gpu/intern/gpu_codegen.c1445
-rw-r--r--source/blender/gpu/intern/gpu_codegen.h87
-rw-r--r--source/blender/gpu/intern/gpu_draw.c1185
-rw-r--r--source/blender/gpu/intern/gpu_extensions.c998
-rw-r--r--source/blender/gpu/intern/gpu_material.c1502
-rw-r--r--source/blender/gpu/intern/gpu_shader_material.glsl1555
-rw-r--r--source/blender/gpu/intern/gpu_shader_material.glsl.c1032
-rw-r--r--source/blender/gpu/intern/gpu_shader_vertex.glsl12
-rw-r--r--source/blender/gpu/intern/gpu_shader_vertex.glsl.c13
-rw-r--r--source/blender/imbuf/CMakeLists.txt4
-rw-r--r--source/blender/imbuf/IMB_imbuf.h2
-rw-r--r--source/blender/imbuf/IMB_imbuf_types.h4
-rw-r--r--source/blender/imbuf/SConscript28
-rw-r--r--source/blender/imbuf/intern/IMB_anim.h17
-rw-r--r--source/blender/imbuf/intern/allocimbuf.c4
-rw-r--r--source/blender/imbuf/intern/amiga.c8
-rw-r--r--source/blender/imbuf/intern/anim.c270
-rw-r--r--source/blender/imbuf/intern/bmp.c4
-rw-r--r--source/blender/imbuf/intern/cineon/SConscript14
-rw-r--r--source/blender/imbuf/intern/cineon/cineon_dpx.c32
-rw-r--r--source/blender/imbuf/intern/cineon/cineonlib.c46
-rw-r--r--source/blender/imbuf/intern/cineon/dpxlib.c93
-rw-r--r--source/blender/imbuf/intern/cineon/logImageCore.c29
-rw-r--r--source/blender/imbuf/intern/cineon/logImageCore.h10
-rw-r--r--source/blender/imbuf/intern/cineon/logImageLib.c5
-rw-r--r--source/blender/imbuf/intern/cineon/logImageLib.h1
-rw-r--r--source/blender/imbuf/intern/cineon/logmemfile.c6
-rw-r--r--source/blender/imbuf/intern/cineon/logmemfile.h2
-rw-r--r--source/blender/imbuf/intern/dds/BlockDXT.cpp214
-rw-r--r--source/blender/imbuf/intern/dds/BlockDXT.h137
-rw-r--r--source/blender/imbuf/intern/dds/CMakeLists.txt45
-rw-r--r--source/blender/imbuf/intern/dds/ColorBlock.cpp117
-rw-r--r--source/blender/imbuf/intern/dds/ColorBlock.h27
-rw-r--r--source/blender/imbuf/intern/dds/Common.h18
-rw-r--r--source/blender/imbuf/intern/dds/DirectDrawSurface.cpp875
-rw-r--r--source/blender/imbuf/intern/dds/DirectDrawSurface.h115
-rw-r--r--source/blender/imbuf/intern/dds/Image.cpp14
-rw-r--r--source/blender/imbuf/intern/dds/Image.h29
-rw-r--r--source/blender/imbuf/intern/dds/PixelFormat.h107
-rw-r--r--source/blender/imbuf/intern/dds/dds_api.cpp1
-rw-r--r--source/blender/imbuf/intern/divers.c2
-rw-r--r--source/blender/imbuf/intern/dynlibtiff.c15
-rw-r--r--source/blender/imbuf/intern/filter.c122
-rwxr-xr-xsource/blender/imbuf/intern/gen_dynlibtiff.py8
-rw-r--r--source/blender/imbuf/intern/hamx.c2
-rw-r--r--source/blender/imbuf/intern/imageprocess.c87
-rw-r--r--source/blender/imbuf/intern/imbuf.h2
-rw-r--r--source/blender/imbuf/intern/imbuf_patch.h2
-rw-r--r--source/blender/imbuf/intern/openexr/openexr_api.cpp143
-rw-r--r--source/blender/imbuf/intern/openexr/openexr_multi.h8
-rw-r--r--source/blender/imbuf/intern/radiance_hdr.c26
-rw-r--r--source/blender/imbuf/intern/readimage.c12
-rw-r--r--source/blender/imbuf/intern/rectop.c17
-rw-r--r--source/blender/imbuf/intern/rotate.c61
-rw-r--r--source/blender/imbuf/intern/scaling.c475
-rw-r--r--source/blender/imbuf/intern/thumbs.c7
-rw-r--r--source/blender/imbuf/intern/tiff.c134
-rw-r--r--source/blender/imbuf/intern/util.c57
-rw-r--r--source/blender/makesdna/DNA_ID.h5
-rw-r--r--source/blender/makesdna/DNA_action_types.h113
-rw-r--r--source/blender/makesdna/DNA_actuator_types.h130
-rw-r--r--source/blender/makesdna/DNA_armature_types.h12
-rw-r--r--source/blender/makesdna/DNA_brush_types.h4
-rw-r--r--source/blender/makesdna/DNA_cloth_types.h95
-rw-r--r--source/blender/makesdna/DNA_color_types.h5
-rw-r--r--source/blender/makesdna/DNA_constraint_types.h42
-rw-r--r--source/blender/makesdna/DNA_controller_types.h7
-rw-r--r--source/blender/makesdna/DNA_curve_types.h45
-rw-r--r--source/blender/makesdna/DNA_customdata_types.h12
-rw-r--r--source/blender/makesdna/DNA_gpencil_types.h145
-rw-r--r--source/blender/makesdna/DNA_group_types.h2
-rw-r--r--source/blender/makesdna/DNA_image_types.h8
-rw-r--r--source/blender/makesdna/DNA_ipo_types.h170
-rw-r--r--source/blender/makesdna/DNA_lamp_types.h40
-rw-r--r--source/blender/makesdna/DNA_material_types.h24
-rw-r--r--source/blender/makesdna/DNA_meshdata_types.h31
-rw-r--r--source/blender/makesdna/DNA_modifier_types.h157
-rw-r--r--source/blender/makesdna/DNA_node_types.h43
-rw-r--r--source/blender/makesdna/DNA_object_fluidsim.h20
-rw-r--r--source/blender/makesdna/DNA_object_force.h95
-rw-r--r--source/blender/makesdna/DNA_object_types.h68
-rw-r--r--source/blender/makesdna/DNA_particle_types.h61
-rw-r--r--source/blender/makesdna/DNA_scene_types.h183
-rw-r--r--source/blender/makesdna/DNA_screen_types.h3
-rw-r--r--source/blender/makesdna/DNA_scriptlink_types.h3
-rw-r--r--source/blender/makesdna/DNA_sensor_types.h34
-rw-r--r--source/blender/makesdna/DNA_sequence_types.h71
-rw-r--r--source/blender/makesdna/DNA_space_types.h100
-rw-r--r--source/blender/makesdna/DNA_text_types.h25
-rw-r--r--source/blender/makesdna/DNA_texture_types.h18
-rw-r--r--source/blender/makesdna/DNA_userdef_types.h76
-rw-r--r--source/blender/makesdna/DNA_view3d_types.h42
-rw-r--r--source/blender/makesdna/DNA_world_types.h14
-rw-r--r--source/blender/makesdna/intern/CMakeLists.txt2
-rw-r--r--source/blender/makesdna/intern/SConscript29
-rw-r--r--source/blender/makesdna/intern/makesdna.c23
-rw-r--r--source/blender/makesrna/intern/makesrna.c4
-rw-r--r--source/blender/nodes/CMP_node.h3
-rw-r--r--source/blender/nodes/CMakeLists.txt5
-rw-r--r--source/blender/nodes/Makefile2
-rw-r--r--source/blender/nodes/SConscript40
-rw-r--r--source/blender/nodes/SHD_node.h2
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_alphaOver.c57
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_bilateralblur.c272
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_blur.c17
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_brightness.c4
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_curves.c8
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_defocus.c31
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_directionalblur.c143
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_displace.c71
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_gamma.c5
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_glare.c18
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_hueSatVal.c2
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_idMask.c22
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_image.c54
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_math.c21
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_premulkey.c77
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_texture.c26
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_tonemap.c11
-rw-r--r--source/blender/nodes/intern/CMP_nodes/CMP_zcombine.c75
-rw-r--r--source/blender/nodes/intern/CMP_nodes/Makefile2
-rw-r--r--source/blender/nodes/intern/CMP_util.c193
-rw-r--r--source/blender/nodes/intern/CMP_util.h5
-rw-r--r--source/blender/nodes/intern/Makefile2
-rw-r--r--source/blender/nodes/intern/SHD_nodes/Makefile5
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_camera.c10
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_curves.c24
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_dynamic.c808
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_geom.c16
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_hueSatVal.c11
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_invert.c8
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_mapping.c17
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_material.c82
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_math.c61
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_mixRgb.c14
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_normal.c11
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_output.c16
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_rgb.c11
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_sepcombRGB.c16
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_squeeze.c8
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_texture.c17
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_valToRgb.c20
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_value.c9
-rw-r--r--source/blender/nodes/intern/SHD_nodes/SHD_vectMath.c31
-rw-r--r--source/blender/nodes/intern/SHD_util.c4
-rw-r--r--source/blender/nodes/intern/SHD_util.h15
-rw-r--r--source/blender/python/BPY_extern.h27
-rw-r--r--source/blender/python/Makefile4
-rw-r--r--source/blender/quicktime/SConscript10
-rw-r--r--source/blender/quicktime/apple/quicktime_export.c28
-rw-r--r--source/blender/radiosity/CMakeLists.txt4
-rw-r--r--source/blender/radiosity/SConscript2
-rw-r--r--source/blender/radiosity/intern/source/Makefile2
-rw-r--r--source/blender/radiosity/intern/source/radfactors.c18
-rw-r--r--source/blender/radiosity/intern/source/radnode.c26
-rw-r--r--source/blender/radiosity/intern/source/radpreprocess.c6
-rw-r--r--source/blender/radiosity/intern/source/radrender.c138
-rw-r--r--source/blender/readblenfile/intern/BLO_readblenfile.c2
-rw-r--r--source/blender/render/CMakeLists.txt2
-rw-r--r--source/blender/render/SConscript22
-rw-r--r--source/blender/render/extern/include/RE_pipeline.h31
-rw-r--r--source/blender/render/extern/include/RE_raytrace.h4
-rw-r--r--source/blender/render/extern/include/RE_shader_ext.h10
-rw-r--r--source/blender/render/intern/include/occlusion.h49
-rw-r--r--source/blender/render/intern/include/pixelblending.h2
-rw-r--r--source/blender/render/intern/include/pixelshading.h5
-rw-r--r--source/blender/render/intern/include/render_types.h89
-rw-r--r--source/blender/render/intern/include/rendercore.h14
-rw-r--r--source/blender/render/intern/include/renderdatabase.h12
-rw-r--r--source/blender/render/intern/include/shadbuf.h2
-rw-r--r--source/blender/render/intern/include/shading.h10
-rw-r--r--source/blender/render/intern/include/sss.h2
-rw-r--r--source/blender/render/intern/include/strand.h19
-rw-r--r--source/blender/render/intern/include/sunsky.h144
-rw-r--r--source/blender/render/intern/include/texture.h2
-rw-r--r--source/blender/render/intern/include/zbuf.h24
-rw-r--r--source/blender/render/intern/source/convertblender.c1527
-rw-r--r--source/blender/render/intern/source/envmap.c39
-rw-r--r--source/blender/render/intern/source/imagetexture.c40
-rw-r--r--source/blender/render/intern/source/initrender.c26
-rw-r--r--source/blender/render/intern/source/occlusion.c1763
-rw-r--r--source/blender/render/intern/source/pipeline.c636
-rw-r--r--source/blender/render/intern/source/pixelblending.c125
-rw-r--r--source/blender/render/intern/source/pixelshading.c154
-rw-r--r--source/blender/render/intern/source/rayshade.c316
-rw-r--r--source/blender/render/intern/source/raytrace.c35
-rw-r--r--source/blender/render/intern/source/rendercore.c1103
-rw-r--r--source/blender/render/intern/source/renderdatabase.c198
-rw-r--r--source/blender/render/intern/source/shadbuf.c61
-rw-r--r--source/blender/render/intern/source/shadeinput.c323
-rw-r--r--source/blender/render/intern/source/shadeoutput.c185
-rw-r--r--source/blender/render/intern/source/sss.c41
-rw-r--r--source/blender/render/intern/source/strand.c1186
-rw-r--r--source/blender/render/intern/source/sunsky.c499
-rw-r--r--source/blender/render/intern/source/texture.c200
-rw-r--r--source/blender/render/intern/source/zbuf.c1180
-rw-r--r--source/blender/windowmanager/SConscript2
-rw-r--r--source/blender/windowmanager/intern/Makefile1
-rw-r--r--source/blender/windowmanager/intern/wm_init_exit.c4
-rw-r--r--source/blender/yafray/intern/export_File.cpp21
-rw-r--r--source/blender/yafray/intern/export_File.h2
-rw-r--r--source/blender/yafray/intern/export_Plugin.cpp62
-rw-r--r--source/blender/yafray/intern/export_Plugin.h12
-rw-r--r--source/blender/yafray/intern/yafray_Render.cpp9
-rw-r--r--source/blender/yafray/intern/yafray_Render.h10
407 files changed, 58145 insertions, 15841 deletions
diff --git a/source/blender/CMakeLists.txt b/source/blender/CMakeLists.txt
index 8551b6412bb..beffd2b13f1 100644
--- a/source/blender/CMakeLists.txt
+++ b/source/blender/CMakeLists.txt
@@ -24,7 +24,7 @@
#
# ***** END GPL LICENSE BLOCK *****
-SUBDIRS(windowmanager editors avi nodes blenkernel blenlib blenloader blenpluginapi imbuf imbuf/intern/cineon makesdna python radiosity readblenfile render yafray)
+SUBDIRS(windowmanager editors avi nodes blenkernel blenlib blenloader blenpluginapi imbuf imbuf/intern/cineon gpu makesdna python radiosity readblenfile render yafray)
IF(WITH_INTERNATIONAL)
SUBDIRS(ftfont)
@@ -34,6 +34,10 @@ IF(WITH_OPENEXR)
SUBDIRS(imbuf/intern/openexr)
ENDIF(WITH_OPENEXR)
+IF(WITH_DDS)
+ SUBDIRS(imbuf/intern/dds)
+ENDIF(WITH_DDS)
+
IF(WITH_QUICKTIME)
SUBDIRS(quicktime)
ENDIF(WITH_QUICKTIME)
diff --git a/source/blender/Makefile b/source/blender/Makefile
index e66c32443a5..37d647788d0 100644
--- a/source/blender/Makefile
+++ b/source/blender/Makefile
@@ -32,11 +32,10 @@ include nan_definitions.mk
DIRS = windowmanager editors blenloader readblenfile
DIRS += avi imbuf render radiosity blenlib blenkernel blenpluginapi
-DIRS += nodes
DIRS += makesdna makesrna yafray
-DIRS += python
+DIRS += python nodes gpu
-ifeq ($(INTERNATIONAL), true)
+ifeq ($(WITH_FREETYPE2), true)
DIRS += ftfont
endif
diff --git a/source/blender/SConscript b/source/blender/SConscript
index 2c39a6d6ff8..93acf8a8430 100644
--- a/source/blender/SConscript
+++ b/source/blender/SConscript
@@ -3,33 +3,38 @@ Import ('env')
import sys
SConscript(['avi/SConscript',
- 'blenkernel/SConscript',
- 'blenlib/SConscript',
- 'blenloader/SConscript',
- 'blenpluginapi/SConscript',
- 'editors/SConscript',
- 'imbuf/SConscript',
- 'imbuf/intern/cineon/SConscript',
- 'makesdna/SConscript',
- 'makesrna/SConscript',
- 'python/SConscript',
- 'radiosity/SConscript',
- 'readblenfile/SConscript',
- 'render/SConscript',
- 'nodes/SConscript',
- 'windowmanager/SConscript'])
-
-if env['WITH_BF_YAFRAY'] == 1:
- SConscript(['yafray/SConscript'])
-
-if env['WITH_BF_INTERNATIONAL'] == 1:
- SConscript (['ftfont/SConscript'])
-
-if env['WITH_BF_DDS'] == 1:
- SConscript (['imbuf/intern/dds/SConscript'])
-
-if env['WITH_BF_OPENEXR'] == 1:
- SConscript (['imbuf/intern/openexr/SConscript'])
-
-if env['WITH_BF_QUICKTIME'] == 1:
- SConscript (['quicktime/SConscript'])
+ 'blenkernel/SConscript',
+ 'blenlib/SConscript',
+ 'blenloader/SConscript',
+ 'blenpluginapi/SConscript',
+ 'gpu/SConscript',
+ 'editors/SConscript',
+ 'imbuf/SConscript',
+ 'imbuf/intern/cineon/SConscript',
+ 'makesdna/SConscript',
+ 'makesrna/SConscript',
+ 'radiosity/SConscript',
+ 'readblenfile/SConscript',
+ 'render/SConscript',
+ 'nodes/SConscript',
+ 'windowmanager/SConscript'])
+
+
+
+if env['WITH_BF_PYTHON']:
+ SConscript(['python/SConscript'])
+
+if env['WITH_BF_YAFRAY']:
+ SConscript(['yafray/SConscript'])
+
+if env['WITH_BF_INTERNATIONAL']:
+ SConscript (['ftfont/SConscript'])
+
+if env['WITH_BF_DDS']:
+ SConscript (['imbuf/intern/dds/SConscript'])
+
+if env['WITH_BF_OPENEXR']:
+ SConscript (['imbuf/intern/openexr/SConscript'])
+
+if env['WITH_BF_QUICKTIME']:
+ SConscript (['quicktime/SConscript'])
diff --git a/source/blender/avi/SConscript b/source/blender/avi/SConscript
index 8c16af9de9d..91239c66ead 100644
--- a/source/blender/avi/SConscript
+++ b/source/blender/avi/SConscript
@@ -7,4 +7,4 @@ sources = env.Glob('intern/*.c')
incs = '. #/intern/guardedalloc'
incs += ' ' + env['BF_JPEG_INC']
-env.BlenderLib ('bf_avi', sources, Split(incs), [], libtype=['core','player'], priority = [105, 40] )
+env.BlenderLib ('bf_avi', sources, Split(incs), [], libtype=['core','player'], priority = [90, 50] )
diff --git a/source/blender/avi/intern/avi.c b/source/blender/avi/intern/avi.c
index 6178807c493..386597c6d85 100644
--- a/source/blender/avi/intern/avi.c
+++ b/source/blender/avi/intern/avi.c
@@ -187,6 +187,7 @@ void AVI_set_debug (int mode) {
AVI_DEBUG= mode;
}
+/*
int AVI_is_avi (char *name) {
FILE *fp;
int ret;
@@ -206,6 +207,195 @@ int AVI_is_avi (char *name) {
fclose(fp);
return ret;
}
+*/
+
+int AVI_is_avi (char *name) {
+ int temp, fcca, j;
+ AviMovie movie;
+ AviMainHeader header;
+ AviBitmapInfoHeader bheader;
+
+ DEBUG("opening movie\n");
+
+ memset(&movie, 0, sizeof(AviMovie));
+
+ movie.type = AVI_MOVIE_READ;
+ movie.fp = fopen (name, "rb");
+ movie.offset_table = NULL;
+
+ if (movie.fp == NULL)
+ return 0;
+
+ if (GET_FCC (movie.fp) != FCC("RIFF") ||
+ !(movie.size = GET_FCC (movie.fp))) {
+ fclose(movie.fp);
+ return 0;
+ }
+
+ movie.header = &header;
+
+ if (GET_FCC (movie.fp) != FCC("AVI ") ||
+ GET_FCC (movie.fp) != FCC("LIST") ||
+ !GET_FCC (movie.fp) ||
+ GET_FCC (movie.fp) != FCC("hdrl") ||
+ (movie.header->fcc = GET_FCC (movie.fp)) != FCC("avih") ||
+ !(movie.header->size = GET_FCC (movie.fp))) {
+ DEBUG("bad initial header info\n");
+ fclose(movie.fp);
+ return 0;
+ }
+
+ movie.header->MicroSecPerFrame = GET_FCC(movie.fp);
+ movie.header->MaxBytesPerSec = GET_FCC(movie.fp);
+ movie.header->PaddingGranularity = GET_FCC(movie.fp);
+ movie.header->Flags = GET_FCC(movie.fp);
+ movie.header->TotalFrames = GET_FCC(movie.fp);
+ movie.header->InitialFrames = GET_FCC(movie.fp);
+ movie.header->Streams = GET_FCC(movie.fp);
+ movie.header->SuggestedBufferSize = GET_FCC(movie.fp);
+ movie.header->Width = GET_FCC(movie.fp);
+ movie.header->Height = GET_FCC(movie.fp);
+ movie.header->Reserved[0] = GET_FCC(movie.fp);
+ movie.header->Reserved[1] = GET_FCC(movie.fp);
+ movie.header->Reserved[2] = GET_FCC(movie.fp);
+ movie.header->Reserved[3] = GET_FCC(movie.fp);
+
+ fseek (movie.fp, movie.header->size-14*4, SEEK_CUR);
+
+ if (movie.header->Streams < 1) {
+ DEBUG("streams less than 1\n");
+ fclose(movie.fp);
+ return 0;
+ }
+
+ movie.streams = (AviStreamRec *) MEM_callocN (sizeof(AviStreamRec) * movie.header->Streams, "moviestreams");
+
+ for (temp=0; temp < movie.header->Streams; temp++) {
+
+ if (GET_FCC(movie.fp) != FCC("LIST") ||
+ !GET_FCC (movie.fp) ||
+ GET_FCC (movie.fp) != FCC ("strl") ||
+ (movie.streams[temp].sh.fcc = GET_FCC (movie.fp)) != FCC ("strh") ||
+ !(movie.streams[temp].sh.size = GET_FCC (movie.fp))) {
+ DEBUG("bad stream header information\n");
+
+ MEM_freeN(movie.streams);
+ fclose(movie.fp);
+ return 0;
+ }
+
+ movie.streams[temp].sh.Type = GET_FCC (movie.fp);
+ movie.streams[temp].sh.Handler = GET_FCC (movie.fp);
+
+ fcca = movie.streams[temp].sh.Handler;
+
+ if (movie.streams[temp].sh.Type == FCC("vids")) {
+ if (fcca == FCC ("DIB ") ||
+ fcca == FCC ("RGB ") ||
+ fcca == FCC ("rgb ") ||
+ fcca == FCC ("RAW ") ||
+ fcca == 0) {
+ movie.streams[temp].format = AVI_FORMAT_AVI_RGB;
+ } else if (fcca == FCC ("mjpg")||fcca == FCC ("MJPG")) {
+ movie.streams[temp].format = AVI_FORMAT_MJPEG;
+ } else {
+ MEM_freeN(movie.streams);
+ fclose(movie.fp);
+ return 0;
+ }
+ }
+
+ movie.streams[temp].sh.Flags = GET_FCC (movie.fp);
+ movie.streams[temp].sh.Priority = GET_TCC (movie.fp);
+ movie.streams[temp].sh.Language = GET_TCC (movie.fp);
+ movie.streams[temp].sh.InitialFrames = GET_FCC (movie.fp);
+ movie.streams[temp].sh.Scale = GET_FCC (movie.fp);
+ movie.streams[temp].sh.Rate = GET_FCC (movie.fp);
+ movie.streams[temp].sh.Start = GET_FCC (movie.fp);
+ movie.streams[temp].sh.Length = GET_FCC (movie.fp);
+ movie.streams[temp].sh.SuggestedBufferSize = GET_FCC (movie.fp);
+ movie.streams[temp].sh.Quality = GET_FCC (movie.fp);
+ movie.streams[temp].sh.SampleSize = GET_FCC (movie.fp);
+ movie.streams[temp].sh.left = GET_TCC (movie.fp);
+ movie.streams[temp].sh.top = GET_TCC (movie.fp);
+ movie.streams[temp].sh.right = GET_TCC (movie.fp);
+ movie.streams[temp].sh.bottom = GET_TCC (movie.fp);
+
+ fseek (movie.fp, movie.streams[temp].sh.size-14*4, SEEK_CUR);
+
+ if (GET_FCC (movie.fp) != FCC("strf")) {
+ DEBUG("no stream format information\n");
+ MEM_freeN(movie.streams);
+ fclose(movie.fp);
+ return 0;
+ }
+
+ movie.streams[temp].sf_size= GET_FCC(movie.fp);
+ if (movie.streams[temp].sh.Type == FCC("vids")) {
+ j = movie.streams[temp].sf_size - (sizeof(AviBitmapInfoHeader) - 8);
+ if (j >= 0) {
+ AviBitmapInfoHeader *bi;
+
+ movie.streams[temp].sf= &bheader;
+ bi= (AviBitmapInfoHeader *) movie.streams[temp].sf;
+
+ bi->fcc= FCC("strf");
+ bi->size= movie.streams[temp].sf_size;
+ bi->Size= GET_FCC(movie.fp);
+ bi->Width= GET_FCC(movie.fp);
+ bi->Height= GET_FCC(movie.fp);
+ bi->Planes= GET_TCC(movie.fp);
+ bi->BitCount= GET_TCC(movie.fp);
+ bi->Compression= GET_FCC(movie.fp);
+ bi->SizeImage= GET_FCC(movie.fp);
+ bi->XPelsPerMeter= GET_FCC(movie.fp);
+ bi->YPelsPerMeter= GET_FCC(movie.fp);
+ bi->ClrUsed= GET_FCC(movie.fp);
+ bi->ClrImportant= GET_FCC(movie.fp);
+
+ fcca = bi->Compression;
+
+ if ( movie.streams[temp].format ==
+ AVI_FORMAT_AVI_RGB) {
+ if (fcca == FCC ("DIB ") ||
+ fcca == FCC ("RGB ") ||
+ fcca == FCC ("rgb ") ||
+ fcca == FCC ("RAW ") ||
+ fcca == 0 ) {
+ } else if ( fcca == FCC ("mjpg") ||
+ fcca == FCC ("MJPG")) {
+ movie.streams[temp].format = AVI_FORMAT_MJPEG;
+ } else {
+ MEM_freeN(movie.streams);
+ fclose(movie.fp);
+ return 0;
+ }
+ }
+
+ }
+ if (j > 0) fseek (movie.fp, j, SEEK_CUR);
+ } else fseek (movie.fp, movie.streams[temp].sf_size, SEEK_CUR);
+
+ /* Walk to the next LIST */
+ while (GET_FCC (movie.fp) != FCC("LIST")) {
+ temp= GET_FCC (movie.fp);
+ if (temp<0 || ftell(movie.fp) > movie.size) {
+ DEBUG("incorrect size in header or error in AVI\n");
+
+ MEM_freeN(movie.streams);
+ fclose(movie.fp);
+ return 0;
+ }
+ fseek(movie.fp, temp, SEEK_CUR);
+ }
+
+ fseek(movie.fp, -4L, SEEK_CUR);
+ }
+
+ MEM_freeN(movie.streams);
+ fclose(movie.fp);
+ return 1;
+}
AviError AVI_open_movie (char *name, AviMovie *movie) {
int temp, fcca, size, j;
@@ -439,7 +629,7 @@ AviError AVI_open_movie (char *name, AviMovie *movie) {
}
void *AVI_read_frame (AviMovie *movie, AviFormat format, int frame, int stream) {
- int cur_frame, temp, i, rewind=1;
+ int cur_frame=-1, temp, i=0, rewind=1;
void *buffer;
/* Retrieve the record number of the desired frame in the index
diff --git a/source/blender/avi/intern/avirgb.c b/source/blender/avi/intern/avirgb.c
index 9731a8f0e28..3a28f4da8a0 100644
--- a/source/blender/avi/intern/avirgb.c
+++ b/source/blender/avi/intern/avirgb.c
@@ -43,7 +43,7 @@
#include "MEM_guardedalloc.h"
#include "avirgb.h"
-#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
+#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__hppa__) || defined (__BIG_ENDIAN__)
#define WORDS_BIGENDIAN
#endif
diff --git a/source/blender/avi/intern/endian.c b/source/blender/avi/intern/endian.c
index 2e549e3f298..ecbabf07039 100644
--- a/source/blender/avi/intern/endian.c
+++ b/source/blender/avi/intern/endian.c
@@ -43,10 +43,11 @@
#include "endian.h"
#include "avi_intern.h"
-#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
+#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__hppa__) || defined (__BIG_ENDIAN__)
#define WORDS_BIGENDIAN
#endif
+#ifdef WORDS_BIGENDIAN
static void invert (int *num) {
int new=0,i,j;
@@ -76,6 +77,7 @@ static void Ichunk (AviChunk *chunk) {
invert (&chunk->fcc);
invert (&chunk->size);
}
+#endif
#ifdef WORDS_BIGENDIAN
static void Ilist (AviList *list){
diff --git a/source/blender/blenkernel/BKE_DerivedMesh.h b/source/blender/blenkernel/BKE_DerivedMesh.h
index b66e009e3d3..5a1e266adeb 100644
--- a/source/blender/blenkernel/BKE_DerivedMesh.h
+++ b/source/blender/blenkernel/BKE_DerivedMesh.h
@@ -55,6 +55,7 @@ struct EditMesh;
struct ModifierData;
struct MCol;
struct ColorBand;
+struct GPUVertexAttribs;
/* number of sub-elements each mesh element has (for interpolation) */
#define SUB_ELEMS_VERT 0
@@ -198,7 +199,8 @@ struct DerivedMesh {
*
* Also called for *final* editmode DerivedMeshes
*/
- void (*drawFacesSolid)(DerivedMesh *dm, int (*setMaterial)(int));
+ void (*drawFacesSolid)(DerivedMesh *dm,
+ int (*setMaterial)(int, void *attribs));
/* Draw all faces
* o If useTwoSided, draw front and back using col arrays
@@ -215,6 +217,13 @@ struct DerivedMesh {
int (*setDrawOptions)(struct MTFace *tface,
struct MCol *mcol, int matnr));
+ /* Draw all faces with GLSL materials
+ * o setMaterial is called for every different material nr
+ * o Only if setMaterial returns true
+ */
+ void (*drawFacesGLSL)(DerivedMesh *dm,
+ int (*setMaterial)(int, void *attribs));
+
/* Draw mapped faces (no color, or texture)
* o Only if !setDrawOptions or
* setDrawOptions(userData, mapped-face-index, drawSmooth_r)
@@ -241,6 +250,15 @@ struct DerivedMesh {
int index),
void *userData);
+ /* Draw mapped faces with GLSL materials
+ * o setMaterial is called for every different material nr
+ * o setDrawOptions is called for every face
+ * o Only if setMaterial and setDrawOptions return true
+ */
+ void (*drawMappedFacesGLSL)(DerivedMesh *dm,
+ int (*setMaterial)(int, void *attribs),
+ int (*setDrawOptions)(void *userData, int index), void *userData);
+
/* Draw mapped edges as lines
* o Only if !setDrawOptions or setDrawOptions(userData, mapped-edge)
* returns true
@@ -412,7 +430,10 @@ DerivedMesh *mesh_create_derived_for_modifier(struct Object *ob, struct Modifier
DerivedMesh *mesh_create_derived_render(struct Object *ob,
CustomDataMask dataMask);
-/* same as above but wont use render settings */
+
+DerivedMesh *mesh_create_derived_index_render(struct Object *ob, CustomDataMask dataMask, int index);
+
+ /* same as above but wont use render settings */
DerivedMesh *mesh_create_derived_view(struct Object *ob,
CustomDataMask dataMask);
DerivedMesh *mesh_create_derived_no_deform(struct Object *ob,
@@ -437,23 +458,36 @@ void weight_to_rgb(float input, float *fr, float *fg, float *fb);
/* determines required DerivedMesh data according to view and edit modes */
CustomDataMask get_viewedit_datamask();
-/* repeate this pattern
- X000X000
- 00000000
- 00X000X0
- 00000000 */
-
-#define DM_FACE_STIPPLE \
-{ \
- 136,136,136,136,0,0,0,0,34,34,34,34,0,0,0,0, \
- 136,136,136,136,0,0,0,0,34,34,34,34,0,0,0,0, \
- 136,136,136,136,0,0,0,0,34,34,34,34,0,0,0,0, \
- 136,136,136,136,0,0,0,0,34,34,34,34,0,0,0,0, \
- 136,136,136,136,0,0,0,0,34,34,34,34,0,0,0,0, \
- 136,136,136,136,0,0,0,0,34,34,34,34,0,0,0,0, \
- 136,136,136,136,0,0,0,0,34,34,34,34,0,0,0,0, \
- 136,136,136,136,0,0,0,0,34,34,34,34,0,0,0,0 \
-}
+/* convert layers requested by a GLSL material to actually available layers in
+ * the DerivedMesh, with both a pointer for arrays and an offset for editmesh */
+typedef struct DMVertexAttribs {
+ struct {
+ struct MTFace *array;
+ int emOffset, glIndex;
+ } tface[MAX_MTFACE];
+
+ struct {
+ struct MCol *array;
+ int emOffset, glIndex;
+ } mcol[MAX_MCOL];
+
+ struct {
+ float (*array)[3];
+ int emOffset, glIndex;
+ } tang;
+
+ struct {
+ float (*array)[3];
+ int emOffset, glIndex;
+ } orco;
+
+ int tottface, totmcol, tottang, totorco;
+} DMVertexAttribs;
+
+void DM_vertex_attributes_from_gpu(DerivedMesh *dm,
+ struct GPUVertexAttribs *gattribs, DMVertexAttribs *attribs);
+
+void DM_add_tangent_layer(DerivedMesh *dm);
#endif
diff --git a/source/blender/blenkernel/BKE_action.h b/source/blender/blenkernel/BKE_action.h
index efdd75d1046..37ced4cb00b 100644
--- a/source/blender/blenkernel/BKE_action.h
+++ b/source/blender/blenkernel/BKE_action.h
@@ -44,6 +44,7 @@ struct bActionChannel;
struct bPose;
struct bPoseChannel;
struct Object;
+struct ID;
/* Kernel prototypes */
#ifdef __cplusplus
@@ -57,6 +58,11 @@ extern "C" {
*/
void free_pose_channels(struct bPose *pose);
+/**
+ * Removes and deallocates all data from a pose, and also frees the pose.
+ */
+void free_pose(struct bPose *pose);
+
/**
* Allocate a new pose on the heap, and copy the src pose and it's channels
* into the new pose. *dst is set to the newly allocated structure, and assumed to be NULL.
@@ -152,6 +158,14 @@ void rest_pose(struct bPose *pose);
float get_action_frame(struct Object *ob, float cframe);
/* map strip time to global time (frame nr) */
float get_action_frame_inv(struct Object *ob, float cframe);
+/* builds a list of NlaIpoChannel with ipo values to write in datablock */
+void extract_ipochannels_from_action(ListBase *lb, struct ID *id, struct bAction *act, const char *name, float ctime);
+/* write values returned by extract_ipochannels_from_action, returns the number of value written */
+int execute_ipochannels(ListBase *lb);
+
+/* functions used by the game engine */
+void game_copy_pose(struct bPose **dst, struct bPose *src);
+void game_free_pose(struct bPose *pose);
#ifdef __cplusplus
};
diff --git a/source/blender/blenkernel/BKE_anim.h b/source/blender/blenkernel/BKE_anim.h
index 2b7a4c5af46..5ea511738ad 100644
--- a/source/blender/blenkernel/BKE_anim.h
+++ b/source/blender/blenkernel/BKE_anim.h
@@ -31,6 +31,8 @@
#ifndef BKE_ANIM_H
#define BKE_ANIM_H
+#define MAX_DUPLI_RECUR 8
+
struct Path;
struct Object;
struct PartEff;
@@ -41,8 +43,9 @@ typedef struct DupliObject {
struct DupliObject *next, *prev;
struct Object *ob;
unsigned int origlay;
- int index, no_draw;
+ int index, no_draw, type, animated;
float mat[4][4], omat[4][4];
+ float orco[3], uv[2];
} DupliObject;
void free_path(struct Path *path);
diff --git a/source/blender/blenkernel/BKE_armature.h b/source/blender/blenkernel/BKE_armature.h
index 6739f3118af..62061238131 100644
--- a/source/blender/blenkernel/BKE_armature.h
+++ b/source/blender/blenkernel/BKE_armature.h
@@ -75,7 +75,9 @@ void unlink_armature(struct bArmature *arm);
void free_armature(struct bArmature *arm);
void make_local_armature(struct bArmature *arm);
struct bArmature *copy_armature(struct bArmature *arm);
+
void bone_flip_name (char *name, int strip_number);
+void bone_autoside_name (char *name, int strip_number, short axis, float head, float tail);
struct bArmature *get_armature (struct Object *ob);
struct Bone *get_named_bone (struct bArmature *arm, const char *name);
diff --git a/source/blender/blenkernel/BKE_bmesh.h b/source/blender/blenkernel/BKE_bmesh.h
new file mode 100644
index 00000000000..71c042e34fe
--- /dev/null
+++ b/source/blender/blenkernel/BKE_bmesh.h
@@ -0,0 +1,253 @@
+/**
+ * BKE_bmesh.h jan 2007
+ *
+ * BMesh modeler structure and functions.
+ *
+ * $Id: BKE_bmesh.h,v 1.00 2007/01/17 17:42:01 Briggs Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2004 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Geoffrey Bantle.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef BKE_BMESH_H
+#define BKE_BMESH_H
+
+#include "DNA_listBase.h"
+#include "BLI_ghash.h"
+#include "BLI_mempool.h"
+#include "BLI_memarena.h"
+#include "DNA_image_types.h"
+#include "BLI_editVert.h"
+#include "BKE_DerivedMesh.h"
+//XXX #include "transform.h"
+
+/*forward declerations*/
+struct BME_Vert;
+struct BME_Edge;
+struct BME_Poly;
+struct BME_Loop;
+
+
+/*Notes on further structure Cleanup:
+ -Remove the tflags, they belong in custom data layers
+ -Remove the eflags completely, they are mostly not used
+ -Remove the selection/vis/bevel weight flag/values ect and move them to custom data
+ -Remove EID member and move to custom data
+ -Add a radial cycle length, disk cycle length and loop cycle lenght attributes to custom data and have eulers maintain/use them if present.
+ -Move data such as vertex coordinates/normals to custom data and leave pointers in structures to active layer data.
+ -Remove BME_CycleNode structure?
+*/
+typedef struct BME_CycleNode{
+ struct BME_CycleNode *next, *prev;
+ void *data;
+} BME_CycleNode;
+
+typedef struct BME_Mesh
+{
+ ListBase verts, edges, polys;
+ /*memory pools used for storing mesh elements*/
+ struct BLI_mempool *vpool;
+ struct BLI_mempool *epool;
+ struct BLI_mempool *ppool;
+ struct BLI_mempool *lpool;
+ /*some scratch arrays used by eulers*/
+ struct BME_Vert **vtar;
+ struct BME_Edge **edar;
+ struct BME_Loop **lpar;
+ struct BME_Poly **plar;
+ int vtarlen, edarlen, lparlen, plarlen;
+ int totvert, totedge, totpoly, totloop; /*record keeping*/
+ int nextv, nexte, nextp, nextl; /*Next element ID for verts/edges/faces/loops. Never reused*/
+ struct CustomData vdata, edata, pdata, ldata; /*Custom Data Layer information*/
+} BME_Mesh;
+
+typedef struct BME_Vert
+{
+ struct BME_Vert *next, *prev;
+ int EID;
+ float co[3];
+ float no[3];
+ struct BME_Edge *edge; /*first edge in the disk cycle for this vertex*/
+ void *data; /*custom vertex data*/
+ int eflag1, eflag2; /*reserved for use by eulers*/
+ int tflag1, tflag2; /*reserved for use by tools*/
+ unsigned short flag, h;
+ float bweight;
+} BME_Vert;
+
+typedef struct BME_Edge
+{
+ struct BME_Edge *next, *prev;
+ int EID;
+ struct BME_Vert *v1, *v2; /*note that order of vertex pointers means nothing to eulers*/
+ struct BME_CycleNode d1, d2; /*disk cycle nodes for v1 and v2 respectivley*/
+ struct BME_Loop *loop; /*first BME_Loop in the radial cycle around this edge*/
+ void *data; /*custom edge data*/
+ int eflag1, eflag2; /*reserved for use by eulers*/
+ int tflag1, tflag2; /*reserved for use by tools*/
+ unsigned short flag, h;
+ float crease, bweight;
+} BME_Edge;
+
+typedef struct BME_Loop
+{
+ struct BME_Loop *next, *prev; /*circularly linked list around face*/
+ int EID;
+ struct BME_CycleNode radial; /*circularly linked list used to find faces around an edge*/
+ struct BME_Vert *v; /*vertex that this loop starts at.*/
+ struct BME_Edge *e; /*edge this loop belongs to*/
+ struct BME_Poly *f; /*face this loop belongs to*/
+ void *data; /*custom per face vertex data*/
+ int eflag1, eflag2; /*reserved for use by eulers*/
+ int tflag1, tflag2; /*reserved for use by tools*/
+ unsigned short flag, h;
+} BME_Loop;
+
+typedef struct BME_Poly
+{
+ struct BME_Poly *next, *prev;
+ int EID;
+ struct BME_Loop *loopbase; /*First editloop around Polygon.*/
+ unsigned int len; /*total length of the face. Eulers should preserve this data*/
+ void *data; /*custom face data*/
+ int eflag1, eflag2; /*reserved for use by eulers*/
+ int tflag1, tflag2; /*reserved for use by tools*/
+ unsigned short flag, h, mat_nr;
+} BME_Poly;
+
+/*EDGE UTILITIES*/
+int BME_verts_in_edge(struct BME_Vert *v1, struct BME_Vert *v2, struct BME_Edge *e);
+int BME_vert_in_edge(struct BME_Edge *e, BME_Vert *v);
+struct BME_Vert *BME_edge_getothervert(struct BME_Edge *e, struct BME_Vert *v);
+
+/*GENERAL CYCLE*/
+int BME_cycle_length(void *h);
+
+/*DISK CYCLE*/
+struct BME_Edge *BME_disk_nextedge(struct BME_Edge *e, struct BME_Vert *v);
+struct BME_CycleNode *BME_disk_getpointer(struct BME_Edge *e, struct BME_Vert *v);
+struct BME_Edge *BME_disk_next_edgeflag(struct BME_Edge *e, struct BME_Vert *v, int eflag, int tflag);
+int BME_disk_count_edgeflag(struct BME_Vert *v, int eflag, int tflag);
+
+/*RADIAL CYCLE*/
+struct BME_Loop *BME_radial_nextloop(struct BME_Loop *l);
+int BME_radial_find_face(struct BME_Edge *e,struct BME_Poly *f);
+
+/*LOOP CYCLE*/
+struct BME_Loop *BME_loop_find_loop(struct BME_Poly *f, struct BME_Vert *v);
+
+/*MESH CREATION/DESTRUCTION*/
+struct BME_Mesh *BME_make_mesh(int allocsize[4]);
+void BME_free_mesh(struct BME_Mesh *bm);
+/*FULL MESH VALIDATION*/
+int BME_validate_mesh(struct BME_Mesh *bm, int halt);
+/*ENTER/EXIT MODELLING LOOP*/
+int BME_model_begin(struct BME_Mesh *bm);
+void BME_model_end(struct BME_Mesh *bm);
+
+/*MESH CONSTRUCTION API.*/
+/*MAKE*/
+struct BME_Vert *BME_MV(struct BME_Mesh *bm, float *vec);
+struct BME_Edge *BME_ME(struct BME_Mesh *bm, struct BME_Vert *v1, struct BME_Vert *v2);
+struct BME_Poly *BME_MF(struct BME_Mesh *bm, struct BME_Vert *v1, struct BME_Vert *v2, struct BME_Edge **elist, int len);
+/*KILL*/
+int BME_KV(struct BME_Mesh *bm, struct BME_Vert *v);
+int BME_KE(struct BME_Mesh *bm, struct BME_Edge *e);
+int BME_KF(struct BME_Mesh *bm, struct BME_Poly *bply);
+/*SPLIT*/
+struct BME_Vert *BME_SEMV(struct BME_Mesh *bm, struct BME_Vert *tv, struct BME_Edge *e, struct BME_Edge **re);
+struct BME_Poly *BME_SFME(struct BME_Mesh *bm, struct BME_Poly *f, struct BME_Vert *v1, struct BME_Vert *v2, struct BME_Loop **rl);
+/*JOIN*/
+int BME_JEKV(struct BME_Mesh *bm, struct BME_Edge *ke, struct BME_Vert *kv);
+struct BME_Poly *BME_JFKE(struct BME_Mesh *bm, struct BME_Poly *f1, struct BME_Poly *f2,struct BME_Edge *e); /*no reason to return BME_Poly pointer?*/
+/*NORMAL FLIP(Is its own inverse)*/
+int BME_loop_reverse(struct BME_Mesh *bm, struct BME_Poly *f);
+
+/* bevel tool defines */
+/* element flags */
+#define BME_BEVEL_ORIG 1
+#define BME_BEVEL_BEVEL (1<<1)
+#define BME_BEVEL_NONMAN (1<<2)
+#define BME_BEVEL_WIRE (1<<3)
+
+/* tool options */
+#define BME_BEVEL_SELECT 1
+#define BME_BEVEL_VERT (1<<1)
+#define BME_BEVEL_RADIUS (1<<2)
+#define BME_BEVEL_ANGLE (1<<3)
+#define BME_BEVEL_WEIGHT (1<<4)
+//~ #define BME_BEVEL_EWEIGHT (1<<4)
+//~ #define BME_BEVEL_VWEIGHT (1<<5)
+#define BME_BEVEL_PERCENT (1<<6)
+#define BME_BEVEL_EMIN (1<<7)
+#define BME_BEVEL_EMAX (1<<8)
+#define BME_BEVEL_RUNNING (1<<9)
+#define BME_BEVEL_RES (1<<10)
+
+typedef struct BME_TransData {
+ BME_Mesh *bm; /* the bmesh the vert belongs to */
+ BME_Vert *v; /* pointer to the vert this tdata applies to */
+ float co[3]; /* the original coordinate */
+ float org[3]; /* the origin */
+ float vec[3]; /* a directional vector; always, always normalize! */
+ void *loc; /* a pointer to the data to transform (likely the vert's cos) */
+ float factor; /* primary scaling factor; also accumulates number of weighted edges for beveling tool */
+ float weight; /* another scaling factor; used primarily for propogating vertex weights to transforms; */
+ /* weight is also used across recursive bevels to help with the math */
+ float maxfactor; /* the unscaled, original factor (used only by "edge verts" in recursive beveling) */
+ float *max; /* the maximum distance this vert can be transformed; negative is infinite
+ * it points to the "parent" maxfactor (where maxfactor makes little sense)
+ * where the max limit is stored (limits are stored per-corner) */
+} BME_TransData;
+
+typedef struct BME_TransData_Head {
+ GHash *gh; /* the hash structure for element lookup */
+ MemArena *ma; /* the memory "pool" we will be drawing individual elements from */
+ int len;
+} BME_TransData_Head;
+
+typedef struct BME_Glob { /* stored in Global G for Transform() purposes */
+ BME_Mesh *bm;
+ BME_TransData_Head *td;
+ struct TransInfo *Trans; /* a pointer to the global Trans struct */
+ int imval[2]; /* for restoring original mouse co when initTransform() is called multiple times */
+ int options;
+ int res;
+} BME_Glob;
+
+struct BME_TransData *BME_get_transdata(struct BME_TransData_Head *td, struct BME_Vert *v);
+void BME_free_transdata(struct BME_TransData_Head *td);
+float *BME_bevel_calc_polynormal(struct BME_Poly *f, struct BME_TransData_Head *td);
+struct BME_Mesh *BME_bevel(struct BME_Mesh *bm, float value, int res, int options, int defgrp_index, float angle, BME_TransData_Head **rtd);
+
+/*CONVERSION FUNCTIONS*/
+struct BME_Mesh *BME_editmesh_to_bmesh(EditMesh *em);
+struct EditMesh *BME_bmesh_to_editmesh(struct BME_Mesh *bm, BME_TransData_Head *td);
+struct BME_Mesh *BME_derivedmesh_to_bmesh(struct DerivedMesh *dm);
+struct DerivedMesh *BME_bmesh_to_derivedmesh(struct BME_Mesh *bm, struct DerivedMesh *dm);
+#endif
diff --git a/source/blender/blenkernel/BKE_bmeshCustomData.h b/source/blender/blenkernel/BKE_bmeshCustomData.h
new file mode 100644
index 00000000000..4f5f2641f54
--- /dev/null
+++ b/source/blender/blenkernel/BKE_bmeshCustomData.h
@@ -0,0 +1,108 @@
+/**
+ * BKE_bmesh.h jan 2007
+ *
+ * BMesh modeler structure and functions.
+ *
+ * $Id: BKE_bmesh.h,v 1.00 2007/01/17 17:42:01 Briggs Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2004 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Geoffrey Bantle.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+
+#ifndef BKE_BMESHCUSTOMDATA_H
+#define BKE_BMESHCUSTOMDATA_H
+
+struct BLI_mempool;
+
+/*Custom Data Types and defines
+ Eventual plan is to move almost everything to custom data and let caller
+ decide when making the mesh what layers they want to store in the mesh
+
+ This stuff should probably go in a seperate file....
+*/
+
+#define BME_CD_FACETEX 0 /*Image texture/texface*/
+#define BME_CD_LOOPTEX 1 /*UV coordinates*/
+#define BME_CD_LOOPCOL 2 /*Vcolors*/
+#define BME_CD_DEFORMVERT 3 /*Vertex Group/Weights*/
+#define BME_CD_NUMTYPES 4
+
+typedef struct BME_CustomDataLayer {
+ int type; /* type of data in layer */
+ int offset; /* offset of layer in block */
+ int active; /* offset of active layer*/
+ char name[32]; /* layer name */
+} BME_CustomDataLayer;
+
+typedef struct BME_CustomData {
+ struct BME_CustomDataLayer *layers; /*Custom Data Layers*/
+ struct BLI_mempool *pool; /*pool for alloc of blocks*/
+ int totlayer, totsize; /*total layers and total size in bytes of each block*/
+} BME_CustomData;
+
+typedef struct BME_CustomDataInit{
+ int layout[BME_CD_NUMTYPES];
+ int active[BME_CD_NUMTYPES];
+ int totlayers;
+ char *nametemplate;
+} BME_CustomDataInit;
+
+/*Custom data types*/
+typedef struct BME_DeformWeight {
+ int def_nr;
+ float weight;
+} BME_DeformWeight;
+
+typedef struct BME_DeformVert {
+ struct BME_DeformWeight *dw;
+ int totweight;
+} BME_DeformVert;
+
+typedef struct BME_facetex{
+ struct Image *tpage;
+ char flag, transp;
+ short mode, tile, unwrap;
+}BME_facetex;
+
+typedef struct BME_looptex{
+ float u, v;
+}BME_looptex;
+
+typedef struct BME_loopcol{
+ char r, g, b, a;
+}BME_loopcol;
+
+/*CUSTOM DATA API*/
+void BME_CD_Create(struct BME_CustomData *data, struct BME_CustomDataInit *init, int initalloc);
+void BME_CD_Free(struct BME_CustomData *data);
+void BME_CD_free_block(struct BME_CustomData *data, void **block);
+void BME_CD_copy_data(const struct BME_CustomData *source, struct BME_CustomData *dest, void *src_block, void **dest_block);
+void BME_CD_set_default(struct BME_CustomData *data, void **block);
+
+#endif
diff --git a/source/blender/blenkernel/BKE_brush.h b/source/blender/blenkernel/BKE_brush.h
index bf8e046eb20..f1f4653f092 100644
--- a/source/blender/blenkernel/BKE_brush.h
+++ b/source/blender/blenkernel/BKE_brush.h
@@ -45,7 +45,7 @@ void free_brush(struct Brush *brush);
int brush_set_nr(struct Brush **current_brush, int nr);
int brush_delete(struct Brush **current_brush);
void brush_check_exists(struct Brush **brush);
-void brush_toggle_fake_user(struct Brush *brush);
+void brush_toggled_fake_user(struct Brush *brush);
int brush_texture_set_nr(struct Brush *brush, int nr);
int brush_texture_delete(struct Brush *brush);
int brush_clone_image_set_nr(struct Brush *brush, int nr);
diff --git a/source/blender/blenkernel/BKE_bullet.h b/source/blender/blenkernel/BKE_bullet.h
new file mode 100644
index 00000000000..1c3bb175d66
--- /dev/null
+++ b/source/blender/blenkernel/BKE_bullet.h
@@ -0,0 +1,43 @@
+/**
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef BKE_BULLET_H
+#define BKE_BULLET_H
+
+struct BulletSoftBody;
+
+
+/* allocates and initializes general main data */
+extern struct BulletSoftBody *bsbNew(void);
+
+/* frees internal data and softbody itself */
+extern void bsbFree(struct BulletSoftBody *sb);
+
+#endif
+
diff --git a/source/blender/blenkernel/BKE_bvhutils.h b/source/blender/blenkernel/BKE_bvhutils.h
new file mode 100644
index 00000000000..dd9ea61f24b
--- /dev/null
+++ b/source/blender/blenkernel/BKE_bvhutils.h
@@ -0,0 +1,98 @@
+/**
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2006 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): André Pinto
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef BKE_BVHUTILS_H
+#define BKE_BVHUTILS_H
+
+#include "BLI_kdopbvh.h"
+
+/*
+ * This header encapsulates necessary code to buld a BVH
+ */
+
+struct DerivedMesh;
+struct MVert;
+struct MFace;
+
+/*
+ * struct that kepts basic information about a BVHTree build from a mesh
+ */
+typedef struct BVHTreeFromMesh
+{
+ struct BVHTree *tree;
+
+ /* default callbacks to bvh nearest and raycast */
+ BVHTree_NearestPointCallback nearest_callback;
+ BVHTree_RayCastCallback raycast_callback;
+
+ /* Mesh represented on this BVHTree */
+ struct DerivedMesh *mesh;
+
+ /* Vertex array, so that callbacks have instante access to data */
+ struct MVert *vert;
+ struct MFace *face;
+
+ /* radius for raycast */
+ float sphere_radius;
+
+} BVHTreeFromMesh;
+
+/*
+ * Builds a bvh tree where nodes are the vertexs of the given mesh.
+ * Configures BVHTreeFromMesh.
+ *
+ * The tree is build in mesh space coordinates, this means special care must be made on queries
+ * so that the coordinates and rays are first translated on the mesh local coordinates.
+ * Reason for this is that later bvh_from_mesh_* might use a cache system and so it becames possible to reuse
+ * a BVHTree.
+ *
+ * free_bvhtree_from_mesh should be called when the tree is no longer needed.
+ */
+void bvhtree_from_mesh_verts(struct BVHTreeFromMesh *data, struct DerivedMesh *mesh, float epsilon, int tree_type, int axis);
+
+/*
+ * Builds a bvh tree where nodes are the faces of the given mesh.
+ * Configures BVHTreeFromMesh.
+ *
+ * The tree is build in mesh space coordinates, this means special care must be made on queries
+ * so that the coordinates and rays are first translated on the mesh local coordinates.
+ * Reason for this is that later bvh_from_mesh_* might use a cache system and so it becames possible to reuse
+ * a BVHTree.
+ *
+ * free_bvhtree_from_mesh should be called when the tree is no longer needed.
+ */
+void bvhtree_from_mesh_faces(struct BVHTreeFromMesh *data, struct DerivedMesh *mesh, float epsilon, int tree_type, int axis);
+
+/*
+ * Frees data allocated by a call to bvhtree_from_mesh_*.
+ */
+void free_bvhtree_from_mesh(struct BVHTreeFromMesh *data);
+
+#endif
+
diff --git a/source/blender/blenkernel/BKE_cloth.h b/source/blender/blenkernel/BKE_cloth.h
new file mode 100644
index 00000000000..f3c13d3d820
--- /dev/null
+++ b/source/blender/blenkernel/BKE_cloth.h
@@ -0,0 +1,282 @@
+/**
+ * BKE_cloth.h
+ *
+ * $Id: BKE_cloth.h,v 1.1 2007/08/01 02:07:27 daniel Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Daniel Genrich
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef BKE_CLOTH_H
+#define BKE_CLOTH_H
+
+#include <float.h>
+
+#include "BLI_linklist.h"
+#include "BKE_customdata.h"
+#include "BKE_DerivedMesh.h"
+
+#include "BLI_blenlib.h"
+#include "BLI_arithb.h"
+#include "BLI_edgehash.h"
+
+#include "DNA_cloth_types.h"
+#include "DNA_customdata_types.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_modifier_types.h"
+#include "DNA_object_types.h"
+
+#include "BKE_collision.h"
+
+struct Object;
+
+struct MFace;
+struct DerivedMesh;
+struct ClothModifierData;
+struct CollisionTree;
+
+// this is needed for inlining behaviour
+#if defined _WIN32
+# define DO_INLINE __inline
+#elif defined (__sgi)
+# define DO_INLINE
+#elif defined (__sun) || defined (__sun__)
+# define DO_INLINE
+#else
+# define DO_INLINE inline
+# define LINUX
+#endif
+
+#define CLOTH_MAX_THREAD 2
+
+/* goal defines */
+#define SOFTGOALSNAP 0.999f
+
+/* This is approximately the smallest number that can be
+* represented by a float, given its precision. */
+#define ALMOST_ZERO FLT_EPSILON
+
+/* Bits to or into the ClothVertex.flags. */
+#define CLOTH_VERT_FLAG_PINNED 1
+#define CLOTH_VERT_FLAG_COLLISION 2
+#define CLOTH_VERT_FLAG_PINNED_EM 3
+
+/**
+* This structure describes a cloth object against which the
+* simulation can run.
+*
+* The m and n members of this structure represent the assumed
+* rectangular ordered grid for which the original paper is written.
+* At some point they need to disappear and we need to determine out
+* own connectivity of the mesh based on the actual edges in the mesh.
+*
+**/
+typedef struct Cloth
+{
+ struct ClothVertex *verts; /* The vertices that represent this cloth. */
+ struct LinkNode *springs; /* The springs connecting the mesh. */
+ unsigned int numverts; /* The number of verts == m * n. */
+ unsigned int numsprings; /* The count of springs. */
+ unsigned int numfaces;
+ unsigned char old_solver_type; /* unused, only 1 solver here */
+ unsigned char pad2;
+ short pad3;
+ struct BVHTree *bvhtree; /* collision tree for this cloth object */
+ struct BVHTree *bvhselftree; /* collision tree for this cloth object */
+ struct MFace *mfaces;
+ struct Implicit_Data *implicit; /* our implicit solver connects to this pointer */
+ struct Implicit_Data *implicitEM; /* our implicit solver connects to this pointer */
+ struct EdgeHash *edgehash; /* used for selfcollisions */
+} Cloth;
+
+/**
+ * The definition of a cloth vertex.
+ */
+typedef struct ClothVertex
+{
+ int flags; /* General flags per vertex. */
+ float v [3]; /* The velocity of the point. */
+ float xconst [3]; /* constrained position */
+ float x [3]; /* The current position of this vertex. */
+ float xold [3]; /* The previous position of this vertex.*/
+ float tx [3]; /* temporary position */
+ float txold [3]; /* temporary old position */
+ float tv[3]; /* temporary "velocity", mostly used as tv = tx-txold */
+ float mass; /* mass / weight of the vertex */
+ float goal; /* goal, from SB */
+ float impulse[3]; /* used in collision.c */
+ unsigned int impulse_count; /* same as above */
+ float avg_spring_len; /* average length of connected springs */
+ float struct_stiff;
+ float bend_stiff;
+ float shear_stiff;
+ int spring_count; /* how many springs attached? */
+}
+ClothVertex;
+
+/**
+ * The definition of a spring.
+ */
+typedef struct ClothSpring
+{
+ int ij; /* Pij from the paper, one end of the spring. */
+ int kl; /* Pkl from the paper, one end of the spring. */
+ float restlen; /* The original length of the spring. */
+ int matrix_index; /* needed for implicit solver (fast lookup) */
+ int type; /* types defined in BKE_cloth.h ("springType") */
+ int flags; /* defined in BKE_cloth.h, e.g. deactivated due to tearing */
+ float dfdx[3][3];
+ float dfdv[3][3];
+ float f[3];
+ float stiffness; /* stiffness factor from the vertex groups */
+ float editrestlen;
+}
+ClothSpring;
+
+// some macro enhancements for vector treatment
+#define VECADDADD(v1,v2,v3) {*(v1)+= *(v2) + *(v3); *(v1+1)+= *(v2+1) + *(v3+1); *(v1+2)+= *(v2+2) + *(v3+2);}
+#define VECSUBADD(v1,v2,v3) {*(v1)-= *(v2) + *(v3); *(v1+1)-= *(v2+1) + *(v3+1); *(v1+2)-= *(v2+2) + *(v3+2);}
+#define VECADDSUB(v1,v2,v3) {*(v1)+= *(v2) - *(v3); *(v1+1)+= *(v2+1) - *(v3+1); *(v1+2)+= *(v2+2) - *(v3+2);}
+#define VECSUBADDSS(v1,v2,aS,v3,bS) {*(v1)-= *(v2)*aS + *(v3)*bS; *(v1+1)-= *(v2+1)*aS + *(v3+1)*bS; *(v1+2)-= *(v2+2)*aS + *(v3+2)*bS;}
+#define VECADDSUBSS(v1,v2,aS,v3,bS) {*(v1)+= *(v2)*aS - *(v3)*bS; *(v1+1)+= *(v2+1)*aS - *(v3+1)*bS; *(v1+2)+= *(v2+2)*aS - *(v3+2)*bS;}
+#define VECADDSS(v1,v2,aS,v3,bS) {*(v1)= *(v2)*aS + *(v3)*bS; *(v1+1)= *(v2+1)*aS + *(v3+1)*bS; *(v1+2)= *(v2+2)*aS + *(v3+2)*bS;}
+#define VECADDS(v1,v2,v3,bS) {*(v1)= *(v2) + *(v3)*bS; *(v1+1)= *(v2+1) + *(v3+1)*bS; *(v1+2)= *(v2+2) + *(v3+2)*bS;}
+#define VECSUBMUL(v1,v2,aS) {*(v1)-= *(v2) * aS; *(v1+1)-= *(v2+1) * aS; *(v1+2)-= *(v2+2) * aS;}
+#define VECSUBS(v1,v2,v3,bS) {*(v1)= *(v2) - *(v3)*bS; *(v1+1)= *(v2+1) - *(v3+1)*bS; *(v1+2)= *(v2+2) - *(v3+2)*bS;}
+#define VECSUBSB(v1,v2, v3,bS) {*(v1)= (*(v2)- *(v3))*bS; *(v1+1)= (*(v2+1) - *(v3+1))*bS; *(v1+2)= (*(v2+2) - *(v3+2))*bS;}
+#define VECMULS(v1,aS) {*(v1)*= aS; *(v1+1)*= aS; *(v1+2)*= *aS;}
+#define VECADDMUL(v1,v2,aS) {*(v1)+= *(v2) * aS; *(v1+1)+= *(v2+1) * aS; *(v1+2)+= *(v2+2) * aS;}
+
+/* SIMULATION FLAGS: goal flags,.. */
+/* These are the bits used in SimSettings.flags. */
+typedef enum
+{
+ CLOTH_SIMSETTINGS_FLAG_COLLOBJ = ( 1 << 2 ),// object is only collision object, no cloth simulation is done
+ CLOTH_SIMSETTINGS_FLAG_GOAL = ( 1 << 3 ), // we have goals enabled
+ CLOTH_SIMSETTINGS_FLAG_TEARING = ( 1 << 4 ),// true if tearing is enabled
+ CLOTH_SIMSETTINGS_FLAG_SCALING = ( 1 << 8 ), /* is advanced scaling active? */
+ CLOTH_SIMSETTINGS_FLAG_CCACHE_EDIT = (1 << 12) /* edit cache in editmode */
+} CLOTH_SIMSETTINGS_FLAGS;
+
+/* COLLISION FLAGS */
+typedef enum
+{
+ CLOTH_COLLSETTINGS_FLAG_ENABLED = ( 1 << 1 ), /* enables cloth - object collisions */
+ CLOTH_COLLSETTINGS_FLAG_SELF = ( 1 << 2 ), /* enables selfcollisions */
+} CLOTH_COLLISIONSETTINGS_FLAGS;
+
+/* Spring types as defined in the paper.*/
+typedef enum
+{
+ CLOTH_SPRING_TYPE_STRUCTURAL = ( 1 << 1 ),
+ CLOTH_SPRING_TYPE_SHEAR = ( 1 << 2 ) ,
+ CLOTH_SPRING_TYPE_BENDING = ( 1 << 3 ),
+ CLOTH_SPRING_TYPE_GOAL = ( 1 << 4 ),
+} CLOTH_SPRING_TYPES;
+
+/* SPRING FLAGS */
+typedef enum
+{
+ CLOTH_SPRING_FLAG_DEACTIVATE = ( 1 << 1 ),
+ CLOTH_SPRING_FLAG_NEEDED = ( 1 << 2 ), // springs has values to be applied
+} CLOTH_SPRINGS_FLAGS;
+
+
+/////////////////////////////////////////////////
+// collision.c
+////////////////////////////////////////////////
+
+// needed for implicit.c
+int cloth_bvh_objcollision ( Object *ob, ClothModifierData * clmd, float step, float dt );
+
+////////////////////////////////////////////////
+
+
+////////////////////////////////////////////////
+// implicit.c
+////////////////////////////////////////////////
+
+// needed for cloth.c
+int implicit_init ( Object *ob, ClothModifierData *clmd );
+int implicit_free ( ClothModifierData *clmd );
+int implicit_solver ( Object *ob, float frame, ClothModifierData *clmd, ListBase *effectors );
+void implicit_set_positions ( ClothModifierData *clmd );
+
+// globally needed
+void clmdSetInterruptCallBack ( int ( *f ) ( void ) );
+////////////////////////////////////////////////
+
+
+/////////////////////////////////////////////////
+// cloth.c
+////////////////////////////////////////////////
+
+// needed for modifier.c
+void cloth_free_modifier_extern ( ClothModifierData *clmd );
+void cloth_free_modifier ( Object *ob, ClothModifierData *clmd );
+void cloth_init ( ClothModifierData *clmd );
+DerivedMesh *clothModifier_do ( ClothModifierData *clmd,Object *ob, DerivedMesh *dm, int useRenderParams, int isFinalCalc );
+
+void cloth_update_normals ( ClothVertex *verts, int nVerts, MFace *face, int totface );
+
+// needed for collision.c
+void bvhtree_update_from_cloth ( ClothModifierData *clmd, int moving );
+void bvhselftree_update_from_cloth ( ClothModifierData *clmd, int moving );
+
+// needed for editmesh.c
+void cloth_write_cache ( Object *ob, ClothModifierData *clmd, float framenr );
+int cloth_read_cache ( Object *ob, ClothModifierData *clmd, float framenr );
+
+// needed for button_object.c
+void cloth_clear_cache ( Object *ob, ClothModifierData *clmd, float framenr );
+
+// needed for cloth.c
+int cloth_add_spring ( ClothModifierData *clmd, unsigned int indexA, unsigned int indexB, float restlength, int spring_type);
+
+////////////////////////////////////////////////
+
+
+/* This enum provides the IDs for our solvers. */
+// only one available in the moment
+typedef enum
+{
+ CM_IMPLICIT = 0,
+} CM_SOLVER_ID;
+
+
+/* This structure defines how to call the solver.
+*/
+typedef struct
+{
+ char *name;
+ CM_SOLVER_ID id;
+ int ( *init ) ( Object *ob, ClothModifierData *clmd );
+ int ( *solver ) ( Object *ob, float framenr, ClothModifierData *clmd, ListBase *effectors );
+ int ( *free ) ( ClothModifierData *clmd );
+}
+CM_SOLVER_DEF;
+
+
+#endif
+
diff --git a/source/blender/blenkernel/BKE_collision.h b/source/blender/blenkernel/BKE_collision.h
new file mode 100644
index 00000000000..c483148e4de
--- /dev/null
+++ b/source/blender/blenkernel/BKE_collision.h
@@ -0,0 +1,150 @@
+/**
+ * BKE_cloth.h
+ *
+ * $Id: BKE_cloth.h,v 1.1 2007/08/01 02:07:27 daniel Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Daniel Genrich
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef BKE_COLLISIONS_H
+#define BKE_COLLISIONS_H
+
+#include <math.h>
+#include <float.h>
+#include <stdlib.h>
+#include <string.h>
+
+/* types */
+#include "BLI_linklist.h"
+#include "BKE_collision.h"
+#include "BKE_customdata.h"
+#include "BKE_DerivedMesh.h"
+#include "DNA_cloth_types.h"
+#include "DNA_customdata_types.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_modifier_types.h"
+#include "DNA_object_types.h"
+
+#include "BLI_kdopbvh.h"
+
+struct Object;
+struct Cloth;
+struct MFace;
+struct DerivedMesh;
+struct ClothModifierData;
+
+////////////////////////////////////////
+// used for collisions in collision.c
+////////////////////////////////////////
+
+/* COLLISION FLAGS */
+typedef enum
+{
+ COLLISION_IN_FUTURE = ( 1 << 1 ),
+} COLLISION_FLAGS;
+
+
+////////////////////////////////////////
+// used for collisions in collision.c
+////////////////////////////////////////
+/* used for collisions in collision.c */
+typedef struct CollPair
+{
+ unsigned int face1; // cloth face
+ unsigned int face2; // object face
+ double distance; // magnitude of vector
+ float normal[3];
+ float vector[3]; // unnormalized collision vector: p2-p1
+ float pa[3], pb[3]; // collision point p1 on face1, p2 on face2
+ int flag;
+ float time; // collision time, from 0 up to 1
+ int ap1, ap2, ap3, bp1, bp2, bp3;
+ int pointsb[4];
+}
+CollPair;
+
+/* used for collisions in collision.c */
+typedef struct EdgeCollPair
+{
+ unsigned int p11, p12, p21, p22;
+ float normal[3];
+ float vector[3];
+ float time;
+ int lastsign;
+ float pa[3], pb[3]; // collision point p1 on face1, p2 on face2
+}
+EdgeCollPair;
+
+/* used for collisions in collision.c */
+typedef struct FaceCollPair
+{
+ unsigned int p11, p12, p13, p21;
+ float normal[3];
+ float vector[3];
+ float time;
+ int lastsign;
+ float pa[3], pb[3]; // collision point p1 on face1, p2 on face2
+}
+FaceCollPair;
+////////////////////////////////////////
+
+
+
+/////////////////////////////////////////////////
+// forward declarations
+/////////////////////////////////////////////////
+
+/////////////////////////////////////////////////
+// used in modifier.c from collision.c
+/////////////////////////////////////////////////
+
+BVHTree *bvhtree_build_from_mvert ( MFace *mfaces, unsigned int numfaces, MVert *x, unsigned int numverts, float epsilon );
+void bvhtree_update_from_mvert ( BVHTree * bvhtree, MFace *faces, int numfaces, MVert *x, MVert *xnew, int numverts, int moving );
+
+/////////////////////////////////////////////////
+
+LinkNode *BLI_linklist_append_fast ( LinkNode **listp, void *ptr );
+
+// move Collision modifier object inter-frame with step = [0,1]
+// defined in collisions.c
+void collision_move_object ( CollisionModifierData *collmd, float step, float prevstep );
+
+// interface for collision functions
+void collisions_compute_barycentric ( float pv[3], float p1[3], float p2[3], float p3[3], float *w1, float *w2, float *w3 );
+void interpolateOnTriangle ( float to[3], float v1[3], float v2[3], float v3[3], double w1, double w2, double w3 );
+
+/////////////////////////////////////////////////
+// used in effect.c
+/////////////////////////////////////////////////
+CollisionModifierData **get_collisionobjects(Object *self, int *numcollobj);
+
+/////////////////////////////////////////////////
+
+
+
+/////////////////////////////////////////////////
+
+#endif
+
diff --git a/source/blender/blenkernel/BKE_colortools.h b/source/blender/blenkernel/BKE_colortools.h
index e78882220a9..555b467b1d6 100644
--- a/source/blender/blenkernel/BKE_colortools.h
+++ b/source/blender/blenkernel/BKE_colortools.h
@@ -57,6 +57,7 @@ void curvemapping_do_ibuf(struct CurveMapping *cumap, struct ImBuf *ibuf);
void curvemapping_premultiply(struct CurveMapping *cumap, int restore);
int curvemapping_RGBA_does_something(struct CurveMapping *cumap);
void curvemapping_initialize(struct CurveMapping *cumap);
+void curvemapping_table_RGBA(struct CurveMapping *cumap, float **array, int *size);
#endif
diff --git a/source/blender/blenkernel/BKE_constraint.h b/source/blender/blenkernel/BKE_constraint.h
index 0b544f20d2a..2f92fadd5ee 100644
--- a/source/blender/blenkernel/BKE_constraint.h
+++ b/source/blender/blenkernel/BKE_constraint.h
@@ -67,7 +67,7 @@ typedef struct bConstraintTypeInfo {
/* admin/ident */
short type; /* CONSTRAINT_TYPE_### */
short size; /* size in bytes of the struct */
- char name[32]; /* name constraint in interface */
+ char name[32]; /* name of constraint in interface */
char structName[32]; /* name of struct for SDNA */
/* data management function pointers - special handling */
@@ -81,8 +81,8 @@ typedef struct bConstraintTypeInfo {
void (*new_data)(void *cdata);
/* target handling function pointers */
- /* for multi-target constraints: return that list; otherwise make a temporary list */
- void (*get_constraint_targets)(struct bConstraint *con, struct ListBase *list);
+ /* for multi-target constraints: return that list; otherwise make a temporary list (returns number of targets) */
+ int (*get_constraint_targets)(struct bConstraint *con, struct ListBase *list);
/* for single-target constraints only: flush data back to source data, and the free memory used */
void (*flush_constraint_targets)(struct bConstraint *con, struct ListBase *list, short nocopy);
@@ -114,6 +114,9 @@ void copy_constraints(struct ListBase *dst, struct ListBase *src);
void relink_constraints(struct ListBase *list);
void free_constraint_data(struct bConstraint *con);
+/* Constraints + Proxies function prototypes */
+void extract_proxylocal_constraints(struct ListBase *dst, struct ListBase *src);
+short proxylocked_constraints_owner(struct Object *ob, struct bPoseChannel *pchan);
/* Constraint Channel function prototypes */
struct bConstraintChannel *get_constraint_channel(struct ListBase *list, const char *name);
@@ -123,6 +126,7 @@ void copy_constraint_channels(struct ListBase *dst, struct ListBase *src);
void clone_constraint_channels(struct ListBase *dst, struct ListBase *src);
void free_constraint_channels(struct ListBase *chanbase);
+
/* Constraint Evaluation function prototypes */
struct bConstraintOb *constraints_make_evalob(struct Object *ob, void *subdata, short datatype);
void constraints_clear_evalob(struct bConstraintOb *cob);
diff --git a/source/blender/blenkernel/BKE_curve.h b/source/blender/blenkernel/BKE_curve.h
index 60444675047..25d6d78c4aa 100644
--- a/source/blender/blenkernel/BKE_curve.h
+++ b/source/blender/blenkernel/BKE_curve.h
@@ -39,9 +39,12 @@ struct ListBase;
struct BezTriple;
struct BevList;
-#define KNOTSU(nu) ( (nu)->orderu+ (nu)->pntsu+ (nu->orderu-1)*((nu)->flagu & 1) )
-#define KNOTSV(nu) ( (nu)->orderv+ (nu)->pntsv+ (nu->orderv-1)*((nu)->flagv & 1) )
+#define KNOTSU(nu) ( (nu)->orderu+ (nu)->pntsu+ (((nu)->flagu & CU_CYCLIC) ? (nu->orderu-1) : 0) )
+#define KNOTSV(nu) ( (nu)->orderv+ (nu)->pntsv+ (((nu)->flagv & CU_CYCLIC) ? (nu->orderv-1) : 0) )
+/* Non cyclic nurbs have 1 less segment */
+#define SEGMENTSU(nu) ( ((nu)->flagu & CU_CYCLIC) ? (nu)->pntsu : (nu)->pntsu-1 )
+#define SEGMENTSV(nu) ( ((nu)->flagv & CU_CYCLIC) ? (nu)->pntsv : (nu)->pntsv-1 )
void unlink_curve( struct Curve *cu);
void free_curve( struct Curve *cu);
@@ -62,15 +65,14 @@ void minmaxNurb( struct Nurb *nu, float *min, float *max);
void makeknots( struct Nurb *nu, short uv, short type);
-void makeNurbfaces( struct Nurb *nu, float *data, int rowstride);
-void makeNurbcurve( struct Nurb *nu, float *data, int resolu, int dim);
+void makeNurbfaces(struct Nurb *nu, float *coord_array, int rowstride);
+void makeNurbcurve(struct Nurb *nu, float *coord_array, float *tilt_array, float *radius_array, int resolu);
void forward_diff_bezier(float q0, float q1, float q2, float q3, float *p, int it, int stride);
float *make_orco_curve( struct Object *ob);
float *make_orco_surf( struct Object *ob);
void makebevelcurve( struct Object *ob, struct ListBase *disp);
void makeBevelList( struct Object *ob);
-float calc_curve_subdiv_radius( struct Curve *cu, struct Nurb *nu, int cursubdiv);
void calchandleNurb( struct BezTriple *bezt, struct BezTriple *prev, struct BezTriple *next, int mode);
void calchandlesNurb( struct Nurb *nu);
@@ -84,5 +86,12 @@ void switchdirectionNurb( struct Nurb *nu);
float (*curve_getVertexCos(struct Curve *cu, struct ListBase *lb, int *numVerts_r))[3];
void curve_applyVertexCos(struct Curve *cu, struct ListBase *lb, float (*vertexCos)[3]);
+/* nurb checks if they can be drawn, also clamp order func */
+int check_valid_nurb_u( struct Nurb *nu);
+int check_valid_nurb_v( struct Nurb *nu);
+
+int clamp_nurb_order_u( struct Nurb *nu);
+int clamp_nurb_order_v( struct Nurb *nu);
+
#endif
diff --git a/source/blender/blenkernel/BKE_customdata.h b/source/blender/blenkernel/BKE_customdata.h
index d0535f1752e..c84b690bc49 100644
--- a/source/blender/blenkernel/BKE_customdata.h
+++ b/source/blender/blenkernel/BKE_customdata.h
@@ -32,14 +32,18 @@
#ifndef BKE_CUSTOMDATA_H
#define BKE_CUSTOMDATA_H
+#include "BLO_sys_types.h" // for intptr_t support
+
struct CustomData;
struct CustomDataLayer;
-typedef long CustomDataMask;
+typedef intptr_t CustomDataMask;
extern const CustomDataMask CD_MASK_BAREMESH;
extern const CustomDataMask CD_MASK_MESH;
extern const CustomDataMask CD_MASK_EDITMESH;
extern const CustomDataMask CD_MASK_DERIVEDMESH;
+extern const CustomDataMask CD_MASK_BMESH;
+extern const CustomDataMask CD_MASK_FACECORNERS;
/* for ORIGINDEX layer type, indicates no original index for this element */
#define ORIGINDEX_NONE -1
@@ -134,6 +138,9 @@ void CustomData_copy_data(const struct CustomData *source,
void CustomData_em_copy_data(const struct CustomData *source,
struct CustomData *dest, void *src_block,
void **dest_block);
+void CustomData_bmesh_copy_data(const struct CustomData *source,
+ struct CustomData *dest,void *src_block,
+ void **dest_block);
/* frees data in a CustomData object
* return 1 on success, 0 on failure
@@ -160,6 +167,10 @@ void CustomData_interp(const struct CustomData *source, struct CustomData *dest,
void CustomData_em_interp(struct CustomData *data, void **src_blocks,
float *weights, float *sub_weights, int count,
void *dest_block);
+void CustomData_bmesh_interp(struct CustomData *data, void **src_blocks,
+ float *weights, float *sub_weights, int count,
+ void *dest_block);
+
/* swaps the data in the element corners, to new corners with indices as
specified in corner_indices. for edges this is an array of length 2, for
@@ -172,6 +183,8 @@ void CustomData_swap(struct CustomData *data, int index, int *corner_indices);
void *CustomData_get(const struct CustomData *data, int index, int type);
void *CustomData_em_get(const struct CustomData *data, void *block, int type);
void *CustomData_em_get_n(const struct CustomData *data, void *block, int type, int n);
+void *CustomData_bmesh_get(const struct CustomData *data, void *block, int type);
+void *CustomData_bmesh_get_n(const struct CustomData *data, void *block, int type, int n);
/* gets a pointer to the active or first layer of type
* returns NULL if there is no layer of type
@@ -199,6 +212,12 @@ void CustomData_em_set(struct CustomData *data, void *block, int type,
void CustomData_em_set_n(struct CustomData *data, void *block, int type, int n,
void *source);
+void CustomData_bmesh_set(const struct CustomData *data, void *block, int type,
+ void *source);
+
+void CustomData_bmesh_set_n(struct CustomData *data, void *block, int type, int n,
+ void *source);
+
/* set the pointer of to the first layer of type. the old data is not freed.
* returns the value of ptr if the layer is found, NULL otherwise
*/
@@ -220,12 +239,20 @@ void CustomData_set_layer_flag(struct CustomData *data, int type, int flag);
void CustomData_em_set_default(struct CustomData *data, void **block);
void CustomData_em_free_block(struct CustomData *data, void **block);
+void CustomData_bmesh_set_default(struct CustomData *data, void **block);
+void CustomData_bmesh_free_block(struct CustomData *data, void **block);
+
/* copy custom data to/from layers as in mesh/derivedmesh, to editmesh
blocks of data. the CustomData's must not be compatible */
void CustomData_to_em_block(const struct CustomData *source,
struct CustomData *dest, int index, void **block);
void CustomData_from_em_block(const struct CustomData *source,
struct CustomData *dest, void *block, int index);
+void CustomData_to_bmesh_block(const struct CustomData *source,
+ struct CustomData *dest, int src_index, void **dest_block);
+void CustomData_from_bmesh_block(const struct CustomData *source,
+ struct CustomData *dest, void *src_block, int dest_index);
+
/* query info over types */
void CustomData_file_write_info(int type, char **structname, int *structnum);
@@ -241,4 +268,8 @@ void CustomData_set_layer_unique_name(struct CustomData *data, int index);
only after this test passes, layer->data should be assigned */
int CustomData_verify_versions(struct CustomData *data, int index);
+/*BMesh specific customdata stuff*/
+void CustomData_to_bmeshpoly(struct CustomData *fdata, struct CustomData *pdata, struct CustomData *ldata);
+void CustomData_from_bmeshpoly(struct CustomData *fdata, struct CustomData *pdata, struct CustomData *ldata, int total);
+void CustomData_bmesh_init_pool(struct CustomData *data, int allocsize);
#endif
diff --git a/source/blender/blenkernel/BKE_deform.h b/source/blender/blenkernel/BKE_deform.h
index a1975dd4265..e982806a6cc 100644
--- a/source/blender/blenkernel/BKE_deform.h
+++ b/source/blender/blenkernel/BKE_deform.h
@@ -38,6 +38,7 @@
struct Object;
struct ListBase;
struct bDeformGroup;
+struct MDeformVert;
void copy_defgroups (struct ListBase *lb1, struct ListBase *lb2);
struct bDeformGroup *copy_defgroup (struct bDeformGroup *ingroup);
@@ -46,5 +47,8 @@ int get_defgroup_num (struct Object *ob, struct bDeformGroup *dg);
int get_named_vertexgroup_num (Object *ob, char *name);
void unique_vertexgroup_name (struct bDeformGroup *dg, struct Object *ob);
+float deformvert_get_weight(const struct MDeformVert *dvert, int group_num);
+float vertexgroup_get_vertex_weight(const struct MDeformVert *dvert, int index, int group_num);
+
#endif
diff --git a/source/blender/blenkernel/BKE_depsgraph.h b/source/blender/blenkernel/BKE_depsgraph.h
index 48a8f8e4ffb..b86a58780dc 100644
--- a/source/blender/blenkernel/BKE_depsgraph.h
+++ b/source/blender/blenkernel/BKE_depsgraph.h
@@ -101,7 +101,7 @@ void DAG_scene_update_flags(struct Scene *sce, unsigned int lay);
void DAG_object_update_flags(struct Scene *sce, struct Object *ob, unsigned int lay);
/* flushes all recalc flags in objects down the dependency tree */
-void DAG_scene_flush_update(struct Scene *sce, unsigned int lay);
+void DAG_scene_flush_update(struct Scene *sce, unsigned int lay, int time);
/* flushes all recalc flags for this object down the dependency tree */
void DAG_object_flush_update(struct Scene *sce, struct Object *ob, short flag);
diff --git a/source/blender/blenkernel/BKE_displist.h b/source/blender/blenkernel/BKE_displist.h
index d6b438a3010..a534dcc3669 100644
--- a/source/blender/blenkernel/BKE_displist.h
+++ b/source/blender/blenkernel/BKE_displist.h
@@ -50,28 +50,6 @@
#define DL_FRONT_CURVE 4
#define DL_BACK_CURVE 8
-#define DL_SURFINDEX(cyclu, cyclv, sizeu, sizev) \
-\
-if( (cyclv)==0 && a==(sizev)-1) break; \
-if(cyclu) { \
- p1= sizeu*a; \
- p2= p1+ sizeu-1; \
- p3= p1+ sizeu; \
- p4= p2+ sizeu; \
- b= 0; \
-} \
-else { \
- p2= sizeu*a; \
- p1= p2+1; \
- p4= p2+ sizeu; \
- p3= p1+ sizeu; \
- b= 1; \
-} \
-if( (cyclv) && a==sizev-1) { \
- p3-= sizeu*sizev; \
- p4-= sizeu*sizev; \
-}
-
/* prototypes */
@@ -114,6 +92,7 @@ extern void makeDispListMBall(struct Object *ob);
extern void shadeDispList(struct Base *base);
extern void shadeMeshMCol(struct Object *ob, struct Mesh *me);
+int surfindex_displist(DispList *dl, int a, int *b, int *p1, int *p2, int *p3, int *p4);
void imagestodisplist(void);
void reshadeall_displist(void);
void filldisplist(struct ListBase *dispbase, struct ListBase *to);
diff --git a/source/blender/blenkernel/BKE_effect.h b/source/blender/blenkernel/BKE_effect.h
index 92aecfaa6f0..6475f7a71ac 100644
--- a/source/blender/blenkernel/BKE_effect.h
+++ b/source/blender/blenkernel/BKE_effect.h
@@ -35,9 +35,9 @@
struct Effect;
struct ListBase;
-struct PartEff;
struct Particle;
struct Group;
+struct RNG;
typedef struct pEffectorCache {
struct pEffectorCache *next, *prev;
@@ -51,25 +51,25 @@ typedef struct pEffectorCache {
Object obcopy; /* for restoring transformation data */
} pEffectorCache;
-
-struct Effect *add_effect(int type);
void free_effect(struct Effect *eff);
void free_effects(struct ListBase *lb);
struct Effect *copy_effect(struct Effect *eff);
-void copy_act_effect(struct Object *ob);
void copy_effects(struct ListBase *lbn, struct ListBase *lb);
void deselectall_eff(struct Object *ob);
-struct PartEff *give_parteff(struct Object *ob);
-void where_is_particle(struct PartEff *paf, struct Particle *pa, float ctime, float *vec);
-void build_particle_system(struct Object *ob);
/* particle deflector */
#define PE_WIND_AS_SPEED 0x00000001
+struct PartEff *give_parteff(struct Object *ob);
struct ListBase *pdInitEffectors(struct Object *obsrc, struct Group *group);
void pdEndEffectors(struct ListBase *lb);
void pdDoEffectors(struct ListBase *lb, float *opco, float *force, float *speed, float cur_time, float loc_time, unsigned int flags);
+/* required for particle_system.c */
+void do_physical_effector(Object *ob, float *opco, short type, float force_val, float distance, float falloff, float size, float damp, float *eff_velocity, float *vec_to_part, float *velocity, float *field, int planar, struct RNG *rng, float noise_factor, float charge, float pa_size);
+float effector_falloff(struct PartDeflect *pd, float *eff_velocity, float *vec_to_part);
+
+
#endif
diff --git a/source/blender/blenkernel/BKE_endian.h b/source/blender/blenkernel/BKE_endian.h
index 1757103eaf6..dc5efd5ea46 100644
--- a/source/blender/blenkernel/BKE_endian.h
+++ b/source/blender/blenkernel/BKE_endian.h
@@ -33,11 +33,11 @@
#define BKE_ENDIANNESS(a) { \
union { \
- long l; \
- char c[sizeof (long)]; \
+ intptr_t l; \
+ char c[sizeof (intptr_t)]; \
} u; \
u.l = 1; \
- a = (u.c[sizeof (long) - 1] == 1) ? 1 : 0; \
+ a = (u.c[sizeof (intptr_t) - 1] == 1) ? 1 : 0; \
}
#endif
diff --git a/source/blender/blenkernel/BKE_fluidsim.h b/source/blender/blenkernel/BKE_fluidsim.h
new file mode 100644
index 00000000000..4aac5eafa00
--- /dev/null
+++ b/source/blender/blenkernel/BKE_fluidsim.h
@@ -0,0 +1,56 @@
+/**
+ * BKE_fluidsim.h
+ *
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "DNA_modifier_types.h"
+#include "DNA_object_fluidsim.h" // N_T
+#include "DNA_object_types.h"
+
+#include "BKE_DerivedMesh.h"
+
+/* old interface */
+FluidsimSettings *fluidsimSettingsNew(Object *srcob);
+
+void initElbeemMesh(Object *ob, int *numVertices, float **vertices, int *numTriangles, int **triangles, int useGlobalCoords, int modifierIndex);
+
+
+/* new fluid-modifier interface */
+void fluidsim_init(FluidsimModifierData *fluidmd);
+void fluidsim_free(FluidsimModifierData *fluidmd);
+
+DerivedMesh *fluidsim_read_cache(Object *ob, DerivedMesh *orgdm, FluidsimModifierData *fluidmd, int framenr, int useRenderParams);
+void fluidsim_read_vel_cache(FluidsimModifierData *fluidmd, DerivedMesh *dm, char *filename);
+DerivedMesh *fluidsimModifier_do(FluidsimModifierData *fluidmd, Object *ob, DerivedMesh *dm, int useRenderParams, int isFinalCalc);
+
+// get bounding box of mesh
+void fluid_get_bb(MVert *mvert, int totvert, float obmat[][4],
+ /*RET*/ float start[3], /*RET*/ float size[3] );
+
+
+
diff --git a/source/blender/blenkernel/BKE_font.h b/source/blender/blenkernel/BKE_font.h
index c840c3d5cfc..3f6b295b9ba 100644
--- a/source/blender/blenkernel/BKE_font.h
+++ b/source/blender/blenkernel/BKE_font.h
@@ -31,6 +31,10 @@
#ifndef BKE_VFONT_H
#define BKE_VFONT_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#include <wchar.h>
struct VFont;
@@ -68,7 +72,11 @@ int getselection(int *start, int *end);
void chtoutf8(unsigned long c, char *o);
void wcs2utf8s(char *dst, wchar_t *src);
int wcsleninu8(wchar_t *src);
-int utf8towchar_(wchar_t *w, char *c);
+int utf8towchar(wchar_t *w, char *c);
+
+#ifdef __cplusplus
+}
+#endif
#endif
diff --git a/source/blender/blenkernel/BKE_global.h b/source/blender/blenkernel/BKE_global.h
index f2929bd8d61..498fd6169b2 100644
--- a/source/blender/blenkernel/BKE_global.h
+++ b/source/blender/blenkernel/BKE_global.h
@@ -61,6 +61,7 @@ struct Object;
struct bSoundListener;
struct BMF_Font;
struct EditMesh;
+struct BME_Glob;
/* former global stuff. context is derived, not storage! */
typedef struct bContext {
@@ -131,6 +132,9 @@ typedef struct Global {
/* Editmode lists */
struct EditMesh *editMesh;
+
+ /* Used for BMesh transformations */
+ struct BME_Glob *editBMesh;
float textcurs[4][2];
@@ -165,6 +169,9 @@ typedef struct Global {
int compat; /* toggle compatibility mode for edge rendering */
int notonlysolid;/* T-> also edge-render transparent faces */
+ /* ndof device found ? */
+ int ndofdevice;
+
/* confusing... G.f and G.flags */
int flags;
@@ -173,10 +180,10 @@ typedef struct Global {
/* **************** GLOBAL ********************* */
/* G.f */
-#define G_DISABLE_OK (1 << 0)
+#define G_RENDER_OGL (1 << 0)
#define G_PLAYANIM (1 << 1)
/* also uses G_FILE_AUTOPLAY */
-#define G_SIMULATION (1 << 3)
+#define G_RENDER_SHADOW (1 << 3)
#define G_BACKBUFSEL (1 << 4)
#define G_PICKSEL (1 << 5)
#define G_DRAWNORMALS (1 << 6)
@@ -191,6 +198,7 @@ typedef struct Global {
#define G_WEIGHTPAINT (1 << 15)
#define G_TEXTUREPAINT (1 << 16)
/* #define G_NOFROZEN (1 << 17) also removed */
+#define G_GREASEPENCIL (1 << 17)
#define G_DRAWEDGES (1 << 18)
#define G_DRAWCREASES (1 << 19)
#define G_DRAWSEAMS (1 << 20)
@@ -200,7 +208,7 @@ typedef struct Global {
#define G_DRAW_FACEAREA (1 << 23)
#define G_DRAW_EDGEANG (1 << 24)
-#define G_RECORDKEYS (1 << 25)
+/* #define G_RECORDKEYS (1 << 25) also removed */
/*#ifdef WITH_VERSE*/
#define G_VERSE_CONNECTED (1 << 26)
#define G_DRAW_VERSE_DEBUG (1 << 27)
@@ -209,8 +217,9 @@ typedef struct Global {
#define G_SCULPTMODE (1 << 29)
#define G_PARTICLEEDIT (1 << 30)
-#define G_AUTOMATKEYS (1 << 30)
+/* #define G_AUTOMATKEYS (1 << 30) also removed */
#define G_HIDDENHANDLES (1 << 31) /* used for curves only */
+#define G_DRAWBWEIGHTS (1 << 31)
/* macro for testing face select mode
* Texture paint could be removed since selected faces are not used
@@ -232,8 +241,15 @@ typedef struct Global {
#define G_FILE_NO_UI (1 << 10)
#define G_FILE_GAME_TO_IPO (1 << 11)
#define G_FILE_GAME_MAT (1 << 12)
-#define G_FILE_DIAPLAY_LISTS (1 << 13)
+#define G_FILE_DISPLAY_LISTS (1 << 13)
#define G_FILE_SHOW_PHYSICS (1 << 14)
+#define G_FILE_GAME_MAT_GLSL (1 << 15)
+#define G_FILE_GLSL_NO_LIGHTS (1 << 16)
+#define G_FILE_GLSL_NO_SHADERS (1 << 17)
+#define G_FILE_GLSL_NO_SHADOWS (1 << 18)
+#define G_FILE_GLSL_NO_RAMPS (1 << 19)
+#define G_FILE_GLSL_NO_NODES (1 << 20)
+#define G_FILE_GLSL_NO_EXTRA_TEX (1 << 21)
/* G.windowstate */
#define G_WINDOWSTATE_USERDEF 0
@@ -280,3 +296,4 @@ extern Global G;
#endif
+
diff --git a/source/blender/blenkernel/BKE_group.h b/source/blender/blenkernel/BKE_group.h
index db2008cfef3..764bdf5d910 100644
--- a/source/blender/blenkernel/BKE_group.h
+++ b/source/blender/blenkernel/BKE_group.h
@@ -41,9 +41,10 @@ void free_group(struct Group *group);
void unlink_group(struct Group *group);
struct Group *add_group(char *name);
void add_to_group(struct Group *group, struct Object *ob);
-void rem_from_group(struct Group *group, struct Object *ob);
-struct Group *find_group(struct Object *ob);
+int rem_from_group(struct Group *group, struct Object *ob);
+struct Group *find_group(struct Object *ob, struct Group *group);
int object_in_group(struct Object *ob, struct Group *group);
+int group_is_animated(struct Object *parent, struct Group *group);
void group_tag_recalc(struct Group *group);
void group_handle_recalc_and_update(struct Object *parent, struct Group *group);
diff --git a/source/blender/blenkernel/BKE_idprop.h b/source/blender/blenkernel/BKE_idprop.h
index 46252b310ae..2274c54ad3b 100644
--- a/source/blender/blenkernel/BKE_idprop.h
+++ b/source/blender/blenkernel/BKE_idprop.h
@@ -46,6 +46,7 @@ struct ID;
typedef union {
int i;
float f;
+ double d;
char *str;
struct ID *id;
struct {
@@ -171,4 +172,9 @@ void IDP_FreeProperty(struct IDProperty *prop);
/*Unlinks any struct IDProperty<->ID linkage that might be going on.*/
void IDP_UnlinkProperty(struct IDProperty *prop);
+#define IDP_Int(prop) (prop->data.val)
+#define IDP_Float(prop) (*(float*)&prop->data.val)
+#define IDP_String(prop) ((char*)prop->data.pointer)
+#define IDP_Array(prop) (prop->data.pointer)
+
#endif /* _BKE_IDPROP_H */
diff --git a/source/blender/blenkernel/BKE_image.h b/source/blender/blenkernel/BKE_image.h
index d1aeb9d8a25..8dac282eedf 100644
--- a/source/blender/blenkernel/BKE_image.h
+++ b/source/blender/blenkernel/BKE_image.h
@@ -44,7 +44,7 @@ struct anim;
void free_image(struct Image *me);
void BKE_stamp_info(struct ImBuf *ibuf);
-void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height);
+void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height, int channels);
int BKE_write_ibuf(struct ImBuf *ibuf, char *name, int imtype, int subimtype, int quality);
void BKE_makepicstring(char *string, char *base, int frame, int imtype);
void BKE_add_image_extension(char *string, int imtype);
@@ -111,7 +111,7 @@ struct ImBuf *BKE_image_get_ibuf(struct Image *ima, struct ImageUser *iuser);
struct Image *BKE_add_image_file(const char *name);
/* adds image, adds ibuf, generates color or pattern */
-struct Image *BKE_add_image_size(int width, int height, char *name, short uvtestgrid, float color[4]);
+struct Image *BKE_add_image_size(int width, int height, char *name, int floatbuf, short uvtestgrid, float color[4]);
/* for reload, refresh, pack */
void BKE_image_signal(struct Image *ima, struct ImageUser *iuser, int signal);
@@ -145,6 +145,9 @@ void BKE_image_all_free_anim_ibufs(int except_frame);
void BKE_image_memorypack(struct Image *ima);
+/* prints memory statistics for images */
+void BKE_image_print_memlist(void);
+
#ifdef __cplusplus
}
#endif
diff --git a/source/blender/blenkernel/BKE_ipo.h b/source/blender/blenkernel/BKE_ipo.h
index 922f3201345..fdd176e0e64 100644
--- a/source/blender/blenkernel/BKE_ipo.h
+++ b/source/blender/blenkernel/BKE_ipo.h
@@ -31,6 +31,10 @@
#ifndef BKE_IPO_H
#define BKE_IPO_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
typedef struct CfraElem {
struct CfraElem *next, *prev;
float cfra;
@@ -50,41 +54,71 @@ struct bPoseChannel;
struct bActionChannel;
struct rctf;
+/* ------------ Time Management ------------ */
+
float frame_to_float(int cfra);
+/* ------------ IPO Management ---------- */
+
void free_ipo_curve(struct IpoCurve *icu);
void free_ipo(struct Ipo *ipo);
+
void ipo_default_v2d_cur(int blocktype, struct rctf *cur);
+
struct Ipo *add_ipo(char *name, int idcode);
struct Ipo *copy_ipo(struct Ipo *ipo);
+
void ipo_idnew(struct Ipo *ipo);
+
+struct IpoCurve *find_ipocurve(struct Ipo *ipo, int adrcode);
+short has_ipo_code(struct Ipo *ipo, int code);
+
+/* -------------- Make Local -------------- */
+
void make_local_obipo(struct Ipo *ipo);
void make_local_matipo(struct Ipo *ipo);
void make_local_keyipo(struct Ipo *ipo);
void make_local_ipo(struct Ipo *ipo);
-struct IpoCurve *find_ipocurve(struct Ipo *ipo, int adrcode);
+
+/* ------------ IPO-Curve Sanity ---------------- */
void calchandles_ipocurve(struct IpoCurve *icu);
void testhandles_ipocurve(struct IpoCurve *icu);
void sort_time_ipocurve(struct IpoCurve *icu);
int test_time_ipocurve(struct IpoCurve *icu);
+
+/* -------- IPO-Curve (Bezier) Calculations ---------- */
+
void correct_bezpart(float *v1, float *v2, float *v3, float *v4);
int findzero(float x, float q0, float q1, float q2, float q3, float *o);
void berekeny(float f1, float f2, float f3, float f4, float *o, int b);
void berekenx(float *f, float *o, int b);
+
+/* -------- IPO Curve Calculation and Evaluation --------- */
+
float eval_icu(struct IpoCurve *icu, float ipotime);
void calc_icu(struct IpoCurve *icu, float ctime);
float calc_ipo_time(struct Ipo *ipo, float ctime);
void calc_ipo(struct Ipo *ipo, float ctime);
+
+/* ------------ Keyframe Column Tools -------------- */
+
+void add_to_cfra_elem(struct ListBase *lb, struct BezTriple *bezt);
+void make_cfra_list(struct Ipo *ipo, struct ListBase *elems);
+
+/* ---------------- IPO DataAPI ----------------- */
+
void write_ipo_poin(void *poin, int type, float val);
float read_ipo_poin(void *poin, int type);
-void *give_mtex_poin(struct MTex *mtex, int adrcode );
-void *get_ipo_poin(struct ID *id, struct IpoCurve *icu, int *type);
+void *give_mtex_poin(struct MTex *mtex, int adrcode );
void *get_pchan_ipo_poin(struct bPoseChannel *pchan, int adrcode);
+void *get_ipo_poin(struct ID *id, struct IpoCurve *icu, int *type);
void set_icu_vars(struct IpoCurve *icu);
+/* ---------------- IPO Execution --------------- */
+
void execute_ipo(struct ID *id, struct Ipo *ipo);
void execute_action_ipo(struct bActionChannel *achan, struct bPoseChannel *pchan);
@@ -95,21 +129,20 @@ void do_ob_ipo(struct Object *ob);
void do_seq_ipo(struct Sequence *seq, int cfra);
void do_ob_ipodrivers(struct Object *ob, struct Ipo *ipo, float ctime);
-int has_ipo_code(struct Ipo *ipo, int code);
void do_all_data_ipos(void);
-int calc_ipo_spec(struct Ipo *ipo, int adrcode, float *ctime);
+short calc_ipo_spec(struct Ipo *ipo, int adrcode, float *ctime);
void clear_delta_obipo(struct Ipo *ipo);
-void add_to_cfra_elem(struct ListBase *lb, struct BezTriple *bezt);
-void make_cfra_list(struct Ipo *ipo, struct ListBase *elems);
-/* the sort is an IPO_Channel... */
-int IPO_GetChannels(struct Ipo *ipo, short *channels);
+/* ----------- IPO <-> GameEngine API ---------------- */
+
+/* the short is an IPO_Channel... */
-float IPO_GetFloatValue(struct Ipo *ipo,
-/* struct IPO_Channel channel, */
- /* channels are shorts... bit ugly for now*/
- short c,
- float ctime);
+short IPO_GetChannels(struct Ipo *ipo, short *channels);
+float IPO_GetFloatValue(struct Ipo *ipo, short c, float ctime);
+
+#ifdef __cplusplus
+};
+#endif
#endif
diff --git a/source/blender/blenkernel/BKE_key.h b/source/blender/blenkernel/BKE_key.h
index a6871aa837f..faf8692b89a 100644
--- a/source/blender/blenkernel/BKE_key.h
+++ b/source/blender/blenkernel/BKE_key.h
@@ -40,6 +40,11 @@ struct Object;
struct Lattice;
struct Mesh;
+/* Kernel prototypes */
+#ifdef __cplusplus
+extern "C" {
+#endif
+
void free_key(struct Key *sc);
struct Key *add_key(struct ID *id);
struct Key *copy_key(struct Key *key);
@@ -57,6 +62,12 @@ int do_ob_key(struct Object *ob);
struct Key *ob_get_key(struct Object *ob);
struct KeyBlock *ob_get_keyblock(struct Object *ob);
struct KeyBlock *key_get_keyblock(struct Key *key, int index);
+// needed for the GE
+void do_rel_key(int start, int end, int tot, char *basispoin, struct Key *key, int mode);
+
+#ifdef __cplusplus
+};
+#endif
#endif
diff --git a/source/blender/blenkernel/BKE_lattice.h b/source/blender/blenkernel/BKE_lattice.h
index 5620674e791..dc7c9dcd5e5 100644
--- a/source/blender/blenkernel/BKE_lattice.h
+++ b/source/blender/blenkernel/BKE_lattice.h
@@ -35,6 +35,7 @@ struct Lattice;
struct Object;
struct DerivedMesh;
struct BPoint;
+struct MDeformVert;
extern struct Lattice *editLatt;
@@ -67,5 +68,7 @@ float (*lattice_getVertexCos(struct Object *ob, int *numVerts_r))[3];
void lattice_applyVertexCos(struct Object *ob, float (*vertexCos)[3]);
void lattice_calc_modifiers(struct Object *ob);
+struct MDeformVert* lattice_get_deform_verts(struct Object *lattice);
+
#endif
diff --git a/source/blender/blenkernel/BKE_main.h b/source/blender/blenkernel/BKE_main.h
index 3b7c3bfbc0a..34ecb2bbba1 100644
--- a/source/blender/blenkernel/BKE_main.h
+++ b/source/blender/blenkernel/BKE_main.h
@@ -44,7 +44,7 @@ struct Library;
typedef struct Main {
struct Main *next, *prev;
- char name[160];
+ char name[240];
short versionfile, subversionfile;
short minversionfile, minsubversionfile;
diff --git a/source/blender/blenkernel/BKE_mball.h b/source/blender/blenkernel/BKE_mball.h
index 7dc70abde97..0dfc8ae6b28 100644
--- a/source/blender/blenkernel/BKE_mball.h
+++ b/source/blender/blenkernel/BKE_mball.h
@@ -91,7 +91,6 @@ typedef struct process { /* parameters, function, storage */
float (*function)(float, float, float);
float size, delta; /* cube size, normal delta */
int bounds; /* cube range within lattice */
- MB_POINT start; /* start point on surface */
CUBES *cubes; /* active cubes */
VERTICES vertices; /* surface vertices */
CENTERLIST **centers; /* cube center hash table */
@@ -151,7 +150,7 @@ void add_cube(PROCESS *mbproc, int i, int j, int k, int count);
void find_first_points(PROCESS *mbproc, struct MetaBall *mb, int a);
void fill_metaball_octal_node(octal_node *node, struct MetaElem *ml, short i);
-void subdivide_metaball_octal_node(octal_node *node, float *size, short depth);
+void subdivide_metaball_octal_node(octal_node *node, float size_x, float size_y, float size_z, short depth);
void free_metaball_octal_node(octal_node *node);
void init_metaball_octal_tree(int depth);
void polygonize(PROCESS *mbproc, struct MetaBall *mb);
@@ -162,8 +161,8 @@ void free_mball(struct MetaBall *mb);
struct MetaBall *add_mball(char *name);
struct MetaBall *copy_mball(struct MetaBall *mb);
void make_local_mball(struct MetaBall *mb);
-void tex_space_mball( struct Object *ob);
-void make_orco_mball( struct Object *ob);
+void tex_space_mball(struct Object *ob);
+float *make_orco_mball(struct Object *ob);
struct Object *find_basis_mball( struct Object *ob);
int is_basis_mball(struct Object *ob);
void metaball_polygonize(struct Object *ob);
diff --git a/source/blender/blenkernel/BKE_mesh.h b/source/blender/blenkernel/BKE_mesh.h
index be7e74bce99..2ca4b3aa39a 100644
--- a/source/blender/blenkernel/BKE_mesh.h
+++ b/source/blender/blenkernel/BKE_mesh.h
@@ -61,14 +61,13 @@ void boundbox_mesh(struct Mesh *me, float *loc, float *size);
void tex_space_mesh(struct Mesh *me);
float *get_mesh_orco_verts(struct Object *ob);
void transform_mesh_orco_verts(struct Mesh *me, float (*orco)[3], int totvert, int invert);
-void test_index_face(struct MFace *mface, struct CustomData *mfdata, int mfindex, int nr);
+int test_index_face(struct MFace *mface, struct CustomData *mfdata, int mfindex, int nr);
struct Mesh *get_mesh(struct Object *ob);
void set_mesh(struct Object *ob, struct Mesh *me);
void mball_to_mesh(struct ListBase *lb, struct Mesh *me);
void nurbs_to_mesh(struct Object *ob);
void free_dverts(struct MDeformVert *dvert, int totvert);
void copy_dverts(struct MDeformVert *dst, struct MDeformVert *src, int totvert); /* __NLA */
-int update_realtime_texture(struct MTFace *tface, double time);
void mesh_delete_material_index(struct Mesh *me, int index);
void mesh_set_smooth_flag(struct Object *meshOb, int enableSmooth);
@@ -93,6 +92,8 @@ float (*mesh_getRefKeyCos(struct Mesh *me, int *numVerts_r))[3];
/* UvVertMap */
+#define STD_UV_CONNECT_LIMIT 0.0001f
+
typedef struct UvVertMap {
struct UvMapVert **vert;
struct UvMapVert *buf;
@@ -101,7 +102,7 @@ typedef struct UvVertMap {
typedef struct UvMapVert {
struct UvMapVert *next;
unsigned int f;
- unsigned char tfindex, separate;
+ unsigned char tfindex, separate, flag;
} UvMapVert;
UvVertMap *make_uv_vert_map(struct MFace *mface, struct MTFace *tface, unsigned int totface, unsigned int totvert, int selected, float *limit);
diff --git a/source/blender/blenkernel/BKE_modifier.h b/source/blender/blenkernel/BKE_modifier.h
index 1b1b00372e7..a41716ed1ff 100644
--- a/source/blender/blenkernel/BKE_modifier.h
+++ b/source/blender/blenkernel/BKE_modifier.h
@@ -284,7 +284,9 @@ int modifiers_getCageIndex(struct Object *ob,
int *lastPossibleCageIndex_r);
int modifiers_isSoftbodyEnabled(struct Object *ob);
+int modifiers_isClothEnabled(struct Object *ob);
int modifiers_isParticleEnabled(struct Object *ob);
+
struct Object *modifiers_isDeformedByArmature(struct Object *ob);
struct Object *modifiers_isDeformedByLattice(struct Object *ob);
int modifiers_usesArmature(struct Object *ob, struct bArmature *arm);
diff --git a/source/blender/blenkernel/BKE_multires.h b/source/blender/blenkernel/BKE_multires.h
index 61eb796e53d..df565ddc7fe 100644
--- a/source/blender/blenkernel/BKE_multires.h
+++ b/source/blender/blenkernel/BKE_multires.h
@@ -61,7 +61,7 @@ void multires_load_cols(struct Mesh *me);
void multires_level_to_mesh(struct Object *ob, struct Mesh *me, const int render);
void multires_update_levels(struct Mesh *me, const int render);
void multires_update_first_level(struct Mesh *me, struct EditMesh *em);
-void multires_update_customdata(struct MultiresLevel *lvl1, struct CustomData *src,
+void multires_update_customdata(struct MultiresLevel *lvl1, struct EditMesh *em, struct CustomData *src,
struct CustomData *dst, const int type);
void multires_customdata_to_mesh(struct Mesh *me, struct EditMesh *em,
struct MultiresLevel *lvl, struct CustomData *src,
diff --git a/source/blender/blenkernel/BKE_node.h b/source/blender/blenkernel/BKE_node.h
index 2ffa1d205da..01c54663c6d 100644
--- a/source/blender/blenkernel/BKE_node.h
+++ b/source/blender/blenkernel/BKE_node.h
@@ -33,7 +33,8 @@
#ifndef BKE_NODE_H
#define BKE_NODE_H
-
+/* not very important, but the stack solver likes to know a maximum */
+#define MAX_SOCKET 64
struct ID;
struct bNodeTree;
@@ -46,6 +47,9 @@ struct rctf;
struct ListBase;
struct RenderData;
struct Scene;
+struct GPUMaterial;
+struct GPUNode;
+struct GPUNodeStack;
#define SOCK_IN 1
#define SOCK_OUT 2
@@ -87,8 +91,11 @@ typedef struct bNodeType {
/* for use with dynamic typedefs */
ID *id;
- void *script; /* holds pointer to python script */
- void *dict; /* holds pointer to python script dictionary (scope)*/
+ void *pynode; /* holds pointer to python script */
+ void *pydict; /* holds pointer to python script dictionary (scope)*/
+
+ /* gpu */
+ int (*gpufunc)(struct GPUMaterial *mat, struct bNode *node, struct GPUNodeStack *in, struct GPUNodeStack *out);
} bNodeType;
@@ -103,13 +110,14 @@ typedef struct bNodeType {
#define NODE_CLASS_INPUT 0
#define NODE_CLASS_OUTPUT 1
#define NODE_CLASS_OP_COLOR 3
-#define NODE_CLASS_OP_VECTOR 4
-#define NODE_CLASS_OP_FILTER 5
+#define NODE_CLASS_OP_VECTOR 4
+#define NODE_CLASS_OP_FILTER 5
#define NODE_CLASS_GROUP 6
#define NODE_CLASS_FILE 7
-#define NODE_CLASS_CONVERTOR 8
+#define NODE_CLASS_CONVERTOR 8
#define NODE_CLASS_MATTE 9
#define NODE_CLASS_DISTORT 10
+#define NODE_CLASS_OP_DYNAMIC 11
/* ************** GENERIC API, TREES *************** */
@@ -119,6 +127,7 @@ struct bNodeTree *ntreeAddTree(int type);
void ntreeInitTypes(struct bNodeTree *ntree);
void ntreeMakeOwnType(struct bNodeTree *ntree);
+void ntreeUpdateType(struct bNodeTree *ntree, struct bNodeType *ntype);
void ntreeFreeTree(struct bNodeTree *ntree);
struct bNodeTree *ntreeCopyTree(struct bNodeTree *ntree, int internal_select);
void ntreeMakeLocal(struct bNodeTree *ntree);
@@ -143,13 +152,21 @@ void nodeVerifyType(struct bNodeTree *ntree, struct bNode *node);
void nodeAddToPreview(struct bNode *, float *, int, int);
-struct bNode *nodeAddNodeType(struct bNodeTree *ntree, int type, struct bNodeTree *ngroup);
+void nodeUnlinkNode(struct bNodeTree *ntree, struct bNode *node);
+void nodeAddSockets(struct bNode *node, struct bNodeType *ntype);
+struct bNode *nodeAddNodeType(struct bNodeTree *ntree, int type, struct bNodeTree *ngroup, struct ID *id);
+void nodeRegisterType(struct ListBase *typelist, const struct bNodeType *ntype) ;
+void nodeUpdateType(struct bNodeTree *ntree, struct bNode* node, struct bNodeType *ntype);
+void nodeMakeDynamicType(struct bNode *node);
+int nodeDynamicUnlinkText(struct ID *txtid);
void nodeFreeNode(struct bNodeTree *ntree, struct bNode *node);
-struct bNode *nodeCopyNode(struct bNodeTree *ntree, struct bNode *node);
+struct bNode *nodeCopyNode(struct bNodeTree *ntree, struct bNode *node, int internal);
struct bNodeLink *nodeAddLink(struct bNodeTree *ntree, struct bNode *fromnode, struct bNodeSocket *fromsock, struct bNode *tonode, struct bNodeSocket *tosock);
void nodeRemLink(struct bNodeTree *ntree, struct bNodeLink *link);
+int nodeFindNode(struct bNodeTree *ntree, struct bNodeSocket *sock, struct bNode **nodep, int *sockindex);
+
struct bNodeLink *nodeFindLink(struct bNodeTree *ntree, struct bNodeSocket *from, struct bNodeSocket *to);
int nodeCountSocketLinks(struct bNodeTree *ntree, struct bNodeSocket *sock);
@@ -169,10 +186,13 @@ int nodeGroupUnGroup(struct bNodeTree *ntree, struct bNode *gnode);
void nodeVerifyGroup(struct bNodeTree *ngroup);
void nodeGroupSocketUseFlags(struct bNodeTree *ngroup);
+void nodeCopyGroup(struct bNode *gnode);
+
/* ************** COMMON NODES *************** */
#define NODE_GROUP 2
#define NODE_GROUP_MENU 1000
+#define NODE_DYNAMIC_MENU 4000
extern bNodeType node_group_typeinfo;
@@ -189,7 +209,7 @@ struct ShadeResult;
#define SH_NODE_OUTPUT 1
#define SH_NODE_MATERIAL 100
-#define SH_NODE_RGB 101
+#define SH_NODE_RGB 101
#define SH_NODE_VALUE 102
#define SH_NODE_MIX_RGB 103
#define SH_NODE_VALTORGB 104
@@ -209,12 +229,21 @@ struct ShadeResult;
#define SH_NODE_SEPRGB 120
#define SH_NODE_COMBRGB 121
#define SH_NODE_HUE_SAT 122
-
+#define NODE_DYNAMIC 123
/* custom defines options for Material node */
#define SH_NODE_MAT_DIFF 1
#define SH_NODE_MAT_SPEC 2
#define SH_NODE_MAT_NEG 4
+/* custom defines: states for Script node. These are bit indices */
+#define NODE_DYNAMIC_READY 0 /* 1 */
+#define NODE_DYNAMIC_LOADED 1 /* 2 */
+#define NODE_DYNAMIC_NEW 2 /* 4 */
+#define NODE_DYNAMIC_UPDATED 3 /* 8 */
+#define NODE_DYNAMIC_ADDEXIST 4 /* 16 */
+#define NODE_DYNAMIC_ERROR 5 /* 32 */
+#define NODE_DYNAMIC_REPARSE 6 /* 64 */
+#define NODE_DYNAMIC_SET 15 /* sign */
/* the type definitions array */
extern struct ListBase node_all_shaders;
@@ -229,25 +258,28 @@ void nodeShaderSynchronizeID(struct bNode *node, int copyto);
extern void (*node_shader_lamp_loop)(struct ShadeInput *, struct ShadeResult *);
void set_node_shader_lamp_loop(void (*lamp_loop_func)(struct ShadeInput *, struct ShadeResult *));
+void ntreeGPUMaterialNodes(struct bNodeTree *ntree, struct GPUMaterial *mat);
+
/* ************** COMPOSITE NODES *************** */
/* output socket defines */
-#define RRES_OUT_IMAGE 0
-#define RRES_OUT_ALPHA 1
-#define RRES_OUT_Z 2
-#define RRES_OUT_NORMAL 3
-#define RRES_OUT_UV 4
-#define RRES_OUT_VEC 5
-#define RRES_OUT_RGBA 6
-#define RRES_OUT_DIFF 7
-#define RRES_OUT_SPEC 8
-#define RRES_OUT_SHADOW 9
-#define RRES_OUT_AO 10
-#define RRES_OUT_REFLECT 11
-#define RRES_OUT_REFRACT 12
-#define RRES_OUT_RADIO 13
-#define RRES_OUT_INDEXOB 14
+#define RRES_OUT_IMAGE 0
+#define RRES_OUT_ALPHA 1
+#define RRES_OUT_Z 2
+#define RRES_OUT_NORMAL 3
+#define RRES_OUT_UV 4
+#define RRES_OUT_VEC 5
+#define RRES_OUT_RGBA 6
+#define RRES_OUT_DIFF 7
+#define RRES_OUT_SPEC 8
+#define RRES_OUT_SHADOW 9
+#define RRES_OUT_AO 10
+#define RRES_OUT_REFLECT 11
+#define RRES_OUT_REFRACT 12
+#define RRES_OUT_RADIO 13
+#define RRES_OUT_INDEXOB 14
+#define RRES_OUT_MIST 15
/* note: types are needed to restore callbacks, don't change values */
#define CMP_NODE_VIEWER 201
@@ -303,6 +335,9 @@ void set_node_shader_lamp_loop(void (*lamp_loop_func)(struct ShadeInput *, str
#define CMP_NODE_INVERT 251
#define CMP_NODE_NORMALIZE 252
#define CMP_NODE_CROP 253
+#define CMP_NODE_DBLUR 254
+#define CMP_NODE_BILATERALBLUR 255
+#define CMP_NODE_PREMULKEY 256
#define CMP_NODE_GLARE 301
#define CMP_NODE_TONEMAP 302
diff --git a/source/blender/blenkernel/BKE_object.h b/source/blender/blenkernel/BKE_object.h
index 69bdcf72550..a4a06b704bc 100644
--- a/source/blender/blenkernel/BKE_object.h
+++ b/source/blender/blenkernel/BKE_object.h
@@ -41,6 +41,7 @@ struct Camera;
struct BoundBox;
struct View3D;
struct SoftBody;
+struct BulletSoftBody;
struct Group;
struct bAction;
@@ -48,6 +49,12 @@ void clear_workob(void);
void copy_baseflags(void);
void copy_objectflags(void);
struct SoftBody *copy_softbody(struct SoftBody *sb);
+struct BulletSoftBody *copy_bulletsoftbody(struct BulletSoftBody *sb);
+void copy_object_particlesystems(struct Object *obn, struct Object *ob);
+void copy_object_softbody(struct Object *obn, struct Object *ob);
+void object_free_particlesystems(struct Object *ob);
+void object_free_softbody(struct Object *ob);
+void object_free_bulletsoftbody(struct Object *ob);
void update_base_layer(struct Object *ob);
void free_object(struct Object *ob);
@@ -81,6 +88,8 @@ void set_field_offs(float field);
void disable_speed_curve(int val);
float bsystem_time(struct Object *ob, float cfra, float ofs);
+void object_scale_to_mat3(struct Object *ob, float mat[][3]);
+void object_rot_to_mat3(struct Object *ob, float mat[][3]);
void object_to_mat3(struct Object *ob, float mat[][3]);
void object_to_mat4(struct Object *ob, float mat[][4]);
@@ -104,12 +113,14 @@ void object_boundbox_flag(struct Object *ob, int flag, int set);
void minmax_object(struct Object *ob, float *min, float *max);
void minmax_object_duplis(struct Object *ob, float *min, float *max);
void solve_tracking (struct Object *ob, float targetmat[][4]);
+int ray_hit_boundbox(struct BoundBox *bb, float ray_start[3], float ray_normal[3]);
void object_handle_update(struct Object *ob);
+float give_timeoffset(struct Object *ob);
+int give_obdata_texspace(struct Object *ob, int **texflag, float **loc, float **size, float **rot);
#ifdef __cplusplus
}
#endif
#endif
-
diff --git a/source/blender/blenkernel/BKE_particle.h b/source/blender/blenkernel/BKE_particle.h
index f64191f3e13..caba63ef8ce 100644
--- a/source/blender/blenkernel/BKE_particle.h
+++ b/source/blender/blenkernel/BKE_particle.h
@@ -38,6 +38,7 @@
struct ParticleSystemModifierData;
struct ParticleSystem;
struct ParticleKey;
+struct ParticleSettings;
struct HairKey;
struct Main;
@@ -46,6 +47,7 @@ struct Object;
struct DerivedMesh;
struct ModifierData;
struct MTFace;
+struct MCol;
struct MFace;
struct MVert;
struct IpoCurve;
@@ -71,6 +73,7 @@ typedef struct ParticleEffectorCache {
short type, psys_nbr;
struct Object obcopy; /* for restoring transformation data */
+ struct RNG *rng; /* random noise generator for e.g. wind */
} ParticleEffectorCache;
typedef struct ParticleReactEvent {
@@ -109,8 +112,8 @@ typedef struct ParticleSeam{
typedef struct ParticleCacheKey{
float co[3];
float vel[3];
- float col[3];
float rot[4];
+ float col[3];
int steps;
} ParticleCacheKey;
@@ -176,6 +179,7 @@ typedef struct ParticleThreadContext {
float *vg_length, *vg_clump, *vg_kink;
float *vg_rough1, *vg_rough2, *vg_roughe;
+ float *vg_effector;
} ParticleThreadContext;
typedef struct ParticleThread {
@@ -207,28 +211,32 @@ int psys_check_enabled(struct Object *ob, struct ParticleSystem *psys);
void psys_free_settings(struct ParticleSettings *part);
void free_child_path_cache(struct ParticleSystem *psys);
void psys_free_path_cache(struct ParticleSystem *psys);
-void free_hair(struct ParticleSystem *psys);
+void free_hair(struct ParticleSystem *psys, int softbody);
void free_keyed_keys(struct ParticleSystem *psys);
void psys_free(struct Object * ob, struct ParticleSystem * psys);
+void psys_free_children(struct ParticleSystem *psys);
-void psys_render_set(struct Object *ob, struct ParticleSystem *psys, float viewmat[][4], float winmat[][4], int winx, int winy);
+void psys_render_set(struct Object *ob, struct ParticleSystem *psys, float viewmat[][4], float winmat[][4], int winx, int winy, int timeoffset);
void psys_render_restore(struct Object *ob, struct ParticleSystem *psys);
int psys_render_simplify_distribution(struct ParticleThreadContext *ctx, int tot);
int psys_render_simplify_params(struct ParticleSystem *psys, struct ChildParticle *cpa, float *params);
-void clear_particles_from_cache(struct Object *ob, struct ParticleSystem *psys, int cfra);
-//void psys_remove_from_particle_list(struct Object *ob, short nbr, struct ParticleSystem *psys);
-
void psys_interpolate_uvs(struct MTFace *tface, int quad, float *uv, float *uvco);
+void psys_interpolate_mcol(struct MCol *mcol, int quad, float *uv, struct MCol *mc);
void copy_particle_key(struct ParticleKey *to, struct ParticleKey *from, int time);
-void psys_particle_on_emitter(struct Object *ob, struct ParticleSystemModifierData *psmd, int distr, int index, int index_dmcache, float *fuv, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor);
+void psys_particle_on_emitter(struct ParticleSystemModifierData *psmd, int distr, int index, int index_dmcache, float *fuv, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor);
struct ParticleSystemModifierData *psys_get_modifier(struct Object *ob, struct ParticleSystem *psys);
struct ParticleSettings *psys_new_settings(char *name, struct Main *main);
struct ParticleSettings *psys_copy_settings(struct ParticleSettings *part);
void psys_flush_settings(struct ParticleSettings *part, int event, int hair_recalc);
+void make_local_particlesettings(struct ParticleSettings *part);
+
+struct LinkNode *psys_using_settings(struct ParticleSettings *part, int flush_update);
+void psys_changed_type(struct ParticleSystem *psys);
+void psys_reset(struct ParticleSystem *psys, int mode);
void psys_find_parents(struct Object *ob, struct ParticleSystemModifierData *psmd, struct ParticleSystem *psys);
@@ -241,8 +249,10 @@ float psys_get_child_time(struct ParticleSystem *psys, struct ChildParticle *cpa
float psys_get_child_size(struct ParticleSystem *psys, struct ChildParticle *cpa, float cfra, float *pa_time);
void psys_get_particle_on_path(struct Object *ob, struct ParticleSystem *psys, int pa_num, struct ParticleKey *state, int vel);
int psys_get_particle_state(struct Object *ob, struct ParticleSystem *psys, int p, struct ParticleKey *state, int always);
+void psys_get_dupli_texture(struct Object *ob, struct ParticleSettings *part, struct ParticleSystemModifierData *psmd, struct ParticleData *pa, struct ChildParticle *cpa, float *uv, float *orco);
+void psys_get_dupli_path_transform(struct Object *ob, struct ParticleSystem *psys, struct ParticleSystemModifierData *psmd, struct ParticleData *pa, struct ChildParticle *cpa, struct ParticleCacheKey *cache, float mat[][4], float *scale);
-ParticleThread *psys_threads_create(struct Object *ob, struct ParticleSystem *psys, int totthread);
+ParticleThread *psys_threads_create(struct Object *ob, struct ParticleSystem *psys);
int psys_threads_init_distribution(ParticleThread *threads, struct DerivedMesh *dm, int from);
int psys_threads_init_path(ParticleThread *threads, float cfra, int editupdate);
void psys_threads_free(ParticleThread *threads);
@@ -274,19 +284,28 @@ void psys_mat_hair_to_orco(struct Object *ob, struct DerivedMesh *dm, short from
float *psys_cache_vgroup(struct DerivedMesh *dm, struct ParticleSystem *psys, int vgroup);
void psys_get_texture(struct Object *ob, struct Material *ma, struct ParticleSystemModifierData *psmd, struct ParticleSystem *psys, struct ParticleData *pa, struct ParticleTexture *ptex, int event);
void psys_interpolate_face(struct MVert *mvert, struct MFace *mface, struct MTFace *tface, float (*orcodata)[3], float *uv, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor);
+float psys_particle_value_from_verts(struct DerivedMesh *dm, short from, struct ParticleData *pa, float *values);
float psys_interpolate_value_from_verts(struct DerivedMesh *dm, short from, int index, float *fw, float *values);
void psys_get_from_key(struct ParticleKey *key, float *loc, float *vel, float *rot, float *time);
int psys_intersect_dm(struct Object *ob, struct DerivedMesh *dm, float *vert_cos, float *co1, float* co2, float *min_d, int *min_face, float *min_uv, float *face_minmax, float *pa_minmax, float radius, float *ipoint);
-void psys_particle_on_dm(struct Object *ob, struct DerivedMesh *dm, int from, int index, int index_dmcache, float *fw, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor);
+void psys_particle_on_dm(struct DerivedMesh *dm, int from, int index, int index_dmcache, float *fw, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor);
/* particle_system.c */
void initialize_particle(struct ParticleData *pa, int p, struct Object *ob, struct ParticleSystem *psys, struct ParticleSystemModifierData *psmd);
void reset_particle(struct ParticleData *pa, struct ParticleSystem *psys, struct ParticleSystemModifierData *psmd, struct Object *ob, float dtime, float cfra, float *vg_vel, float *vg_tan, float *vg_rot);
-void psys_calc_dmfaces(struct Object *ob, struct DerivedMesh *dm, struct ParticleSystem *psys);
+void do_effectors(int pa_no, struct ParticleData *pa, struct ParticleKey *state, struct Object *ob, struct ParticleSystem *psys, float *texco, float *force_field, float *vel,float framestep, float cfra);
+
+void psys_calc_dmcache(struct Object *ob, struct DerivedMesh *dm, struct ParticleSystem *psys);
int psys_particle_dm_face_lookup(struct Object *ob, struct DerivedMesh *dm, int index, float *fw, struct LinkNode *node);
+/* psys_reset */
+#define PSYS_RESET_ALL 1
+#define PSYS_RESET_DEPSGRAPH 2
+#define PSYS_RESET_CHILDREN 3
+#define PSYS_RESET_CACHE_MISS 4
+
/* ParticleEffectorCache->type */
#define PSYS_EC_EFFECTOR 1
#define PSYS_EC_DEFLECT 2
diff --git a/source/blender/blenkernel/BKE_plugin_types.h b/source/blender/blenkernel/BKE_plugin_types.h
index d6b91212d8f..fe5aafe5874 100644
--- a/source/blender/blenkernel/BKE_plugin_types.h
+++ b/source/blender/blenkernel/BKE_plugin_types.h
@@ -36,7 +36,8 @@
struct ImBuf;
-typedef int (*TexDoit)(int, void*, float*, float*, float*);
+typedef int (*TexDoitold)(int stype, void *cast, float *texvec, float *dxt, float *dyt);
+typedef int (*TexDoit)(int stype, void *cast, float *texvec, float *dxt, float *dyt, float *result );
typedef void (*SeqDoit)(void*, float, float, int, int,
struct ImBuf*, struct ImBuf*,
struct ImBuf*, struct ImBuf*);
@@ -60,7 +61,7 @@ typedef struct _PluginInfo {
void (*init)(void);
void (*callback)(int);
- TexDoit tex_doit;
+ void (*tex_doit)(void *);
SeqDoit seq_doit;
void (*instance_init)(void *);
} PluginInfo;
diff --git a/source/blender/blenkernel/BKE_pointcache.h b/source/blender/blenkernel/BKE_pointcache.h
index 52cc0ddcaa7..5bc467465a8 100644
--- a/source/blender/blenkernel/BKE_pointcache.h
+++ b/source/blender/blenkernel/BKE_pointcache.h
@@ -31,25 +31,84 @@
#include "DNA_ID.h"
-/* options for clearing pointcache - used for BKE_ptcache_id_clear
- Before and after are non inclusive (they wont remove the cfra) */
+/* Point cache clearing option, for BKE_ptcache_id_clear, before
+ * and after are non inclusive (they wont remove the cfra) */
#define PTCACHE_CLEAR_ALL 0
#define PTCACHE_CLEAR_FRAME 1
#define PTCACHE_CLEAR_BEFORE 2
#define PTCACHE_CLEAR_AFTER 3
+/* Point cache reset options */
+#define PTCACHE_RESET_DEPSGRAPH 0
+#define PTCACHE_RESET_BAKED 1
+#define PTCACHE_RESET_OUTDATED 2
+
/* Add the blendfile name after blendcache_ */
#define PTCACHE_EXT ".bphys"
-#define PTCACHE_PATH "//blendcache_"
+#define PTCACHE_PATH "blendcache_"
+
+/* File open options, for BKE_ptcache_file_open */
+#define PTCACHE_FILE_READ 0
+#define PTCACHE_FILE_WRITE 1
+
+/* PTCacheID types */
+#define PTCACHE_TYPE_SOFTBODY 0
+#define PTCACHE_TYPE_PARTICLES 1
+#define PTCACHE_TYPE_CLOTH 2
+
+/* Structs */
+struct Object;
+struct SoftBody;
+struct ParticleSystem;
+struct ClothModifierData;
+struct PointCache;
+struct ListBase;
+
+typedef struct PTCacheFile {
+ FILE *fp;
+} PTCacheFile;
+
+typedef struct PTCacheID {
+ struct PTCacheID *next, *prev;
+
+ struct Object *ob;
+ void *data;
+ int type;
+ int stack_index;
+
+ struct PointCache *cache;
+} PTCacheID;
+
+/* Creating ID's */
+void BKE_ptcache_id_from_softbody(PTCacheID *pid, struct Object *ob, struct SoftBody *sb);
+void BKE_ptcache_id_from_particles(PTCacheID *pid, struct Object *ob, struct ParticleSystem *psys);
+void BKE_ptcache_id_from_cloth(PTCacheID *pid, struct Object *ob, struct ClothModifierData *clmd);
+
+void BKE_ptcache_ids_from_object(struct ListBase *lb, struct Object *ob);
/* Global funcs */
-/* void BKE_ptcache_clean(void); - not implimented yet! */
+void BKE_ptcache_remove(void);
+
+/* ID specific functions */
+void BKE_ptcache_id_clear(PTCacheID *id, int mode, int cfra);
+int BKE_ptcache_id_exist(PTCacheID *id, int cfra);
+int BKE_ptcache_id_reset(PTCacheID *id, int mode);
+void BKE_ptcache_id_time(PTCacheID *pid, float cfra, int *startframe, int *endframe, float *timescale);
+int BKE_ptcache_object_reset(struct Object *ob, int mode);
+
+/* File reading/writing */
+PTCacheFile *BKE_ptcache_file_open(PTCacheID *id, int mode, int cfra);
+void BKE_ptcache_file_close(PTCacheFile *pf);
+int BKE_ptcache_file_read_floats(PTCacheFile *pf, float *f, int tot);
+int BKE_ptcache_file_write_floats(PTCacheFile *pf, float *f, int tot);
+/* Continue physics */
+void BKE_ptcache_set_continue_physics(int enable);
+int BKE_ptcache_get_continue_physics(void);
-/* Object spesific funcs */
-int BKE_ptcache_id_filename(struct ID *id, char *filename, int cfra, int stack_index, short do_path, short do_ext);
-FILE * BKE_ptcache_id_fopen(struct ID *id, char mode, int cfra, int stack_index);
-void BKE_ptcache_id_clear(struct ID *id, char mode, int cfra, int stack_index);
-int BKE_ptcache_id_exist(struct ID *id, int cfra, int stack_index);
+/* Point Cache */
+struct PointCache *BKE_ptcache_add(void);
+void BKE_ptcache_free(struct PointCache *cache);
+struct PointCache *BKE_ptcache_copy(struct PointCache *cache);
#endif
diff --git a/source/blender/blenkernel/BKE_property.h b/source/blender/blenkernel/BKE_property.h
index f1587790c4a..6af1deda727 100644
--- a/source/blender/blenkernel/BKE_property.h
+++ b/source/blender/blenkernel/BKE_property.h
@@ -41,7 +41,8 @@ struct bProperty *copy_property(struct bProperty *prop);
void copy_properties(struct ListBase *lbn, struct ListBase *lbo);
void init_property(struct bProperty *prop);
struct bProperty *new_property(int type);
-struct bProperty *get_property(struct Object *ob, char *name);
+struct bProperty *get_ob_property(struct Object *ob, char *name);
+void set_ob_property(struct Object *ob, struct bProperty *propc);
int compare_property(struct bProperty *prop, char *str);
void set_property(struct bProperty *prop, char *str);
void add_property(struct bProperty *prop, char *str);
diff --git a/source/blender/blenkernel/BKE_scene.h b/source/blender/blenkernel/BKE_scene.h
index bdc98f2817b..35168cb65f2 100644
--- a/source/blender/blenkernel/BKE_scene.h
+++ b/source/blender/blenkernel/BKE_scene.h
@@ -31,11 +31,14 @@
#ifndef BKE_SCENE_H
#define BKE_SCENE_H
+struct bglMats;
struct Scene;
struct Object;
struct Base;
struct AviCodecData;
struct QuicktimeCodecData;
+struct SculptData;
+struct RenderData;
/* sequence related defines */
@@ -51,7 +54,7 @@ struct QuicktimeCodecData;
}
/* note; doesn't work when scene is empty */
-#define SETLOOPER(s, b) sce= s, b= sce->base.first; b; b= (b->next?b->next:sce->set?(sce=sce->set)->base.first:NULL)
+#define SETLOOPER(s, b) sce= s, b= (Base*)sce->base.first; b; b= (Base*)(b->next?b->next:sce->set?(sce=sce->set)->base.first:NULL)
void free_avicodecdata(struct AviCodecData *acd);
@@ -78,5 +81,11 @@ void scene_update_for_newframe(struct Scene *sce, unsigned int lay);
void scene_add_render_layer(struct Scene *sce);
+/* render profile */
+int get_render_subsurf_level(struct RenderData *r, int level);
+int get_render_child_particle_number(struct RenderData *r, int num);
+int get_render_shadow_samples(struct RenderData *r, int samples);
+float get_render_aosss_error(struct RenderData *r, float error);
+
#endif
diff --git a/source/blender/blenkernel/BKE_screen.h b/source/blender/blenkernel/BKE_screen.h
index ebaf85a58f9..129093f6078 100644
--- a/source/blender/blenkernel/BKE_screen.h
+++ b/source/blender/blenkernel/BKE_screen.h
@@ -8,7 +8,7 @@
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
+ * of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
diff --git a/source/blender/blenkernel/BKE_sculpt.h b/source/blender/blenkernel/BKE_sculpt.h
index d539bcf5e8c..5d7ed28f561 100644
--- a/source/blender/blenkernel/BKE_sculpt.h
+++ b/source/blender/blenkernel/BKE_sculpt.h
@@ -31,30 +31,11 @@
#define BKE_SCULPT_H
struct NumInput;
+struct RadialControl;
struct Scene;
struct SculptData;
struct SculptSession;
-typedef enum PropsetMode {
- PropsetNone = 0,
- PropsetSize,
- PropsetStrength,
- PropsetTexRot
-} PropsetMode;
-
-typedef struct PropsetData {
- PropsetMode mode;
- unsigned int tex;
- short origloc[2];
- float *texdata;
-
- short origsize;
- char origstrength;
- float origtexrot;
-
- struct NumInput *num;
-} PropsetData;
-
typedef struct SculptSession {
struct ProjVert *projverts;
@@ -76,11 +57,8 @@ typedef struct SculptSession {
/* Used to cache the render of the active texture */
unsigned int texcache_w, texcache_h, *texcache;
- struct PropsetData *propset;
+ struct RadialControl *radialcontrol;
- /* For rotating around a pivot point */
- vec3f pivot;
-
struct SculptStroke *stroke;
} SculptSession;
diff --git a/source/blender/blenkernel/BKE_shrinkwrap.h b/source/blender/blenkernel/BKE_shrinkwrap.h
new file mode 100644
index 00000000000..eed22ff9d8e
--- /dev/null
+++ b/source/blender/blenkernel/BKE_shrinkwrap.h
@@ -0,0 +1,150 @@
+/**
+ * BKE_shrinkwrap.h
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef BKE_SHRINKWRAP_H
+#define BKE_SHRINKWRAP_H
+
+/* mesh util */
+//TODO: move this somewhere else
+#include "BKE_customdata.h"
+struct DerivedMesh;
+struct Object;
+struct DerivedMesh *object_get_derived_final(struct Object *ob, CustomDataMask dataMask);
+
+
+/* SpaceTransform stuff */
+/*
+ * TODO: move this somewhere else
+ *
+ * this structs encapsulates all needed data to convert between 2 coordinate spaces
+ * (where conversion can be represented by a matrix multiplication)
+ *
+ * This is used to reduce the number of arguments to pass to functions that need to perform
+ * this kind of operation and make it easier for the coder, as he/she doenst needs to recode
+ * the matrix calculation.
+ *
+ * A SpaceTransform is initialized using:
+ * space_transform_setup( &data, ob1, ob2 )
+ *
+ * After that the following calls can be used:
+ * space_transform_apply (&data, co); //converts a coordinate in ob1 coords space to the corresponding ob2 coords
+ * space_transform_invert(&data, co); //converts a coordinate in ob2 coords space to the corresponding ob1 coords
+ *
+ * //Same Concept as space_transform_apply and space_transform_invert, but no is normalized after conversion
+ * space_transform_apply_normal (&data, &no);
+ * space_transform_invert_normal(&data, &no);
+ *
+ */
+struct Object;
+
+typedef struct SpaceTransform
+{
+ float local2target[4][4];
+ float target2local[4][4];
+
+} SpaceTransform;
+
+void space_transform_from_matrixs(SpaceTransform *data, float local[][4], float target[][4]);
+#define space_transform_setup(data, local, target) space_transform_from_matrixs(data, (local)->obmat, (target)->obmat)
+
+void space_transform_apply (const SpaceTransform *data, float *co);
+void space_transform_invert(const SpaceTransform *data, float *co);
+
+void space_transform_apply_normal (const SpaceTransform *data, float *no);
+void space_transform_invert_normal(const SpaceTransform *data, float *no);
+
+/* Shrinkwrap stuff */
+#include "BKE_bvhutils.h"
+
+/*
+ * Shrinkwrap is composed by a set of functions and options that define the type of shrink.
+ *
+ * 3 modes are available:
+ * - Nearest vertex
+ * - Nearest surface
+ * - Normal projection
+ *
+ * ShrinkwrapCalcData encapsulates all needed data for shrinkwrap functions.
+ * (So that you dont have to pass an enormous ammount of arguments to functions)
+ */
+
+struct Object;
+struct DerivedMesh;
+struct ShrinkwrapModifierData;
+struct MDeformVert;
+struct BVHTree;
+
+
+typedef struct ShrinkwrapCalcData
+{
+ ShrinkwrapModifierData *smd; //shrinkwrap modifier data
+
+ struct Object *ob; //object we are applying shrinkwrap to
+ struct DerivedMesh *original; //mesh before shrinkwrap
+
+ float (*vertexCos)[3]; //vertexs being shrinkwraped
+ int numVerts;
+
+ struct MDeformVert* dvert; //Pointer to mdeform array
+ int vgroup; //Vertex group num
+
+ struct DerivedMesh *target; //mesh we are shrinking to
+ SpaceTransform local2target; //transform to move bettwem local and target space
+
+ float keepDist; //Distance to kept from target (units are in local space)
+
+} ShrinkwrapCalcData;
+
+void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *data);
+void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *data);
+void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *data);
+
+void shrinkwrapModifier_deform(struct ShrinkwrapModifierData *smd, struct Object *ob, struct DerivedMesh *dm, float (*vertexCos)[3], int numVerts);
+
+/*
+ * This function casts a ray in the given BVHTree.. but it takes into consideration the space_transform, that is:
+ *
+ * if transf was configured with "space_transform_setup( &transf, ob1, ob2 )"
+ * then the input (vert, dir, BVHTreeRayHit) must be defined in ob1 coordinates space
+ * and the BVHTree must be built in ob2 coordinate space.
+ *
+ * Thus it provides an easy way to cast the same ray across several trees (where each tree was built on its own coords space)
+ */
+int normal_projection_project_vertex(char options, const float *vert, const float *dir, const SpaceTransform *transf, BVHTree *tree, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata);
+
+/*
+ * NULL initializers to local data
+ */
+#define NULL_ShrinkwrapCalcData {NULL, }
+#define NULL_BVHTreeFromMesh {NULL, }
+#define NULL_BVHTreeRayHit {NULL, }
+#define NULL_BVHTreeNearest {0, }
+
+
+#endif
+
diff --git a/source/blender/blenkernel/BKE_simple_deform.h b/source/blender/blenkernel/BKE_simple_deform.h
new file mode 100644
index 00000000000..161871a64bc
--- /dev/null
+++ b/source/blender/blenkernel/BKE_simple_deform.h
@@ -0,0 +1,39 @@
+/**
+ * BKE_shrinkwrap.h
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef BKE_SIMPLE_DEFORM_H
+#define BKE_SIMPLE_DEFORM_H
+
+struct Object;
+struct DerivedMesh;
+struct SimpleDeformModifierData;
+
+void SimpleDeformModifier_do(SimpleDeformModifierData *smd, struct Object *ob, struct DerivedMesh *dm, float (*vertexCos)[3], int numVerts);
+
+#endif
+
diff --git a/source/blender/blenkernel/BKE_softbody.h b/source/blender/blenkernel/BKE_softbody.h
index b11585b47fb..1756734813b 100644
--- a/source/blender/blenkernel/BKE_softbody.h
+++ b/source/blender/blenkernel/BKE_softbody.h
@@ -38,8 +38,9 @@ typedef struct BodyPoint {
float origS[3], origE[3], origT[3], pos[3], vec[3], force[3];
float goal;
float prevpos[3], prevvec[3], prevdx[3], prevdv[3]; /* used for Heun integration */
+ float impdv[3],impdx[3];
int nofsprings; int *springs;
- float choke;
+ float choke,choke2,frozen;
float colball;
short flag;
char octantflag;
@@ -51,7 +52,8 @@ extern struct SoftBody *sbNew(void);
/* frees internal data and softbody itself */
extern void sbFree(struct SoftBody *sb);
-extern void softbody_clear_cache(struct Object *ob, float framenr);
+/* frees simulation data to reset simulation */
+extern void sbFreeSimulation(struct SoftBody *sb);
/* do one simul step, reading and writing vertex locs from given array */
extern void sbObjectStep(struct Object *ob, float framnr, float (*vertexCos)[3], int numVerts);
@@ -63,6 +65,8 @@ extern void sbObjectToSoftbody(struct Object *ob);
/* pass NULL to unlink again */
extern void sbSetInterruptCallBack(int (*f)(void));
+/* writing to cache for bake editing */
+extern void sbWriteCache(struct Object *ob, int framenr);
#endif
diff --git a/source/blender/blenkernel/BKE_suggestions.h b/source/blender/blenkernel/BKE_suggestions.h
new file mode 100644
index 00000000000..d58b8f58bf5
--- /dev/null
+++ b/source/blender/blenkernel/BKE_suggestions.h
@@ -0,0 +1,93 @@
+/**
+ * $Id: $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2008, Blender Foundation
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef BKE_SUGGESTIONS_H
+#define BKE_SUGGESTIONS_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* ****************************************************************************
+Suggestions should be added in sorted order although a linear sorting method is
+implemented. The list is then divided up based on the prefix provided by
+update_suggestions:
+
+Example:
+ Prefix: ab
+ aaa <-- first
+ aab
+ aba <-- firstmatch
+ abb <-- lastmatch
+ baa
+ bab <-- last
+**************************************************************************** */
+
+struct Text;
+
+typedef struct SuggItem {
+ struct SuggItem *prev, *next;
+ char *name;
+ char type;
+} SuggItem;
+
+typedef struct SuggList {
+ SuggItem *first, *last;
+ SuggItem *firstmatch, *lastmatch;
+ SuggItem *selected;
+ int top;
+} SuggList;
+
+/* Free all text tool memory */
+void free_texttools();
+
+/* Used to identify which Text object the current tools should appear against */
+void texttool_text_set_active(Text *text);
+void texttool_text_clear();
+short texttool_text_is_active(Text *text);
+
+/* Suggestions */
+void texttool_suggest_add(const char *name, char type);
+void texttool_suggest_prefix(const char *prefix);
+void texttool_suggest_clear();
+SuggItem *texttool_suggest_first();
+SuggItem *texttool_suggest_last();
+void texttool_suggest_select(SuggItem *sel);
+SuggItem *texttool_suggest_selected();
+int *texttool_suggest_top();
+
+/* Documentation */
+void texttool_docs_show(const char *docs);
+char *texttool_docs_get();
+void texttool_docs_clear();
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/source/blender/blenkernel/BKE_text.h b/source/blender/blenkernel/BKE_text.h
index 370a19304fe..002c804f17f 100644
--- a/source/blender/blenkernel/BKE_text.h
+++ b/source/blender/blenkernel/BKE_text.h
@@ -52,20 +52,24 @@ void txt_free_cut_buffer (void);
char* txt_to_buf (struct Text *text);
void txt_clean_text (struct Text *text);
void txt_order_cursors (struct Text *text);
-int txt_find_string (struct Text *text, char *findstr);
+int txt_find_string (struct Text *text, char *findstr, int wrap);
int txt_has_sel (struct Text *text);
int txt_get_span (struct TextLine *from, struct TextLine *to);
void txt_move_up (struct Text *text, short sel);
void txt_move_down (struct Text *text, short sel);
void txt_move_left (struct Text *text, short sel);
void txt_move_right (struct Text *text, short sel);
+void txt_jump_left (struct Text *text, short sel);
+void txt_jump_right (struct Text *text, short sel);
void txt_move_bof (struct Text *text, short sel);
void txt_move_eof (struct Text *text, short sel);
void txt_move_bol (struct Text *text, short sel);
void txt_move_eol (struct Text *text, short sel);
void txt_move_toline (struct Text *text, unsigned int line, short sel);
+void txt_move_to (struct Text *text, unsigned int line, unsigned int ch, short sel);
void txt_pop_sel (struct Text *text);
void txt_delete_char (struct Text *text);
+void txt_delete_word (struct Text *text);
void txt_copy_sel (struct Text *text);
void txt_sel_all (struct Text *text);
void txt_sel_line (struct Text *text);
@@ -80,8 +84,10 @@ void txt_do_undo (struct Text *text);
void txt_do_redo (struct Text *text);
void txt_split_curline (struct Text *text);
void txt_backspace_char (struct Text *text);
+void txt_backspace_word (struct Text *text);
int txt_add_char (struct Text *text, char add);
-void txt_find_panel (struct SpaceText *st, int again);
+int txt_replace_char (struct Text *text, char add);
+void find_and_replace (struct SpaceText *st, short mode);
void run_python_script (struct SpaceText *st);
int jumptoline_interactive (struct SpaceText *st);
void txt_export_to_object (struct Text *text);
@@ -92,6 +98,18 @@ void indent (struct Text *text);
void uncomment (struct Text *text);
int setcurr_tab (struct Text *text);
void convert_tabs (struct SpaceText *st, int tab);
+void txt_copy_clipboard (struct Text *text);
+void txt_paste_clipboard (struct Text *text);
+
+void txt_add_marker (struct Text *text, struct TextLine *line, int start, int end, char color[4], int group, int flags);
+short txt_clear_marker_region (struct Text *text, struct TextLine *line, int start, int end, int group, int flags);
+short txt_clear_markers (struct Text *text, int group, int flags);
+struct TextMarker *txt_find_marker (struct Text *text, struct TextLine *line, int curs, int group, int flags);
+struct TextMarker *txt_find_marker_region (struct Text *text, struct TextLine *line, int start, int end, int group, int flags);
+struct TextMarker *txt_prev_marker (struct Text *text, struct TextMarker *marker);
+struct TextMarker *txt_next_marker (struct Text *text, struct TextMarker *marker);
+struct TextMarker *txt_prev_marker_color (struct Text *text, struct TextMarker *marker);
+struct TextMarker *txt_next_marker_color (struct Text *text, struct TextMarker *marker);
/* Undo opcodes */
@@ -134,6 +152,14 @@ void convert_tabs (struct SpaceText *st, int tab);
#define UNDO_COMMENT 034
#define UNDO_UNCOMMENT 035
+/* Find and replace flags */
+#define TXT_FIND_WRAP 0x01
+#define TXT_FIND_ALLTEXTS 0x02
+
+/* Marker flags */
+#define TMARK_TEMP 0x01 /* Remove on non-editing events, don't save */
+#define TMARK_EDITALL 0x02 /* Edit all markers of the same group as one */
+
#ifdef __cplusplus
}
#endif
diff --git a/source/blender/blenkernel/BKE_texture.h b/source/blender/blenkernel/BKE_texture.h
index 78a8f60caeb..cfcae3c44bc 100644
--- a/source/blender/blenkernel/BKE_texture.h
+++ b/source/blender/blenkernel/BKE_texture.h
@@ -53,6 +53,7 @@ void free_plugin_tex(struct PluginTex *pit);
void init_colorband(struct ColorBand *coba, int rangetype);
struct ColorBand *add_colorband(int rangetype);
int do_colorband(struct ColorBand *coba, float in, float out[4]);
+void colorband_table_RGBA(struct ColorBand *coba, float **array, int *size);
void default_tex(struct Tex *tex);
struct Tex *add_texture(char *name);
@@ -62,6 +63,7 @@ struct Tex *copy_texture(struct Tex *tex);
void make_local_texture(struct Tex *tex);
void autotexname(struct Tex *tex);
struct Tex *give_current_texture(struct Object *ob, int act);
+struct Tex *give_current_world_texture(void);
struct TexMapping *add_mapping(void);
void init_mapping(struct TexMapping *texmap);
@@ -72,6 +74,7 @@ void BKE_free_envmap(struct EnvMap *env);
struct EnvMap *BKE_add_envmap(void);
struct EnvMap *BKE_copy_envmap(struct EnvMap *env);
+int BKE_texture_dependsOnTime(const struct Tex *texture);
#endif
diff --git a/source/blender/blenkernel/BKE_utildefines.h b/source/blender/blenkernel/BKE_utildefines.h
index 50e3f487171..6584af085cd 100644
--- a/source/blender/blenkernel/BKE_utildefines.h
+++ b/source/blender/blenkernel/BKE_utildefines.h
@@ -55,6 +55,8 @@
#define ELEM7(a, b, c, d, e, f, g, h) ( ELEM3(a, b, c, d) || ELEM4(a, e, f, g, h) )
#define ELEM8(a, b, c, d, e, f, g, h, i) ( ELEM4(a, b, c, d, e) || ELEM4(a, f, g, h, i) )
#define ELEM9(a, b, c, d, e, f, g, h, i, j) ( ELEM4(a, b, c, d, e) || ELEM5(a, f, g, h, i, j) )
+#define ELEM10(a, b, c, d, e, f, g, h, i, j, k) ( ELEM4(a, b, c, d, e) || ELEM6(a, f, g, h, i, j, k) )
+#define ELEM11(a, b, c, d, e, f, g, h, i, j, k, l) ( ELEM4(a, b, c, d, e) || ELEM7(a, f, g, h, i, j, k, l) )
/* shift around elements */
#define SHIFT3(type, a, b, c) { type tmp; tmp = a; a = c; c = b; b = tmp; }
@@ -98,6 +100,10 @@
#define ABS(a) ( (a)<0 ? (-(a)) : (a) )
+#define AVG2(x, y) ( 0.5 * ((x) + (y)) )
+
+#define FTOCHAR(val) ((val)<=0.0f)? 0 : (((val)>(1.0f-0.5f/255.0f))? 255 : (char)((255.0f*(val))+0.5f))
+
#define VECCOPY(v1,v2) {*(v1)= *(v2); *(v1+1)= *(v2+1); *(v1+2)= *(v2+2);}
#define VECCOPY2D(v1,v2) {*(v1)= *(v2); *(v1+1)= *(v2+1);}
#define QUATCOPY(v1,v2) {*(v1)= *(v2); *(v1+1)= *(v2+1); *(v1+2)= *(v2+2); *(v1+3)= *(v2+3);}
@@ -106,7 +112,9 @@
#define VECADD(v1,v2,v3) {*(v1)= *(v2) + *(v3); *(v1+1)= *(v2+1) + *(v3+1); *(v1+2)= *(v2+2) + *(v3+2);}
#define VECSUB(v1,v2,v3) {*(v1)= *(v2) - *(v3); *(v1+1)= *(v2+1) - *(v3+1); *(v1+2)= *(v2+2) - *(v3+2);}
+#define VECSUB2D(v1,v2,v3) {*(v1)= *(v2) - *(v3); *(v1+1)= *(v2+1) - *(v3+1);}
#define VECADDFAC(v1,v2,v3,fac) {*(v1)= *(v2) + *(v3)*(fac); *(v1+1)= *(v2+1) + *(v3+1)*(fac); *(v1+2)= *(v2+2) + *(v3+2)*(fac);}
+#define QUATADDFAC(v1,v2,v3,fac) {*(v1)= *(v2) + *(v3)*(fac); *(v1+1)= *(v2+1) + *(v3+1)*(fac); *(v1+2)= *(v2+2) + *(v3+2)*(fac); *(v1+3)= *(v2+3) + *(v3+3)*(fac);}
#define INPR(v1, v2) ( (v1)[0]*(v2)[0] + (v1)[1]*(v2)[1] + (v1)[2]*(v2)[2] )
@@ -129,7 +137,7 @@
#endif
/* INTEGER CODES */
-#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
+#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__hppa__) || defined (__BIG_ENDIAN__)
/* Big Endian */
#define MAKE_ID(a,b,c,d) ( (int)(a)<<24 | (int)(b)<<16 | (c)<<8 | (d) )
#else
@@ -165,20 +173,22 @@
/* This one rotates the bytes in an int */
#define SWITCH_INT(a) { \
- char s_i, *p_i; \
- p_i= (char *)&(a); \
- s_i=p_i[0]; p_i[0]=p_i[3]; p_i[3]=s_i; \
- s_i=p_i[1]; p_i[1]=p_i[2]; p_i[2]=s_i; }
+ char s_i, *p_i; \
+ p_i= (char *)&(a); \
+ s_i=p_i[0]; p_i[0]=p_i[3]; p_i[3]=s_i; \
+ s_i=p_i[1]; p_i[1]=p_i[2]; p_i[2]=s_i; }
#define SWITCH_SHORT(a) { \
- char s_i, *p_i; \
- p_i= (char *)&(a); \
- s_i=p_i[0]; p_i[0]=p_i[1]; p_i[1]=s_i; }
+ char s_i, *p_i; \
+ p_i= (char *)&(a); \
+ s_i=p_i[0]; p_i[0]=p_i[1]; p_i[1]=s_i; }
/* Bit operations */
-#define BTST(a,b) ( ( (a) & 1<<(b) )!=0 )
-#define BSET(a,b) ( (a) | 1<<(b) )
+#define BTST(a,b) ( ( (a) & 1<<(b) )!=0 )
+#define BNTST(a,b) ( ( (a) & 1<<(b) )==0 )
+#define BTST2(a,b,c) ( BTST( (a), (b) ) || BTST( (a), (c) ) )
+#define BSET(a,b) ( (a) | 1<<(b) )
#define BCLR(a,b) ( (a) & ~(1<<(b)) )
/* bit-row */
#define BROW(min, max) (((max)>=31? 0xFFFFFFFF: (1<<(max+1))-1) - ((min)? ((1<<(min))-1):0) )
@@ -189,5 +199,10 @@
#endif
#define GS(a) (*((short *)(a)))
+/* Warning-free macros for storing ints in pointers. Use these _only_
+ * for storing an int in a pointer, not a pointer in an int (64bit)! */
+#define SET_INT_IN_POINTER(i) ((void*)(intptr_t)(i))
+#define GET_INT_FROM_POINTER(i) ((int)(intptr_t)(i))
+
#endif
diff --git a/source/blender/blenkernel/BKE_writeffmpeg.h b/source/blender/blenkernel/BKE_writeffmpeg.h
index eccc02af1b1..02f7ba6f860 100644
--- a/source/blender/blenkernel/BKE_writeffmpeg.h
+++ b/source/blender/blenkernel/BKE_writeffmpeg.h
@@ -42,20 +42,16 @@ extern "C" {
#define FFMPEG_DV 5
#define FFMPEG_H264 6
#define FFMPEG_XVID 7
-
-#define FFMPEG_CODEC_MPEG1 0
-#define FFMPEG_CODEC_MPEG2 1
-#define FFMPEG_CODEC_MPEG4 2
-#define FFMPEG_CODEC_HUFFYUV 3
-#define FFMPEG_CODEC_DV 4
-#define FFMPEG_CODEC_H264 5
-#define FFMPEG_CODEC_XVID 6
+#define FFMPEG_FLV 8
+#define FFMPEG_MKV 9
+#define FFMPEG_OGG 10
#define FFMPEG_PRESET_NONE 0
#define FFMPEG_PRESET_DVD 1
#define FFMPEG_PRESET_SVCD 2
#define FFMPEG_PRESET_VCD 3
#define FFMPEG_PRESET_DV 4
+#define FFMPEG_PRESET_H264 5
struct RenderData;
diff --git a/source/blender/blenkernel/BKE_writeframeserver.h b/source/blender/blenkernel/BKE_writeframeserver.h
index a6ece63bc56..4774906a2fa 100644
--- a/source/blender/blenkernel/BKE_writeframeserver.h
+++ b/source/blender/blenkernel/BKE_writeframeserver.h
@@ -37,7 +37,7 @@ struct RenderData;
extern void start_frameserver(struct RenderData *rd, int rectx, int recty);
extern void end_frameserver(void);
extern void append_frameserver(int frame, int *pixels, int rectx, int recty);
-extern int frameserver_loop();
+extern int frameserver_loop(void);
#ifdef __cplusplus
}
diff --git a/source/blender/blenkernel/CMakeLists.txt b/source/blender/blenkernel/CMakeLists.txt
index 214af30f3c3..4c6d5717591 100644
--- a/source/blender/blenkernel/CMakeLists.txt
+++ b/source/blender/blenkernel/CMakeLists.txt
@@ -27,14 +27,15 @@
FILE(GLOB SRC intern/*.c)
SET(INC
- . ../../../intern/guardedalloc ../include ../blenlib ../makesdna
+ . ../../../intern/guardedalloc ../editors/include ../blenlib ../makesdna
../python ../render/extern/include ../../../intern/decimation/extern
- ../imbuf ../avi ../../../intern/elbeem/extern
+ ../imbuf ../avi ../../../intern/elbeem/extern ../../../intern/opennl/extern
../../../intern/iksolver/extern ../blenloader ../quicktime
- ../../../intern/bmfont
- ../nodes ../editors/include
+ ../../../intern/bmfont ../../../extern/bullet2/src
+ ../nodes ../../../extern/glew/include ../gpu
${SDL_INC}
${ZLIB_INC}
+ ${PYTHON_INC}
)
IF(WITH_VERSE)
@@ -46,6 +47,10 @@ IF(WITH_OPENEXR)
ADD_DEFINITIONS(-DWITH_OPENEXR)
ENDIF(WITH_OPENEXR)
+IF(WITH_DDS)
+ ADD_DEFINITIONS(-DWITH_DDS)
+ENDIF(WITH_DDS)
+
IF(WITH_QUICKTIME)
SET(INC ${INC} ${QUICKTIME_INC})
ADD_DEFINITIONS(-DWITH_QUICKTIME)
@@ -72,3 +77,6 @@ IF(WITH_INTERNATIONAL)
ADD_DEFINITIONS(-DWITH_FREETYPE2)
ENDIF(WITH_INTERNATIONAL)
+IF(NOT WITH_ELBEEM)
+ ADD_DEFINITIONS(-DDISABLE_ELBEEM)
+ENDIF(NOT WITH_ELBEEM)
diff --git a/source/blender/blenkernel/SConscript b/source/blender/blenkernel/SConscript
index 96ec8c3fff2..071fd5d82d9 100644
--- a/source/blender/blenkernel/SConscript
+++ b/source/blender/blenkernel/SConscript
@@ -4,19 +4,33 @@ Import ('env')
sources = env.Glob('intern/*.c')
incs = '. #/intern/guardedalloc ../editors/include ../blenlib ../makesdna'
-incs += ' ../python ../render/extern/include #/intern/decimation/extern'
+incs += ' ../render/extern/include #/intern/decimation/extern'
incs += ' ../imbuf ../avi #/intern/elbeem/extern ../nodes'
-incs += ' #/intern/iksolver/extern ../blenloader ../quicktime'
+incs += ' #/intern/iksolver/extern ../blenloader'
+incs += ' #/extern/bullet2/src'
incs += ' #/intern/bmfont'
+incs += ' #/intern/opennl/extern'
+incs += ' ../gpu #/extern/glew/include'
incs += ' ' + env['BF_OPENGL_INC']
incs += ' ' + env['BF_ZLIB_INC']
-incs += ' ' + env['BF_SDL_INC']
defs = ''
+if not env['WITH_BF_PYTHON']:
+ defs += 'DISABLE_PYTHON'
+else:
+ incs += ' ../python'
+ incs += ' ' + env['BF_PYTHON_INC']
+
+if env['WITH_BF_QUICKTIME']:
+ incs += ' ../quicktime'
+
+if env['WITH_BF_SDL']:
+ incs += ' ' + env['BF_SDL_INC']
+
if env['WITH_BF_INTERNATIONAL']:
- defs += 'WITH_FREETYPE2'
+ defs += ' WITH_FREETYPE2'
if env['WITH_BF_VERSE']:
defs += ' WITH_VERSE'
@@ -25,23 +39,24 @@ if env['WITH_BF_VERSE']:
if env['WITH_BF_VERSE']:
defs += ' WITH_VERSE'
-if env['WITH_BF_OPENEXR'] == 1:
- defs += ' WITH_OPENEXR'
+if env['WITH_BF_OPENEXR']:
+ defs += ' WITH_OPENEXR'
-if env['WITH_BF_DDS'] == 1:
- defs += ' WITH_DDS'
+if env['WITH_BF_DDS']:
+ defs += ' WITH_DDS'
-if env['WITH_BF_FFMPEG'] == 1:
- defs += ' WITH_FFMPEG'
- incs += ' ' + env['BF_FFMPEG_INC']
+if env['WITH_BF_FFMPEG']:
+ defs += ' WITH_FFMPEG'
+ incs += ' ' + env['BF_FFMPEG_INC']
-if env['WITH_BF_QUICKTIME'] == 1:
- defs += ' WITH_QUICKTIME'
- incs += ' ' + env['BF_QUICKTIME_INC']
+if env['WITH_BF_QUICKTIME']:
+ defs += ' WITH_QUICKTIME'
+ incs += ' ' + env['BF_QUICKTIME_INC']
-defs += ' WITH_CCGSUBSURF'
+if env['BF_NO_ELBEEM']:
+ defs += ' DISABLE_ELBEEM'
if env['WITH_BF_PLAYER']:
- SConscript(['bad_level_call_stubs/SConscript'])
+ SConscript(['bad_level_call_stubs/SConscript'])
-env.BlenderLib ( libname = 'bf_blenkernel', sources = sources, includes = Split(incs), defines = Split(defs), libtype=['core','player'], priority = [75, 10] )
+env.BlenderLib ( libname = 'bf_blenkernel', sources = sources, includes = Split(incs), defines = Split(defs), libtype=['core','player'], priority = [65, 20] )
diff --git a/source/blender/blenkernel/depsgraph_private.h b/source/blender/blenkernel/depsgraph_private.h
index adcb63b3d3a..78717393baf 100644
--- a/source/blender/blenkernel/depsgraph_private.h
+++ b/source/blender/blenkernel/depsgraph_private.h
@@ -51,6 +51,7 @@ typedef struct DagAdjList
short type;
int count; // number of identical arcs
unsigned int lay; // for flushing redraw/rebuild events
+ char *name;
struct DagAdjList *next;
} DagAdjList;
@@ -114,7 +115,7 @@ DagNode * dag_find_node (DagForest *forest,void * fob);
DagNode * dag_add_node (DagForest *forest,void * fob);
DagNode * dag_get_node (DagForest *forest,void * fob);
DagNode * dag_get_sub_node (DagForest *forest,void * fob);
-void dag_add_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel);
+void dag_add_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel, char *name);
void graph_bfs(void);
diff --git a/source/blender/blenkernel/intern/BME_Customdata.c b/source/blender/blenkernel/intern/BME_Customdata.c
new file mode 100644
index 00000000000..1fc8a4071dc
--- /dev/null
+++ b/source/blender/blenkernel/intern/BME_Customdata.c
@@ -0,0 +1,199 @@
+/**
+ * BME_customdata.c jan 2007
+ *
+ * Custom Data functions for Bmesh
+ *
+ * $Id: BKE_bmesh.h,v 1.00 2007/01/17 17:42:01 Briggs Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2004 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Geoffrey Bantle, Brecht Van Lommel, Ben Batt
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+
+#include "BKE_bmesh.h"
+#include "BKE_bmeshCustomData.h"
+#include "bmesh_private.h"
+#include <string.h>
+#include "MEM_guardedalloc.h"
+#include "BLI_mempool.h"
+
+/********************* Layer type information **********************/
+typedef struct BME_LayerTypeInfo {
+ int size;
+ char *defaultname;
+ void (*copy)(const void *source, void *dest, int count);
+ void (*free)(void *data, int count, int size);
+ void (*interp)(void **sources, float *weights, float *sub_weights, int count, void *dest);
+ void (*set_default)(void *data, int count);
+} BME_LayerTypeInfo;
+const BME_LayerTypeInfo BMELAYERTYPEINFO[BME_CD_NUMTYPES] = {
+ {sizeof(BME_facetex), "TexFace", NULL, NULL, NULL, NULL},
+ {sizeof(BME_looptex), "UV", NULL, NULL, NULL, NULL},
+ {sizeof(BME_loopcol), "VCol", NULL, NULL, NULL, NULL},
+ {sizeof(BME_DeformVert), "Group", NULL, NULL, NULL, NULL}
+};
+static const BME_LayerTypeInfo *BME_layerType_getInfo(int type)
+{
+ if(type < 0 || type >= CD_NUMTYPES) return NULL;
+
+ return &BMELAYERTYPEINFO[type];
+}
+void BME_CD_Create(BME_CustomData *data, BME_CustomDataInit *init, int initalloc)
+{
+ int i, j, offset=0;
+ const BME_LayerTypeInfo *info;
+
+ /*initialize data members*/
+ data->layers = NULL;
+ data->pool = NULL;
+ data->totlayer = 0;
+ data->totsize = 0;
+
+ /*first count how many layers to alloc*/
+ for(i=0; i < BME_CD_NUMTYPES; i++){
+ info = BME_layerType_getInfo(i);
+ data->totlayer += init->layout[i];
+ data->totsize += (init->layout[i] * info->size);
+ }
+ /*alloc our layers*/
+ if(data->totlayer){
+ /*alloc memory*/
+ data->layers = MEM_callocN(sizeof(BME_CustomDataLayer)*data->totlayer, "BMesh Custom Data Layers");
+ data->pool = BLI_mempool_create(data->totsize, initalloc, initalloc);
+ /*initialize layer data*/
+ for(i=0; i < BME_CD_NUMTYPES; i++){
+ if(init->layout[i]){
+ info = BME_layerType_getInfo(i);
+ for(j=0; j < init->layout[i]; j++){
+ if(j==0) data->layers[j+i].active = init->active[i];
+ data->layers[j+i].type = i;
+ data->layers[j+i].offset = offset;
+ strcpy(data->layers[j+i].name, &(init->nametemplate[j+i]));
+ offset += info->size;
+ }
+ }
+ }
+ }
+}
+
+void BME_CD_Free(BME_CustomData *data)
+{
+ if(data->pool) BLI_mempool_destroy(data->pool);
+}
+
+/*Block level ops*/
+void BME_CD_free_block(BME_CustomData *data, void **block)
+{
+ const BME_LayerTypeInfo *typeInfo;
+ int i;
+
+ if(!*block) return;
+ for(i = 0; i < data->totlayer; ++i) {
+ typeInfo = BME_layerType_getInfo(data->layers[i].type);
+ if(typeInfo->free) {
+ int offset = data->layers[i].offset;
+ typeInfo->free((char*)*block + offset, 1, typeInfo->size);
+ }
+ }
+ BLI_mempool_free(data->pool, *block);
+ *block = NULL;
+}
+
+
+static void BME_CD_alloc_block(BME_CustomData *data, void **block)
+{
+
+ if (*block) BME_CD_free_block(data, block); //if we copy layers that have their own free functions like deformverts
+
+ if (data->totsize > 0)
+ *block = BLI_mempool_alloc(data->pool);
+ else
+ *block = NULL;
+}
+
+void BME_CD_copy_data(const BME_CustomData *source, BME_CustomData *dest,
+ void *src_block, void **dest_block)
+{
+ const BME_LayerTypeInfo *typeInfo;
+ int dest_i, src_i;
+
+ if (!*dest_block) /*for addXXXlist functions!*/
+ BME_CD_alloc_block(dest, dest_block);
+
+ /* copies a layer at a time */
+ dest_i = 0;
+ for(src_i = 0; src_i < source->totlayer; ++src_i) {
+
+ /* find the first dest layer with type >= the source type
+ * (this should work because layers are ordered by type)
+ */
+ while(dest_i < dest->totlayer
+ && dest->layers[dest_i].type < source->layers[src_i].type)
+ ++dest_i;
+
+ /* if there are no more dest layers, we're done */
+ if(dest_i >= dest->totlayer) return;
+
+ /* if we found a matching layer, copy the data */
+ if(dest->layers[dest_i].type == source->layers[src_i].type &&
+ strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
+ char *src_data = (char*)src_block + source->layers[src_i].offset;
+ char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
+
+ typeInfo = BME_layerType_getInfo(source->layers[src_i].type);
+
+ if(typeInfo->copy)
+ typeInfo->copy(src_data, dest_data, 1);
+ else
+ memcpy(dest_data, src_data, typeInfo->size);
+
+ /* if there are multiple source & dest layers of the same type,
+ * we don't want to copy all source layers to the same dest, so
+ * increment dest_i
+ */
+ ++dest_i;
+ }
+ }
+}
+void BME_CD_set_default(BME_CustomData *data, void **block)
+{
+ const BME_LayerTypeInfo *typeInfo;
+ int i;
+
+ if (!*block)
+ BME_CD_alloc_block(data, block); //for addXXXlist functions...
+
+ for(i = 0; i < data->totlayer; ++i) {
+ int offset = data->layers[i].offset;
+
+ typeInfo = BME_layerType_getInfo(data->layers[i].type);
+
+ if(typeInfo->set_default)
+ typeInfo->set_default((char*)*block + offset, 1);
+ }
+}
diff --git a/source/blender/blenkernel/intern/BME_conversions.c b/source/blender/blenkernel/intern/BME_conversions.c
new file mode 100644
index 00000000000..2129042bdc2
--- /dev/null
+++ b/source/blender/blenkernel/intern/BME_conversions.c
@@ -0,0 +1,646 @@
+/**
+ * BME_mesh.c jan 2007
+ *
+ * BMesh mesh level functions.
+ *
+ * $Id: BME_eulers.c,v 1.00 2007/01/17 17:42:01 Briggs Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2007 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Geoffrey Bantle, Levi Schooley.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "MEM_guardedalloc.h"
+#include "BKE_customdata.h"
+
+#include "DNA_listBase.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_object_types.h"
+#include "DNA_scene_types.h"
+
+#include "BKE_utildefines.h"
+#include "BKE_mesh.h"
+#include "BKE_bmesh.h"
+#include "BKE_global.h"
+#include "BKE_DerivedMesh.h"
+#include "BKE_cdderivedmesh.h"
+
+#include "BLI_blenlib.h"
+#include "BLI_editVert.h"
+#include "BLI_edgehash.h"
+//XXX #include "BIF_editmesh.h"
+//XXX #include "editmesh.h"
+#include "bmesh_private.h"
+
+//XXX #include "BSE_edit.h"
+
+/*merge these functions*/
+static void BME_DMcorners_to_loops(BME_Mesh *bm, CustomData *facedata, int index, BME_Poly *f, int numCol, int numTex){
+ int i, j;
+ BME_Loop *l;
+ MTFace *texface;
+ MTexPoly *texpoly;
+ MCol *mcol;
+ MLoopCol *mloopcol;
+ MLoopUV *mloopuv;
+
+ for(i=0; i< numTex; i++){
+ texface = CustomData_get_layer_n(facedata, CD_MTFACE, i);
+ texpoly = CustomData_bmesh_get_n(&bm->pdata, f->data, CD_MTEXPOLY, i);
+
+ texpoly->tpage = texface[index].tpage;
+ texpoly->flag = texface[index].flag;
+ texpoly->transp = texface[index].transp;
+ texpoly->mode = texface[index].mode;
+ texpoly->tile = texface[index].tile;
+ texpoly->unwrap = texface[index].unwrap;
+
+ j = 0;
+ l = f->loopbase;
+ do{
+ mloopuv = CustomData_bmesh_get_n(&bm->ldata, l->data, CD_MLOOPUV, i);
+ mloopuv->uv[0] = texface[index].uv[j][0];
+ mloopuv->uv[1] = texface[index].uv[j][1];
+ j++;
+ l = l->next;
+ }while(l!=f->loopbase);
+ }
+
+ for(i=0; i < numCol; i++){
+ mcol = CustomData_get_layer_n(facedata, CD_MCOL, i);
+ j = 0;
+ l = f->loopbase;
+ do{
+ mloopcol = CustomData_bmesh_get_n(&bm->ldata, l->data, CD_MLOOPCOL, i);
+ mloopcol->r = mcol[(index*4)+j].r;
+ mloopcol->g = mcol[(index*4)+j].g;
+ mloopcol->b = mcol[(index*4)+j].b;
+ mloopcol->a = mcol[(index*4)+j].a;
+ j++;
+ l = l->next;
+ }while(l!=f->loopbase);
+ }
+}
+
+static void BME_DMloops_to_corners(BME_Mesh *bm, CustomData *facedata, int index, BME_Poly *f,int numCol, int numTex){
+ int i, j;
+ BME_Loop *l;
+ MTFace *texface;
+ MTexPoly *texpoly;
+ MCol *mcol;
+ MLoopCol *mloopcol;
+ MLoopUV *mloopuv;
+
+ for(i=0; i < numTex; i++){
+ texface = CustomData_get_layer_n(facedata, CD_MTFACE, i);
+ texpoly = CustomData_bmesh_get_n(&bm->pdata, f->data, CD_MTEXPOLY, i);
+
+ texface[index].tpage = texpoly->tpage;
+ texface[index].flag = texpoly->flag;
+ texface[index].transp = texpoly->transp;
+ texface[index].mode = texpoly->mode;
+ texface[index].tile = texpoly->tile;
+ texface[index].unwrap = texpoly->unwrap;
+
+ j = 0;
+ l = f->loopbase;
+ do{
+ mloopuv = CustomData_bmesh_get_n(&bm->ldata, l->data, CD_MLOOPUV, i);
+ texface[index].uv[j][0] = mloopuv->uv[0];
+ texface[index].uv[j][1] = mloopuv->uv[1];
+ j++;
+ l = l->next;
+ }while(l!=f->loopbase);
+
+ }
+ for(i=0; i < numCol; i++){
+ mcol = CustomData_get_layer_n(facedata,CD_MCOL, i);
+ j = 0;
+ l = f->loopbase;
+ do{
+ mloopcol = CustomData_bmesh_get_n(&bm->ldata, l->data, CD_MLOOPCOL, i);
+ mcol[(index*4) + j].r = mloopcol->r;
+ mcol[(index*4) + j].g = mloopcol->g;
+ mcol[(index*4) + j].b = mloopcol->b;
+ mcol[(index*4) + j].a = mloopcol->a;
+ j++;
+ l = l->next;
+ }while(l!=f->loopbase);
+ }
+}
+
+
+static void BME_corners_to_loops(BME_Mesh *bm, CustomData *facedata, void *face_block, BME_Poly *f,int numCol, int numTex){
+ int i, j;
+ BME_Loop *l;
+ MTFace *texface;
+ MTexPoly *texpoly;
+ MCol *mcol;
+ MLoopCol *mloopcol;
+ MLoopUV *mloopuv;
+
+ for(i=0; i < numTex; i++){
+ texface = CustomData_em_get_n(facedata, face_block, CD_MTFACE, i);
+ texpoly = CustomData_bmesh_get_n(&bm->pdata, f->data, CD_MTEXPOLY, i);
+
+ texpoly->tpage = texface->tpage;
+ texpoly->flag = texface->flag;
+ texpoly->transp = texface->transp;
+ texpoly->mode = texface->mode;
+ texpoly->tile = texface->tile;
+ texpoly->unwrap = texface->unwrap;
+
+ j = 0;
+ l = f->loopbase;
+ do{
+ mloopuv = CustomData_bmesh_get_n(&bm->ldata, l->data, CD_MLOOPUV, i);
+ mloopuv->uv[0] = texface->uv[j][0];
+ mloopuv->uv[1] = texface->uv[j][1];
+ j++;
+ l = l->next;
+ }while(l!=f->loopbase);
+
+ }
+ for(i=0; i < numCol; i++){
+ mcol = CustomData_em_get_n(facedata, face_block, CD_MCOL, i);
+ j = 0;
+ l = f->loopbase;
+ do{
+ mloopcol = CustomData_bmesh_get_n(&bm->ldata, l->data, CD_MLOOPCOL, i);
+ mloopcol->r = mcol[j].r;
+ mloopcol->g = mcol[j].g;
+ mloopcol->b = mcol[j].b;
+ mloopcol->a = mcol[j].a;
+ j++;
+ l = l->next;
+ }while(l!=f->loopbase);
+ }
+}
+
+static void BME_loops_to_corners(BME_Mesh *bm, CustomData *facedata, void *face_block, BME_Poly *f,int numCol, int numTex){
+ int i, j;
+ BME_Loop *l;
+ MTFace *texface;
+ MTexPoly *texpoly;
+ MCol *mcol;
+ MLoopCol *mloopcol;
+ MLoopUV *mloopuv;
+
+ for(i=0; i < numTex; i++){
+ texface = CustomData_em_get_n(facedata, face_block, CD_MTFACE, i);
+ texpoly = CustomData_bmesh_get_n(&bm->pdata, f->data, CD_MTEXPOLY, i);
+
+ texface->tpage = texpoly->tpage;
+ texface->flag = texpoly->flag;
+ texface->transp = texpoly->transp;
+ texface->mode = texpoly->mode;
+ texface->tile = texpoly->tile;
+ texface->unwrap = texpoly->unwrap;
+
+ j = 0;
+ l = f->loopbase;
+ do{
+ mloopuv = CustomData_bmesh_get_n(&bm->ldata, l->data, CD_MLOOPUV, i);
+ texface->uv[j][0] = mloopuv->uv[0];
+ texface->uv[j][1] = mloopuv->uv[1];
+ j++;
+ l = l->next;
+ }while(l!=f->loopbase);
+
+ }
+ for(i=0; i < numCol; i++){
+ mcol = CustomData_em_get_n(facedata, face_block, CD_MCOL, i);
+ j = 0;
+ l = f->loopbase;
+ do{
+ mloopcol = CustomData_bmesh_get_n(&bm->ldata, l->data, CD_MLOOPCOL, i);
+ mcol[j].r = mloopcol->r;
+ mcol[j].g = mloopcol->g;
+ mcol[j].b = mloopcol->b;
+ mcol[j].a = mloopcol->a;
+ j++;
+ l = l->next;
+ }while(l!=f->loopbase);
+ }
+}
+/*move the EditMesh conversion functions to editmesh_tools.c*/
+BME_Mesh *BME_editmesh_to_bmesh(EditMesh *em) {
+ BME_Mesh *bm;
+ int allocsize[4] = {512,512,2048,512}, numTex, numCol;
+ BME_Vert *v1, *v2;
+ BME_Edge *e, *edar[4];
+ BME_Poly *f;
+
+ EditVert *eve;
+ EditEdge *eed;
+ EditFace *efa;
+
+ int len;
+ bm = BME_make_mesh(allocsize);
+
+ /*copy custom data layout*/
+ CustomData_copy(&em->vdata, &bm->vdata, CD_MASK_BMESH, CD_CALLOC, 0);
+ CustomData_copy(&em->edata, &bm->edata, CD_MASK_BMESH, CD_CALLOC, 0);
+ CustomData_copy(&em->fdata, &bm->pdata, CD_MASK_BMESH, CD_CALLOC, 0);
+
+ /*copy face corner data*/
+ CustomData_to_bmeshpoly(&em->fdata, &bm->pdata, &bm->ldata);
+ /*initialize memory pools*/
+ CustomData_bmesh_init_pool(&bm->vdata, allocsize[0]);
+ CustomData_bmesh_init_pool(&bm->edata, allocsize[1]);
+ CustomData_bmesh_init_pool(&bm->ldata, allocsize[2]);
+ CustomData_bmesh_init_pool(&bm->pdata, allocsize[3]);
+ /*needed later*/
+ numTex = CustomData_number_of_layers(&bm->pdata, CD_MTEXPOLY);
+ numCol = CustomData_number_of_layers(&bm->ldata, CD_MLOOPCOL);
+
+ BME_model_begin(bm);
+ /*add verts*/
+ eve= em->verts.first;
+ while(eve) {
+ v1 = BME_MV(bm,eve->co);
+ VECCOPY(v1->no,eve->no);
+ v1->flag = eve->f;
+ v1->h = eve->h;
+ v1->bweight = eve->bweight;
+ /*Copy Custom Data*/
+ CustomData_bmesh_copy_data(&em->vdata, &bm->vdata, eve->data, &v1->data);
+ eve->tmp.v = (EditVert*)v1;
+ eve = eve->next;
+ }
+
+ /*add edges*/
+ eed= em->edges.first;
+ while(eed) {
+ v1 = (BME_Vert*)eed->v1->tmp.v;
+ v2 = (BME_Vert*)eed->v2->tmp.v;
+ e = BME_ME(bm, v1, v2);
+ e->crease = eed->crease;
+ e->bweight = eed->bweight;
+ e->flag = eed->f & SELECT;
+ if(eed->sharp) e->flag |= ME_SHARP;
+ if(eed->seam) e->flag |= ME_SEAM;
+ //XXX if(eed->h & EM_FGON) e->flag |= ME_FGON;
+ if(eed->h & 1) e->flag |= ME_HIDE;
+ eed->tmp.e = (EditEdge*)e;
+ CustomData_bmesh_copy_data(&em->edata, &bm->edata, eed->data, &e->data);
+ eed = eed->next;
+ }
+ /*add faces.*/
+ efa= em->faces.first;
+ while(efa) {
+ if(efa->v4) len = 4;
+ else len = 3;
+
+ edar[0] = (BME_Edge*)efa->e1->tmp.e;
+ edar[1] = (BME_Edge*)efa->e2->tmp.e;
+ edar[2] = (BME_Edge*)efa->e3->tmp.e;
+ if(len == 4){
+ edar[3] = (BME_Edge*)efa->e4->tmp.e;
+ }
+
+ /*find v1 and v2*/
+ v1 = (BME_Vert*)efa->v1->tmp.v;
+ v2 = (BME_Vert*)efa->v2->tmp.v;
+
+ f = BME_MF(bm,v1,v2,edar,len);
+ f->mat_nr = efa->mat_nr;
+ f->flag = efa->flag;
+ if(efa->h) {
+ f->flag |= ME_HIDE;
+ f->flag &= ~ME_FACE_SEL;
+ }
+ else {
+ if(efa->f & 1) f->flag |= ME_FACE_SEL;
+ else f->flag &= ~ME_FACE_SEL;
+ }
+ CustomData_bmesh_copy_data(&em->fdata, &bm->pdata, efa->data, &f->data);
+ BME_corners_to_loops(bm, &em->fdata, efa->data, f,numCol,numTex);
+ efa = efa->next;
+ }
+ BME_model_end(bm);
+ return bm;
+}
+/* adds the geometry in the bmesh to G.editMesh (does not free G.editMesh)
+ * if td != NULL, the transdata will be mapped to the EditVert's co */
+EditMesh *BME_bmesh_to_editmesh(BME_Mesh *bm, BME_TransData_Head *td) {
+ BME_Vert *v1;
+ BME_Edge *e;
+ BME_Poly *f;
+
+ BME_TransData *vtd;
+
+ EditMesh *em;
+ EditVert *eve1, *eve2, *eve3, *eve4, **evlist;
+ EditEdge *eed;
+ EditFace *efa;
+
+ int totvert, len, i, numTex, numCol;
+
+ em = G.editMesh;
+
+ if (em == NULL) return NULL;
+
+
+ CustomData_copy(&bm->vdata, &em->vdata, CD_MASK_BMESH, CD_CALLOC, 0);
+ CustomData_copy(&bm->edata, &em->edata, CD_MASK_BMESH, CD_CALLOC, 0);
+ CustomData_copy(&bm->pdata, &em->fdata, CD_MASK_BMESH, CD_CALLOC, 0);
+ CustomData_from_bmeshpoly(&em->fdata, &bm->pdata, &bm->ldata,0);
+ numTex = CustomData_number_of_layers(&bm->pdata, CD_MTEXPOLY);
+ numCol = CustomData_number_of_layers(&bm->ldata, CD_MLOOPCOL);
+
+
+ /* convert to EditMesh */
+ /* make editverts */
+ totvert = BLI_countlist(&(bm->verts));
+ evlist= (EditVert **)MEM_mallocN(totvert*sizeof(void *),"evlist");
+ for (i=0,v1=bm->verts.first;v1;v1=v1->next,i++) {
+ v1->tflag1 = i;
+ eve1 = NULL; //XXX addvertlist(v1->co,NULL);
+ if (td && (vtd = BME_get_transdata(td,v1))) {
+ vtd->loc = eve1->co;
+ }
+ eve1->keyindex = i;
+ evlist[i]= eve1;
+ eve1->f = (unsigned char)v1->flag;
+ eve1->h = (unsigned char)v1->h;
+ eve1->bweight = v1->bweight;
+ CustomData_em_copy_data(&bm->vdata, &em->vdata, v1->data, &eve1->data);
+ }
+
+ /* make edges */
+ for (e=bm->edges.first;e;e=e->next) {
+ if(0) { //XXX if(!(findedgelist(evlist[e->v1->tflag1], evlist[e->v2->tflag1]))){
+ eed= NULL; //XXX addedgelist(evlist[e->v1->tflag1], evlist[e->v2->tflag1], NULL);
+ eed->crease = e->crease;
+ eed->bweight = e->bweight;
+ if(e->flag & ME_SEAM) eed->seam = 1;
+ if(e->flag & ME_SHARP) eed->sharp = 1;
+ if(e->flag & SELECT) eed->f |= SELECT;
+ //XXX if(e->flag & ME_FGON) eed->h= EM_FGON; // 2 different defines!
+ if(e->flag & ME_HIDE) eed->h |= 1;
+ if(G.scene->selectmode==SCE_SELECT_EDGE)
+ ; //XXX EM_select_edge(eed, eed->f & SELECT);
+
+ CustomData_em_copy_data(&bm->edata, &em->edata, e->data, &eed->data);
+ }
+ }
+
+ /* make faces */
+ for (f=bm->polys.first;f;f=f->next) {
+ len = BME_cycle_length(f->loopbase);
+ if (len==3 || len==4) {
+ eve1= evlist[f->loopbase->v->tflag1];
+ eve2= evlist[f->loopbase->next->v->tflag1];
+ eve3= evlist[f->loopbase->next->next->v->tflag1];
+ if (len == 4) {
+ eve4= evlist[f->loopbase->prev->v->tflag1];
+ }
+ else {
+ eve4= NULL;
+ }
+
+ efa = NULL; //XXX addfacelist(eve1, eve2, eve3, eve4, NULL, NULL);
+ efa->mat_nr = (unsigned char)f->mat_nr;
+ efa->flag= f->flag & ~ME_HIDE;
+ if(f->flag & ME_FACE_SEL) {
+ efa->f |= SELECT;
+ }
+ if(f->flag & ME_HIDE) efa->h= 1;
+ if((G.f & G_FACESELECT) && (efa->f & SELECT))
+ ; //XXX EM_select_face(efa, 1); /* flush down */
+ CustomData_em_copy_data(&bm->pdata, &em->fdata, f->data, &efa->data);
+ BME_loops_to_corners(bm, &em->fdata, efa->data, f,numCol,numTex);
+ }
+ }
+
+ MEM_freeN(evlist);
+
+ //XXX countall();
+
+ return em;
+}
+
+/* Adds the geometry found in dm to bm
+ */
+BME_Mesh *BME_derivedmesh_to_bmesh(DerivedMesh *dm)
+{
+
+ BME_Mesh *bm;
+ int allocsize[4] = {512,512,2048,512};
+ MVert *mvert, *mv;
+ MEdge *medge, *me;
+ MFace *mface, *mf;
+ int totface,totedge,totvert,i,len, numTex, numCol;
+ BME_Vert *v1=NULL,*v2=NULL, **vert_array;
+ BME_Edge *e=NULL;
+ BME_Poly *f=NULL;
+
+ EdgeHash *edge_hash = BLI_edgehash_new();
+
+ bm = BME_make_mesh(allocsize);
+ /*copy custom data layout*/
+ CustomData_copy(&dm->vertData, &bm->vdata, CD_MASK_BMESH, CD_CALLOC, 0);
+ CustomData_copy(&dm->edgeData, &bm->edata, CD_MASK_BMESH, CD_CALLOC, 0);
+ CustomData_copy(&dm->faceData, &bm->pdata, CD_MASK_BMESH, CD_CALLOC, 0);
+
+ /*copy face corner data*/
+ CustomData_to_bmeshpoly(&dm->faceData, &bm->pdata, &bm->ldata);
+ /*initialize memory pools*/
+ CustomData_bmesh_init_pool(&bm->vdata, allocsize[0]);
+ CustomData_bmesh_init_pool(&bm->edata, allocsize[1]);
+ CustomData_bmesh_init_pool(&bm->ldata, allocsize[2]);
+ CustomData_bmesh_init_pool(&bm->pdata, allocsize[3]);
+ /*needed later*/
+ numTex = CustomData_number_of_layers(&bm->pdata, CD_MTEXPOLY);
+ numCol = CustomData_number_of_layers(&bm->ldata, CD_MLOOPCOL);
+
+ totvert = dm->getNumVerts(dm);
+ totedge = dm->getNumEdges(dm);
+ totface = dm->getNumFaces(dm);
+ mvert = dm->getVertArray(dm);
+ medge = dm->getEdgeArray(dm);
+ mface = dm->getFaceArray(dm);
+
+ vert_array = MEM_mallocN(sizeof(*vert_array)*totvert,"BME_derivedmesh_to_bmesh BME_Vert* array");
+
+ BME_model_begin(bm);
+ /*add verts*/
+ for(i=0,mv = mvert; i < totvert;i++,mv++){
+ v1 = BME_MV(bm,mv->co);
+ vert_array[i] = v1;
+ v1->flag = mv->flag;
+ v1->bweight = mv->bweight/255.0f;
+ CustomData_to_bmesh_block(&dm->vertData, &bm->vdata, i, &v1->data);
+ }
+ /*add edges*/
+ for(i=0,me = medge; i < totedge;i++,me++){
+ v1 = vert_array[me->v1];
+ v2 = vert_array[me->v2];
+ e = BME_ME(bm, v1, v2);
+ e->crease = me->crease/255.0f;
+ e->bweight = me->bweight/255.0f;
+ e->flag = (unsigned char)me->flag;
+ BLI_edgehash_insert(edge_hash,me->v1,me->v2,e);
+ CustomData_to_bmesh_block(&dm->edgeData, &bm->edata, i, &e->data);
+ }
+ /*add faces.*/
+ for(i=0,mf = mface; i < totface;i++,mf++){
+ BME_Edge *edar[4];
+ if(mf->v4) len = 4;
+ else len = 3;
+
+ edar[0] = BLI_edgehash_lookup(edge_hash,mf->v1,mf->v2);
+ edar[1] = BLI_edgehash_lookup(edge_hash,mf->v2,mf->v3);
+ if(len == 4){
+ edar[2] = BLI_edgehash_lookup(edge_hash,mf->v3,mf->v4);
+ edar[3] = BLI_edgehash_lookup(edge_hash,mf->v4,mf->v1);
+ }
+ else
+ edar[2] = BLI_edgehash_lookup(edge_hash,mf->v3,mf->v1);
+
+ /*find v1 and v2*/
+ v1 = vert_array[mf->v1];
+ v2 = vert_array[mf->v2];
+
+ f = BME_MF(bm,v1,v2,edar,len);
+ f->mat_nr = mf->mat_nr;
+ f->flag = mf->flag;
+ CustomData_to_bmesh_block(&dm->faceData,&bm->pdata,i,&f->data);
+ BME_DMcorners_to_loops(bm, &dm->faceData,i,f, numCol,numTex);
+ }
+
+ BME_model_end(bm);
+ BLI_edgehash_free(edge_hash, NULL);
+ MEM_freeN(vert_array);
+ return bm;
+}
+
+DerivedMesh *BME_bmesh_to_derivedmesh(BME_Mesh *bm, DerivedMesh *dm)
+{
+ MFace *mface, *mf;
+ MEdge *medge, *me;
+ MVert *mvert, *mv;
+ int totface,totedge,totvert,i,bmeshok,len, numTex, numCol;
+
+ BME_Vert *v1=NULL;
+ BME_Edge *e=NULL, *oe=NULL;
+ BME_Poly *f=NULL;
+
+ DerivedMesh *result;
+ EdgeHash *edge_hash = BLI_edgehash_new();
+
+ totvert = BLI_countlist(&(bm->verts));
+ totedge = 0;
+
+ /*we cannot have double edges in a derived mesh!*/
+ for(i=0, v1=bm->verts.first; v1; v1=v1->next, i++) v1->tflag1 = i;
+ for(e=bm->edges.first; e; e=e->next){
+ oe = BLI_edgehash_lookup(edge_hash,e->v1->tflag1, e->v2->tflag1);
+ if(!oe){
+ totedge++;
+ BLI_edgehash_insert(edge_hash,e->v1->tflag1,e->v2->tflag1,e);
+ e->tflag2 = 1;
+ }
+ else{
+ e->tflag2 = 0;
+ }
+ }
+
+ /*count quads and tris*/
+ totface = 0;
+ bmeshok = 1;
+ for(f=bm->polys.first;f;f=f->next){
+ len = BME_cycle_length(f->loopbase);
+ if(len == 3 || len == 4) totface++;
+ }
+
+ /*convert back to mesh*/
+ result = CDDM_from_template(dm,totvert,totedge,totface);
+ CustomData_merge(&bm->vdata, &result->vertData, CD_MASK_BMESH, CD_CALLOC, totvert);
+ CustomData_merge(&bm->edata, &result->edgeData, CD_MASK_BMESH, CD_CALLOC, totedge);
+ CustomData_merge(&bm->pdata, &result->faceData, CD_MASK_BMESH, CD_CALLOC, totface);
+ CustomData_from_bmeshpoly(&result->faceData, &bm->pdata, &bm->ldata,totface);
+ numTex = CustomData_number_of_layers(&bm->pdata, CD_MTEXPOLY);
+ numCol = CustomData_number_of_layers(&bm->ldata, CD_MLOOPCOL);
+
+
+ /*Make Verts*/
+ mvert = CDDM_get_verts(result);
+ for(i=0,v1=bm->verts.first,mv=mvert;v1;v1=v1->next,i++,mv++){
+ VECCOPY(mv->co,v1->co);
+ mv->flag = (unsigned char)v1->flag;
+ mv->bweight = (char)(255.0*v1->bweight);
+ CustomData_from_bmesh_block(&bm->vdata, &result->vertData, &v1->data, i);
+ }
+ medge = CDDM_get_edges(result);
+ i=0;
+ for(e=bm->edges.first,me=medge;e;e=e->next){
+ if(e->tflag2){
+ if(e->v1->tflag1 < e->v2->tflag1){
+ me->v1 = e->v1->tflag1;
+ me->v2 = e->v2->tflag1;
+ }
+ else{
+ me->v1 = e->v2->tflag1;
+ me->v2 = e->v1->tflag1;
+ }
+
+ me->crease = (char)(255.0*e->crease);
+ me->bweight = (char)(255.0*e->bweight);
+ me->flag = e->flag;
+ CustomData_from_bmesh_block(&bm->edata, &result->edgeData, &e->data, i);
+ me++;
+ i++;
+ }
+ }
+ if(totface){
+ mface = CDDM_get_faces(result);
+ /*make faces*/
+ for(i=0,f=bm->polys.first;f;f=f->next){
+ mf = &mface[i];
+ len = BME_cycle_length(f->loopbase);
+ if(len==3 || len==4){
+ mf->v1 = f->loopbase->v->tflag1;
+ mf->v2 = f->loopbase->next->v->tflag1;
+ mf->v3 = f->loopbase->next->next->v->tflag1;
+ if(len == 4){
+ mf->v4 = f->loopbase->prev->v->tflag1;
+ }
+ /* test and rotate indexes if necessary so that verts 3 and 4 aren't index 0 */
+ if(mf->v3 == 0 || (len == 4 && mf->v4 == 0)){
+ test_index_face(mf, NULL, i, len);
+ }
+ mf->mat_nr = (unsigned char)f->mat_nr;
+ mf->flag = (unsigned char)f->flag;
+ CustomData_from_bmesh_block(&bm->pdata, &result->faceData, &f->data, i);
+ BME_DMloops_to_corners(bm, &result->faceData, i, f,numCol,numTex);
+ i++;
+ }
+ }
+ }
+ BLI_edgehash_free(edge_hash, NULL);
+ return result;
+}
diff --git a/source/blender/blenkernel/intern/BME_eulers.c b/source/blender/blenkernel/intern/BME_eulers.c
new file mode 100644
index 00000000000..801e0b8bdec
--- /dev/null
+++ b/source/blender/blenkernel/intern/BME_eulers.c
@@ -0,0 +1,977 @@
+/**
+ * BME_eulers.c jan 2007
+ *
+ * BMesh Euler construction API.
+ *
+ * $Id: BME_eulers.c,v 1.00 2007/01/17 17:42:01 Briggs Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2004 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Geoffrey Bantle.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_listBase.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_mesh_types.h"
+
+#include "BKE_utildefines.h"
+#include "BKE_customdata.h"
+#include "BKE_bmesh.h"
+
+#include "BLI_blenlib.h"
+#include "bmesh_private.h"
+#include "BLI_ghash.h"
+
+/*********************************************************
+ * "Euler API" *
+ * *
+ * *
+ * Primitive construction operators for mesh tools. *
+ * *
+ **********************************************************/
+
+
+/*
+ The functions in this file represent the 'primitive' or 'atomic' operators that
+ mesh tools use to manipulate the topology of the structure.* The purpose of these
+ functions is to provide a trusted set of operators to manipulate the mesh topology
+ and which can also be combined together like building blocks to create more
+ sophisticated tools. It needs to be stressed that NO manipulation of an existing
+ mesh structure should be done outside of these functions.
+
+ In the BMesh system, each euler is named by an ancronym which describes what it actually does.
+ Furthermore each Euler has a logical inverse. An important design criteria of all Eulers is that
+ through a Euler's logical inverse you can 'undo' an operation. (Special note should
+ be taken of BME_loop_reverse, which is its own inverse).
+
+ BME_MF/KF: Make Face and Kill Face
+ BME_ME/KE: Make Edge and Kill Edge
+ BME_MV/KV: Make Vert and Kill Vert
+ BME_SEMV/JEKV: Split Edge, Make Vert and Join Edge, Kill Vert
+ BME_SFME/JFKE: Split Face, Make Edge and Join Face, Kill Edge
+ BME_loop_reverse: Reverse a Polygon's loop cycle. (used for flip normals for one)
+
+ Using a combination of these eleven eulers any non-manifold modelling operation can be achieved.
+ Each Euler operator has a detailed explanation of what is does in the comments preceding its
+ code.
+
+ *The term "Euler Operator" is actually a misnomer when referring to a non-manifold
+ data structure. Its use is in keeping with the convention established by others.
+
+ TODO:
+ -Finish inserting 'strict' validation in all Eulers
+*/
+
+void *BME_exit(char *s) {
+ if (s) printf("%s\n",s);
+ return NULL;
+}
+
+#define RETCLEAR(bm) {bm->rval->v = bm->rval->e = bm->rval->f = bm->rva->l = NULL;}
+/*MAKE Eulers*/
+
+/**
+ * BME_MV
+ *
+ * MAKE VERT EULER:
+ *
+ * Makes a single loose vertex.
+ *
+ * Returns -
+ * A BME_Vert pointer.
+ */
+
+BME_Vert *BME_MV(BME_Mesh *bm, float *vec){
+ BME_Vert *v = BME_addvertlist(bm, NULL);
+ VECCOPY(v->co,vec);
+ return v;
+}
+
+/**
+ * BME_ME
+ *
+ * MAKE EDGE EULER:
+ *
+ * Makes a single wire edge between two vertices.
+ * If the caller does not want there to be duplicate
+ * edges between the vertices, it is up to them to check
+ * for this condition beforehand.
+ *
+ * Returns -
+ * A BME_Edge pointer.
+ */
+
+BME_Edge *BME_ME(BME_Mesh *bm, BME_Vert *v1, BME_Vert *v2){
+ BME_Edge *e=NULL;
+ BME_CycleNode *d1=NULL, *d2=NULL;
+ int valance1=0, valance2=0, edok;
+
+ /*edge must be between two distinct vertices...*/
+ if(v1 == v2) return NULL;
+
+ #ifndef BME_FASTEULER
+ /*count valance of v1*/
+ if(v1->edge){
+ d1 = BME_disk_getpointer(v1->edge,v1);
+ if(d1) valance1 = BME_cycle_length(d1);
+ else BME_error();
+ }
+ if(v2->edge){
+ d2 = BME_disk_getpointer(v2->edge,v2);
+ if(d2) valance2 = BME_cycle_length(d2);
+ else BME_error();
+ }
+ #endif
+
+ /*go ahead and add*/
+ e = BME_addedgelist(bm, v1, v2, NULL);
+ BME_disk_append_edge(e, e->v1);
+ BME_disk_append_edge(e, e->v2);
+
+ #ifndef BME_FASTEULER
+ /*verify disk cycle lengths*/
+ d1 = BME_disk_getpointer(e, e->v1);
+ edok = BME_cycle_validate(valance1+1, d1);
+ if(!edok) BME_error();
+ d2 = BME_disk_getpointer(e, e->v2);
+ edok = BME_cycle_validate(valance2+1, d2);
+ if(!edok) BME_error();
+
+ /*verify that edge actually made it into the cycle*/
+ edok = BME_disk_hasedge(v1, e);
+ if(!edok) BME_error();
+ edok = BME_disk_hasedge(v2, e);
+ if(!edok) BME_error();
+ #endif
+ return e;
+}
+
+
+
+/**
+ * BME_MF
+ *
+ * MAKE FACE EULER:
+ * Takes a list of edge pointers which form a closed loop and makes a face
+ * from them. The first edge in elist is considered to be the start of the
+ * polygon, and v1 and v2 are its vertices and determine the winding of the face
+ * Other than the first edge, no other assumptions are made about the order of edges
+ * in the elist array. To verify that it is a single closed loop and derive the correct
+ * order a simple series of verifications is done and all elements are visited.
+ *
+ * Returns -
+ * A BME_Poly pointer
+ */
+
+#define MF_CANDIDATE 1
+#define MF_VISITED 2
+#define MF_TAKEN 4
+
+BME_Poly *BME_MF(BME_Mesh *bm, BME_Vert *v1, BME_Vert *v2, BME_Edge **elist, int len)
+{
+ BME_Poly *f = NULL;
+ BME_Edge *curedge;
+ BME_Vert *curvert, *tv, **vlist;
+ int i, j, done, cont, edok;
+
+ if(len < 2) return NULL;
+
+ /*make sure that v1 and v2 are in elist[0]*/
+ if(BME_verts_in_edge(v1,v2,elist[0]) == 0) return NULL;
+
+ /*clear euler flags*/
+ for(i=0;i<len;i++) elist[i]->eflag1=elist[i]->eflag2 = 0;
+ for(i=0;i<len;i++){
+ elist[i]->eflag1 |= MF_CANDIDATE;
+
+ /*if elist[i] has a loop, count its radial length*/
+ if(elist[i]->loop) elist[i]->eflag2 = BME_cycle_length(&(elist[i]->loop->radial));
+ else elist[i]->eflag2 = 0;
+ }
+
+ /* For each vertex in each edge, it must have exactly two MF_CANDIDATE edges attached to it
+ Note that this does not gauruntee that face is a single closed loop. At best it gauruntees
+ that elist contains a finite number of seperate closed loops.
+ */
+ for(i=0; i<len; i++){
+ edok = BME_disk_count_edgeflag(elist[i]->v1, MF_CANDIDATE, 0);
+ if(edok != 2) return NULL;
+ edok = BME_disk_count_edgeflag(elist[i]->v2, MF_CANDIDATE, 0);
+ if(edok != 2) return NULL;
+ }
+
+ /*set start edge, start vert and target vert for our loop traversal*/
+ curedge = elist[0];
+ tv = v1;
+ curvert = v2;
+
+ if(bm->vtarlen < len){
+ MEM_freeN(bm->vtar);
+ bm->vtar = MEM_callocN(sizeof(BME_Vert *)* len, "BMesh Vert pointer array");
+ bm->vtarlen = len;
+ }
+ /*insert tv into vlist since its the first vertex in face*/
+ i=0;
+ vlist=bm->vtar;
+ vlist[i] = tv;
+
+ /* Basic procedure: Starting with curv we find the edge in it's disk cycle which hasn't
+ been visited yet. When we do, we put curv in a linked list and find the next MF_CANDIDATE
+ edge, loop until we find TV. We know TV is reachable because of test we did earlier.
+ */
+ done=0;
+ while(!done){
+ /*add curvert to vlist*/
+ /*insert some error cheking here for overflows*/
+ i++;
+ vlist[i] = curvert;
+
+ /*mark curedge as visited*/
+ curedge->eflag1 |= MF_VISITED;
+
+ /*find next edge and vert*/
+ curedge = BME_disk_next_edgeflag(curedge, curvert, MF_CANDIDATE, 0);
+ curvert = BME_edge_getothervert(curedge, curvert);
+ if(curvert == tv){
+ curedge->eflag1 |= MF_VISITED;
+ done=1;
+ }
+ }
+
+ /* Verify that all edges have been visited It's possible that we did reach tv
+ from sv, but that several unconnected loops were passed in via elist.
+ */
+ cont=1;
+ for(i=0; i<len; i++){
+ if((elist[i]->eflag1 & MF_VISITED) == 0) cont = 0;
+ }
+
+ /*if we get this far, its ok to allocate the face and add the loops*/
+ if(cont){
+ BME_Loop *l;
+ BME_Edge *e;
+ f = BME_addpolylist(bm, NULL);
+ f->len = len;
+ for(i=0;i<len;i++){
+ curvert = vlist[i];
+ l = BME_create_loop(bm,curvert,NULL,f,NULL);
+ if(!(f->loopbase)) f->loopbase = l;
+ BME_cycle_append(f->loopbase, l);
+ }
+
+ /*take care of edge pointers and radial cycle*/
+ for(i=0, l = f->loopbase; i<len; i++, l=l->next){
+ e = NULL;
+ if(l == f->loopbase) e = elist[0]; /*first edge*/
+
+ else{/*search elist for others*/
+ for(j=1; j<len; j++){
+ edok = BME_verts_in_edge(l->v, l->next->v, elist[j]);
+ if(edok){
+ e = elist[j];
+ break;
+ }
+ }
+ }
+ l->e = e; /*set pointer*/
+ BME_radial_append(e, l); /*append into radial*/
+ }
+
+ f->len = len;
+
+ /*Validation Loop cycle*/
+ edok = BME_cycle_validate(len, f->loopbase);
+ if(!edok) BME_error();
+ for(i=0, l = f->loopbase; i<len; i++, l=l->next){
+ /*validate loop vert pointers*/
+ edok = BME_verts_in_edge(l->v, l->next->v, l->e);
+ if(!edok) BME_error();
+ /*validate the radial cycle of each edge*/
+ edok = BME_cycle_length(&(l->radial));
+ if(edok != (l->e->eflag2 + 1)) BME_error();
+ }
+ }
+ return f;
+}
+
+/* KILL Eulers */
+
+/**
+ * BME_KV
+ *
+ * KILL VERT EULER:
+ *
+ * Kills a single loose vertex.
+ *
+ * Returns -
+ * 1 for success, 0 for failure.
+ */
+
+int BME_KV(BME_Mesh *bm, BME_Vert *v){
+ if(v->edge == NULL){
+ BLI_remlink(&(bm->verts), v);
+ BME_free_vert(bm,v);
+ return 1;
+ }
+ return 0;
+}
+
+/**
+ * BME_KE
+ *
+ * KILL EDGE EULER:
+ *
+ * Kills a wire edge.
+ *
+ * Returns -
+ * 1 for success, 0 for failure.
+ */
+
+int BME_KE(BME_Mesh *bm, BME_Edge *e){
+ int edok;
+
+ /*Make sure that no faces!*/
+ if(e->loop == NULL){
+ BME_disk_remove_edge(e, e->v1);
+ BME_disk_remove_edge(e, e->v2);
+
+ /*verify that edge out of disk*/
+ edok = BME_disk_hasedge(e->v1, e);
+ if(edok) BME_error();
+ edok = BME_disk_hasedge(e->v2, e);
+ if(edok) BME_error();
+
+ /*remove and deallocate*/
+ BLI_remlink(&(bm->edges), e);
+ BME_free_edge(bm, e);
+ return 1;
+ }
+ return 0;
+}
+
+/**
+ * BME_KF
+ *
+ * KILL FACE EULER:
+ *
+ * The logical inverse of BME_MF.
+ * Kills a face and removes each of its loops from the radial that it belongs to.
+ *
+ * Returns -
+ * 1 for success, 0 for failure.
+*/
+
+int BME_KF(BME_Mesh *bm, BME_Poly *bply){
+ BME_Loop *newbase,*oldbase, *curloop;
+ int i,len=0;
+
+ /*add validation to make sure that radial cycle is cleaned up ok*/
+ /*deal with radial cycle first*/
+ len = BME_cycle_length(bply->loopbase);
+ for(i=0, curloop=bply->loopbase; i < len; i++, curloop = curloop->next)
+ BME_radial_remove_loop(curloop, curloop->e);
+
+ /*now deallocate the editloops*/
+ for(i=0; i < len; i++){
+ newbase = bply->loopbase->next;
+ oldbase = bply->loopbase;
+ BME_cycle_remove(oldbase, oldbase);
+ BME_free_loop(bm, oldbase);
+ bply->loopbase = newbase;
+ }
+
+ BLI_remlink(&(bm->polys), bply);
+ BME_free_poly(bm, bply);
+ return 1;
+}
+
+/*SPLIT Eulers*/
+
+/**
+ * BME_SEMV
+ *
+ * SPLIT EDGE MAKE VERT:
+ * Takes a given edge and splits it into two, creating a new vert.
+ *
+ *
+ * Before: OV---------TV
+ * After: OV----NV---TV
+ *
+ * Returns -
+ * BME_Vert pointer.
+ *
+*/
+
+BME_Vert *BME_SEMV(BME_Mesh *bm, BME_Vert *tv, BME_Edge *e, BME_Edge **re){
+ BME_Vert *nv, *ov;
+ BME_CycleNode *diskbase;
+ BME_Edge *ne;
+ int i, edok, valance1=0, valance2=0;
+
+ if(BME_vert_in_edge(e,tv) == 0) return NULL;
+ ov = BME_edge_getothervert(e,tv);
+ //v2 = tv;
+
+ /*count valance of v1*/
+ diskbase = BME_disk_getpointer(e, ov);
+ valance1 = BME_cycle_length(diskbase);
+ /*count valance of v2*/
+ diskbase = BME_disk_getpointer(e, tv);
+ valance2 = BME_cycle_length(diskbase);
+
+ nv = BME_addvertlist(bm, tv);
+ ne = BME_addedgelist(bm, nv, tv, e);
+
+ //e->v2 = nv;
+ /*remove e from v2's disk cycle*/
+ BME_disk_remove_edge(e, tv);
+ /*swap out tv for nv in e*/
+ BME_edge_swapverts(e, tv, nv);
+ /*add e to nv's disk cycle*/
+ BME_disk_append_edge(e, nv);
+ /*add ne to nv's disk cycle*/
+ BME_disk_append_edge(ne, nv);
+ /*add ne to tv's disk cycle*/
+ BME_disk_append_edge(ne, tv);
+ /*verify disk cycles*/
+ diskbase = BME_disk_getpointer(ov->edge,ov);
+ edok = BME_cycle_validate(valance1, diskbase);
+ if(!edok) BME_error();
+ diskbase = BME_disk_getpointer(tv->edge,tv);
+ edok = BME_cycle_validate(valance2, diskbase);
+ if(!edok) BME_error();
+ diskbase = BME_disk_getpointer(nv->edge,nv);
+ edok = BME_cycle_validate(2, diskbase);
+ if(!edok) BME_error();
+
+ /*Split the radial cycle if present*/
+ if(e->loop){
+ BME_Loop *nl,*l;
+ BME_CycleNode *radEBase=NULL, *radNEBase=NULL;
+ int radlen = BME_cycle_length(&(e->loop->radial));
+ /*Take the next loop. Remove it from radial. Split it. Append to appropriate radials.*/
+ while(e->loop){
+ l=e->loop;
+ l->f->len++;
+ BME_radial_remove_loop(l,e);
+
+ nl = BME_create_loop(bm,NULL,NULL,l->f,l);
+ nl->prev = l;
+ nl->next = l->next;
+ nl->prev->next = nl;
+ nl->next->prev = nl;
+ nl->v = nv;
+
+ /*assign the correct edge to the correct loop*/
+ if(BME_verts_in_edge(nl->v, nl->next->v, e)){
+ nl->e = e;
+ l->e = ne;
+
+ /*append l into ne's rad cycle*/
+ if(!radNEBase){
+ radNEBase = &(l->radial);
+ radNEBase->next = NULL;
+ radNEBase->prev = NULL;
+ }
+
+ if(!radEBase){
+ radEBase = &(nl->radial);
+ radEBase->next = NULL;
+ radEBase->prev = NULL;
+ }
+
+ BME_cycle_append(radEBase,&(nl->radial));
+ BME_cycle_append(radNEBase,&(l->radial));
+
+ }
+ else if(BME_verts_in_edge(nl->v,nl->next->v,ne)){
+ nl->e = ne;
+ l->e = e;
+
+ if(!radNEBase){
+ radNEBase = &(nl->radial);
+ radNEBase->next = NULL;
+ radNEBase->prev = NULL;
+ }
+ if(!radEBase){
+ radEBase = &(l->radial);
+ radEBase->next = NULL;
+ radEBase->prev = NULL;
+ }
+ BME_cycle_append(radEBase,&(l->radial));
+ BME_cycle_append(radNEBase,&(nl->radial));
+ }
+
+ }
+
+ e->loop = radEBase->data;
+ ne->loop = radNEBase->data;
+
+ /*verify length of radial cycle*/
+ edok = BME_cycle_validate(radlen,&(e->loop->radial));
+ if(!edok) BME_error();
+ edok = BME_cycle_validate(radlen,&(ne->loop->radial));
+ if(!edok) BME_error();
+
+ /*verify loop->v and loop->next->v pointers for e*/
+ for(i=0,l=e->loop; i < radlen; i++, l = l->radial.next->data){
+ if(!(l->e == e)) BME_error();
+ if(!(l->radial.data == l)) BME_error();
+ if(l->prev->e != ne && l->next->e != ne) BME_error();
+ edok = BME_verts_in_edge(l->v, l->next->v, e);
+ if(!edok) BME_error();
+ if(l->v == l->next->v) BME_error();
+ if(l->e == l->next->e) BME_error();
+ /*verify loop cycle for kloop->f*/
+ edok = BME_cycle_validate(l->f->len, l->f->loopbase);
+ if(!edok) BME_error();
+ }
+ /*verify loop->v and loop->next->v pointers for ne*/
+ for(i=0,l=ne->loop; i < radlen; i++, l = l->radial.next->data){
+ if(!(l->e == ne)) BME_error();
+ if(!(l->radial.data == l)) BME_error();
+ if(l->prev->e != e && l->next->e != e) BME_error();
+ edok = BME_verts_in_edge(l->v, l->next->v, ne);
+ if(!edok) BME_error();
+ if(l->v == l->next->v) BME_error();
+ if(l->e == l->next->e) BME_error();
+ /*verify loop cycle for kloop->f. Redundant*/
+ edok = BME_cycle_validate(l->f->len, l->f->loopbase);
+ if(!edok) BME_error();
+ }
+ }
+
+ if(re) *re = ne;
+ return nv;
+}
+
+/**
+ * BME_SFME
+ *
+ * SPLIT FACE MAKE EDGE:
+ *
+ * Takes as input two vertices in a single face. An edge is created which divides the original face
+ * into two distinct regions. One of the regions is assigned to the original face and it is closed off.
+ * The second region has a new face assigned to it.
+ *
+ * Examples:
+ *
+ * Before: After:
+ * ---------- ----------
+ * | | | |
+ * | | | f1 |
+ * v1 f1 v2 v1======v2
+ * | | | f2 |
+ * | | | |
+ * ---------- ----------
+ *
+ * Note that the input vertices can be part of the same edge. This will result in a two edged face.
+ * This is desirable for advanced construction tools and particularly essential for edge bevel. Because
+ * of this it is up to the caller to decide what to do with the extra edge.
+ *
+ * Returns -
+ * A BME_Poly pointer
+ */
+BME_Poly *BME_SFME(BME_Mesh *bm, BME_Poly *f, BME_Vert *v1, BME_Vert *v2, BME_Loop **rl){
+
+ BME_Poly *f2;
+ BME_Loop *v1loop = NULL, *v2loop = NULL, *curloop, *f1loop=NULL, *f2loop=NULL;
+ BME_Edge *e;
+ int i, len, f1len, f2len;
+
+
+ /*verify that v1 and v2 are in face.*/
+ len = BME_cycle_length(f->loopbase);
+ for(i = 0, curloop = f->loopbase; i < len; i++, curloop = curloop->next){
+ if(curloop->v == v1) v1loop = curloop;
+ else if(curloop->v == v2) v2loop = curloop;
+ }
+
+ if(!v1loop || !v2loop) return NULL;
+
+ /*allocate new edge between v1 and v2*/
+ e = BME_addedgelist(bm, v1, v2,NULL);
+ BME_disk_append_edge(e, v1);
+ BME_disk_append_edge(e, v2);
+
+ f2 = BME_addpolylist(bm,f);
+ f1loop = BME_create_loop(bm,v2,e,f,v2loop);
+ f2loop = BME_create_loop(bm,v1,e,f2,v1loop);
+
+ f1loop->prev = v2loop->prev;
+ f2loop->prev = v1loop->prev;
+ v2loop->prev->next = f1loop;
+ v1loop->prev->next = f2loop;
+
+ f1loop->next = v1loop;
+ f2loop->next = v2loop;
+ v1loop->prev = f1loop;
+ v2loop->prev = f2loop;
+
+ f2->loopbase = f2loop;
+ f->loopbase = f1loop;
+
+ /*validate both loops*/
+ /*I dont know how many loops are supposed to be in each face at this point! FIXME!*/
+
+ /*go through all of f2's loops and make sure they point to it properly.*/
+ f2len = BME_cycle_length(f2->loopbase);
+ for(i=0, curloop = f2->loopbase; i < f2len; i++, curloop = curloop->next) curloop->f = f2;
+
+ /*link up the new loops into the new edges radial*/
+ BME_radial_append(e, f1loop);
+ BME_radial_append(e, f2loop);
+
+
+ f2->len = f2len;
+
+ f1len = BME_cycle_length(f->loopbase);
+ f->len = f1len;
+
+ if(rl) *rl = f2loop;
+ return f2;
+}
+
+
+/**
+ * BME_JEKV
+ *
+ * JOIN EDGE KILL VERT:
+ * Takes a an edge and pointer to one of its vertices and collapses
+ * the edge on that vertex.
+ *
+ * Before: OE KE
+ * ------- -------
+ * | || |
+ * OV KV TV
+ *
+ *
+ * After: OE
+ * ---------------
+ * | |
+ * OV TV
+ *
+ *
+ * Restrictions:
+ * KV is a vertex that must have a valance of exactly two. Furthermore
+ * both edges in KV's disk cycle (OE and KE) must be unique (no double
+ * edges).
+ *
+ * It should also be noted that this euler has the possibility of creating
+ * faces with just 2 edges. It is up to the caller to decide what to do with
+ * these faces.
+ *
+ * Returns -
+ * 1 for success, 0 for failure.
+ */
+int BME_JEKV(BME_Mesh *bm, BME_Edge *ke, BME_Vert *kv)
+{
+ BME_Edge *oe;
+ BME_Vert *ov, *tv;
+ BME_CycleNode *diskbase;
+ BME_Loop *killoop,*nextl;
+ int len,radlen=0, halt = 0, i, valance1, valance2,edok;
+
+ if(BME_vert_in_edge(ke,kv) == 0) return 0;
+ diskbase = BME_disk_getpointer(kv->edge, kv);
+ len = BME_cycle_length(diskbase);
+
+ if(len == 2){
+ oe = BME_disk_nextedge(ke, kv);
+ tv = BME_edge_getothervert(ke, kv);
+ ov = BME_edge_getothervert(oe, kv);
+ halt = BME_verts_in_edge(kv, tv, oe); //check for double edges
+
+ if(halt) return 0;
+ else{
+
+ /*For verification later, count valance of ov and tv*/
+ diskbase = BME_disk_getpointer(ov->edge, ov);
+ valance1 = BME_cycle_length(diskbase);
+ diskbase = BME_disk_getpointer(tv->edge, tv);
+ valance2 = BME_cycle_length(diskbase);
+
+ /*remove oe from kv's disk cycle*/
+ BME_disk_remove_edge(oe,kv);
+ /*relink oe->kv to be oe->tv*/
+ BME_edge_swapverts(oe, kv, tv);
+ /*append oe to tv's disk cycle*/
+ BME_disk_append_edge(oe, tv);
+ /*remove ke from tv's disk cycle*/
+ BME_disk_remove_edge(ke, tv);
+
+
+
+ /*deal with radial cycle of ke*/
+ if(ke->loop){
+ /*first step, fix the neighboring loops of all loops in ke's radial cycle*/
+ radlen = BME_cycle_length(&(ke->loop->radial));
+ for(i=0,killoop = ke->loop; i<radlen; i++, killoop = BME_radial_nextloop(killoop)){
+ /*relink loops and fix vertex pointer*/
+ killoop->next->prev = killoop->prev;
+ killoop->prev->next = killoop->next;
+ if(killoop->next->v == kv) killoop->next->v = tv;
+
+ /*fix len attribute of face*/
+ killoop->f->len--;
+ if(killoop->f->loopbase == killoop) killoop->f->loopbase = killoop->next;
+ }
+ /*second step, remove all the hanging loops attached to ke*/
+ killoop = ke->loop;
+ radlen = BME_cycle_length(&(ke->loop->radial));
+ /*make sure we have enough room in bm->lpar*/
+ if(bm->lparlen < radlen){
+ MEM_freeN(bm->lpar);
+ bm->lpar = MEM_callocN(sizeof(BME_Loop *)* radlen, "BMesh Loop pointer array");
+ bm->lparlen = bm->lparlen * radlen;
+ }
+ /*this should be wrapped into a bme_free_radial function to be used by BME_KF as well...*/
+ i=0;
+ while(i<radlen){
+ bm->lpar[i] = killoop;
+ killoop = killoop->radial.next->data;
+ i++;
+ }
+ i=0;
+ while(i<radlen){
+ BME_free_loop(bm,bm->lpar[i]);
+ i++;
+ }
+ /*Validate radial cycle of oe*/
+ edok = BME_cycle_validate(radlen,&(oe->loop->radial));
+
+ }
+
+
+ /*Validate disk cycles*/
+ diskbase = BME_disk_getpointer(ov->edge,ov);
+ edok = BME_cycle_validate(valance1, diskbase);
+ if(!edok) BME_error();
+ diskbase = BME_disk_getpointer(tv->edge,tv);
+ edok = BME_cycle_validate(valance2, diskbase);
+ if(!edok) BME_error();
+
+ /*Validate loop cycle of all faces attached to oe*/
+ for(i=0,nextl = oe->loop; i<radlen; i++, nextl = BME_radial_nextloop(nextl)){
+ edok = BME_cycle_validate(nextl->f->len,nextl->f->loopbase);
+ if(!edok) BME_error();
+ }
+ /*deallocate edge*/
+ BLI_remlink(&(bm->edges), ke);
+ BME_free_edge(bm, ke);
+ /*deallocate vertex*/
+ BLI_remlink(&(bm->verts), kv);
+ BME_free_vert(bm, kv);
+ return 1;
+ }
+ }
+ return 0;
+}
+
+
+/**
+ * BME_loop_reverse
+ *
+ * FLIP FACE EULER
+ *
+ * Changes the winding order of a face from CW to CCW or vice versa.
+ * This euler is a bit peculiar in compairson to others as it is its
+ * own inverse.
+ *
+ * TODO: reinsert validation code.
+ *
+ * Returns -
+ * 1 for success, 0 for failure.
+ */
+
+int BME_loop_reverse(BME_Mesh *bm, BME_Poly *f){
+ BME_Loop *l = f->loopbase, *curloop, *oldprev, *oldnext;
+ int i, j, edok, len = 0;
+
+ len = BME_cycle_length(l);
+ if(bm->edarlen < len){
+ MEM_freeN(bm->edar);
+ bm->edar = MEM_callocN(sizeof(BME_Edge *)* len, "BMesh Edge pointer array");
+ bm->edarlen = len;
+ }
+
+ for(i=0, curloop = l; i< len; i++, curloop=curloop->next){
+ curloop->e->eflag1 = 0;
+ curloop->e->eflag2 = BME_cycle_length(&curloop->radial);
+ BME_radial_remove_loop(curloop, curloop->e);
+ /*in case of border edges we HAVE to zero out curloop->radial Next/Prev*/
+ curloop->radial.next = curloop->radial.prev = NULL;
+ bm->edar[i] = curloop->e;
+ }
+
+ /*actually reverse the loop. This belongs in BME_cycle_reverse!*/
+ for(i=0, curloop = l; i < len; i++){
+ oldnext = curloop->next;
+ oldprev = curloop->prev;
+ curloop->next = oldprev;
+ curloop->prev = oldnext;
+ curloop = oldnext;
+ }
+
+ if(len == 2){ //two edged face
+ //do some verification here!
+ l->e = bm->edar[1];
+ l->next->e = bm->edar[0];
+ }
+ else{
+ for(i=0, curloop = l; i < len; i++, curloop = curloop->next){
+ edok = 0;
+ for(j=0; j < len; j++){
+ edok = BME_verts_in_edge(curloop->v, curloop->next->v, bm->edar[j]);
+ if(edok){
+ curloop->e = bm->edar[j];
+ break;
+ }
+ }
+ }
+ }
+ /*rebuild radial*/
+ for(i=0, curloop = l; i < len; i++, curloop = curloop->next) BME_radial_append(curloop->e, curloop);
+
+ /*validate radial*/
+ for(i=0, curloop = l; i < len; i++, curloop = curloop->next){
+ edok = BME_cycle_validate(curloop->e->eflag2, &(curloop->radial));
+ if(!edok){
+ BME_error();
+ }
+ }
+ return 1;
+}
+
+/**
+ * BME_JFKE
+ *
+ * JOIN FACE KILL EDGE:
+ *
+ * Takes two faces joined by a single 2-manifold edge and fuses them togather.
+ * The edge shared by the faces must not be connected to any other edges which have
+ * Both faces in its radial cycle
+ *
+ * Examples:
+ *
+ * A B
+ * ---------- ----------
+ * | | | |
+ * | f1 | | f1 |
+ * v1========v2 = Ok! v1==V2==v3 == Wrong!
+ * | f2 | | f2 |
+ * | | | |
+ * ---------- ----------
+ *
+ * In the example A, faces f1 and f2 are joined by a single edge, and the euler can safely be used.
+ * In example B however, f1 and f2 are joined by multiple edges and will produce an error. The caller
+ * in this case should call BME_JEKV on the extra edges before attempting to fuse f1 and f2.
+ *
+ * Also note that the order of arguments decides whether or not certain per-face attributes are present
+ * in the resultant face. For instance vertex winding, material index, smooth flags, ect are inherited
+ * from f1, not f2.
+ *
+ * Returns -
+ * A BME_Poly pointer
+*/
+
+BME_Poly *BME_JFKE(BME_Mesh *bm, BME_Poly *f1, BME_Poly *f2, BME_Edge *e)
+{
+
+ BME_Loop *curloop, *f1loop=NULL, *f2loop=NULL;
+ int loopok = 0, newlen = 0,i, f1len=0, f2len=0, radlen=0, edok;
+
+ if(f1 == f2) return NULL; //can't join a face to itself
+ /*verify that e is in both f1 and f2*/
+ f1len = BME_cycle_length(f1->loopbase);
+ f2len = BME_cycle_length(f2->loopbase);
+ for(i=0, curloop = f1->loopbase; i < f1len; i++, curloop = curloop->next){
+ if(curloop->e == e){
+ f1loop = curloop;
+ break;
+ }
+ }
+ for(i=0, curloop = f2->loopbase; i < f2len; i++, curloop = curloop->next){
+ if(curloop->e==e){
+ f2loop = curloop;
+ break;
+ }
+ }
+ if(!(f1loop && f2loop)) return NULL;
+
+ /*validate that edge is 2-manifold edge*/
+ radlen = BME_cycle_length(&(f1loop->radial));
+ if(radlen != 2) return NULL;
+
+ /*validate direction of f2's loop cycle is compatible.*/
+ if(f1loop->v == f2loop->v) return NULL;
+
+ /*
+ Finally validate that for each face, each vertex has another edge in its disk cycle that is
+ not e, and not shared.
+ */
+ if(BME_radial_find_face(f1loop->next->e,f2)) return NULL;
+ if(BME_radial_find_face(f1loop->prev->e,f2)) return NULL;
+ if(BME_radial_find_face(f2loop->next->e,f1)) return NULL;
+ if(BME_radial_find_face(f2loop->prev->e,f1)) return NULL;
+
+ /*join the two loops*/
+ f1loop->prev->next = f2loop->next;
+ f2loop->next->prev = f1loop->prev;
+
+ f1loop->next->prev = f2loop->prev;
+ f2loop->prev->next = f1loop->next;
+
+ /*if f1loop was baseloop, give f1loop->next the base.*/
+ if(f1->loopbase == f1loop) f1->loopbase = f1loop->next;
+
+ /*validate the new loop*/
+ loopok = BME_cycle_validate((f1len+f2len)-2, f1->loopbase);
+ if(!loopok) BME_error();
+
+ /*make sure each loop points to the proper face*/
+ newlen = BME_cycle_length(f1->loopbase);
+ for(i = 0, curloop = f1->loopbase; i < newlen; i++, curloop = curloop->next) curloop->f = f1;
+
+ f1->len = newlen;
+
+ edok = BME_cycle_validate(f1->len, f1->loopbase);
+ if(!edok) BME_error();
+
+ /*remove edge from the disk cycle of its two vertices.*/
+ BME_disk_remove_edge(f1loop->e, f1loop->e->v1);
+ BME_disk_remove_edge(f1loop->e, f1loop->e->v2);
+
+ /*deallocate edge and its two loops as well as f2*/
+ BLI_remlink(&(bm->edges), f1loop->e);
+ BLI_remlink(&(bm->polys), f2);
+ BME_free_edge(bm, f1loop->e);
+ BME_free_loop(bm, f1loop);
+ BME_free_loop(bm, f2loop);
+ BME_free_poly(bm, f2);
+ return f1;
+}
diff --git a/source/blender/blenkernel/intern/BME_mesh.c b/source/blender/blenkernel/intern/BME_mesh.c
new file mode 100644
index 00000000000..ad46a7c1eb7
--- /dev/null
+++ b/source/blender/blenkernel/intern/BME_mesh.c
@@ -0,0 +1,285 @@
+/**
+ * BME_mesh.c jan 2007
+ *
+ * BMesh mesh level functions.
+ *
+ * $Id: BME_eulers.c,v 1.00 2007/01/17 17:42:01 Briggs Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2007 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Geoffrey Bantle.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+
+#include "MEM_guardedalloc.h"
+#include "DNA_listBase.h"
+#include "BLI_blenlib.h"
+#include "BKE_utildefines.h"
+#include "BKE_bmesh.h"
+#include "bmesh_private.h"
+
+
+/*
+ * BME MAKE MESH
+ *
+ * Allocates a new BME_Mesh structure.
+ * Returns -
+ * Pointer to a Bmesh
+ *
+*/
+
+BME_Mesh *BME_make_mesh(int allocsize[4])
+{
+ /*allocate the structure*/
+ BME_Mesh *bm = MEM_callocN(sizeof(BME_Mesh),"BMesh");
+ /*allocate the memory pools for the mesh elements*/
+ bm->vpool = BLI_mempool_create(sizeof(BME_Vert), allocsize[0], allocsize[0]);
+ bm->epool = BLI_mempool_create(sizeof(BME_Edge), allocsize[1], allocsize[1]);
+ bm->lpool = BLI_mempool_create(sizeof(BME_Loop), allocsize[2], allocsize[2]);
+ bm->ppool = BLI_mempool_create(sizeof(BME_Poly), allocsize[3], allocsize[3]);
+ return bm;
+}
+/*
+ * BME FREE MESH
+ *
+ * Frees a BME_Mesh structure.
+*/
+
+void BME_free_mesh(BME_Mesh *bm)
+{
+ BME_Vert *v;
+ BME_Edge *e;
+ BME_Loop *l;
+ BME_Poly *f;
+
+ for(v=bm->verts.first; v; v=v->next) CustomData_bmesh_free_block(&bm->vdata, &v->data);
+ for(e=bm->edges.first; e; e=e->next) CustomData_bmesh_free_block(&bm->edata, &e->data);
+ for(f=bm->polys.first; f; f=f->next){
+ CustomData_bmesh_free_block(&bm->pdata, &f->data);
+ l = f->loopbase;
+ do{
+ CustomData_bmesh_free_block(&bm->ldata, &l->data);
+ l = l->next;
+ }while(l!=f->loopbase);
+ }
+
+ /*Free custom data pools, This should probably go in CustomData_free?*/
+ if(bm->vdata.totlayer) BLI_mempool_destroy(bm->vdata.pool);
+ if(bm->edata.totlayer) BLI_mempool_destroy(bm->edata.pool);
+ if(bm->ldata.totlayer) BLI_mempool_destroy(bm->ldata.pool);
+ if(bm->pdata.totlayer) BLI_mempool_destroy(bm->pdata.pool);
+
+ /*free custom data*/
+ CustomData_free(&bm->vdata,0);
+ CustomData_free(&bm->edata,0);
+ CustomData_free(&bm->ldata,0);
+ CustomData_free(&bm->pdata,0);
+
+ /*destroy element pools*/
+ BLI_mempool_destroy(bm->vpool);
+ BLI_mempool_destroy(bm->epool);
+ BLI_mempool_destroy(bm->ppool);
+ BLI_mempool_destroy(bm->lpool);
+
+ MEM_freeN(bm);
+}
+
+/*
+ * BME MODEL BEGIN AND END
+ *
+ * These two functions represent the 'point of entry' for tools. Every BMesh tool
+ * must begin with a call to BME_model_end() and finish with a call to BME_model_end().
+ * No modification of mesh data is allowed except in between these two calls.
+ *
+ * The purpose of these calls is allow for housekeeping tasks to be performed,
+ * such as allocating/freeing scratch arrays or performing debug validation of
+ * the mesh structure.
+ *
+ * Returns -
+ * Nothing
+ *
+*/
+
+int BME_model_begin(BME_Mesh *bm){
+ /*Initialize some scratch pointer arrays used by eulers*/
+ bm->vtar = MEM_callocN(sizeof(BME_Vert *) * 1024, "BMesh scratch vert array");
+ bm->edar = MEM_callocN(sizeof(BME_Edge *) * 1024, "BMesh scratch edge array");
+ bm->lpar = MEM_callocN(sizeof(BME_Loop *) * 1024, "BMesh scratch loop array");
+ bm->plar = MEM_callocN(sizeof(BME_Poly *) * 1024, "BMesh scratch poly array");
+
+ bm->vtarlen = bm->edarlen = bm->lparlen = bm->plarlen = 1024;
+
+ return 1;
+}
+
+void BME_model_end(BME_Mesh *bm){
+ int meshok, totvert, totedge, totpoly;
+
+ totvert = BLI_countlist(&(bm->verts));
+ totedge = BLI_countlist(&(bm->edges));
+ totpoly = BLI_countlist(&(bm->polys));
+
+ if(bm->vtar) MEM_freeN(bm->vtar);
+ if(bm->edar) MEM_freeN(bm->edar);
+ if(bm->lpar) MEM_freeN(bm->lpar);
+ if(bm->plar) MEM_freeN(bm->plar);
+
+ bm->vtar = NULL;
+ bm->edar = NULL;
+ bm->lpar = NULL;
+ bm->plar = NULL;
+ bm->vtarlen = bm->edarlen = bm->lparlen = bm->plarlen = 0;
+
+
+ if(bm->totvert!=totvert || bm->totedge!=totedge || bm->totpoly!=totpoly)
+ BME_error();
+
+ meshok = BME_validate_mesh(bm, 1);
+ if(!meshok){
+ BME_error();
+ }
+}
+
+/*
+ * BME VALIDATE MESH
+ *
+ * There are several levels of validation for meshes. At the
+ * Euler level, some basic validation is done to local topology.
+ * To catch more subtle problems however, BME_validate_mesh() is
+ * called by BME_model_end() whenever a tool is done executing.
+ * The purpose of this function is to insure that during the course
+ * of tool execution that nothing has been done to invalidate the
+ * structure, and if it has, provide a way of reporting that so that
+ * we can restore the proper structure from a backup. Since a full mesh
+ * validation would be too expensive, this is presented as a compromise.
+ *
+ * TODO
+ *
+ * -Make this only part of debug builds
+ */
+
+#define VHALT(halt) {BME_error(); if(halt) return 0;}
+
+int BME_validate_mesh(struct BME_Mesh *bm, int halt)
+{
+ BME_Vert *v;
+ BME_Edge *e;
+ BME_Poly *f;
+ BME_Loop *l;
+ BME_CycleNode *diskbase;
+ int i, ok;
+
+ /*Simple edge verification*/
+ for(e=bm->edges.first; e; e=e->next){
+ if(e->v1 == e->v2) VHALT(halt);
+ /*validate e->d1.data and e->d2.data*/
+ if(e->d1.data != e || e->d2.data != e) VHALT(halt);
+ /*validate e->loop->e*/
+ if(e->loop){
+ if(e->loop->e != e) VHALT(halt);
+ }
+ }
+
+ /*calculate disk cycle lengths*/
+ for(v=bm->verts.first; v; v=v->next) v->tflag1 = v->tflag2 = 0;
+ for(e=bm->edges.first; e; e=e->next){
+ e->v1->tflag1++;
+ e->v2->tflag1++;
+ }
+ /*Validate vertices and disk cycle*/
+ for(v=bm->verts.first; v; v=v->next){
+ /*validate v->edge pointer*/
+ if(v->tflag1){
+ if(v->edge){
+ ok = BME_vert_in_edge(v->edge,v);
+ if(!ok) VHALT(halt);
+ /*validate length of disk cycle*/
+ diskbase = BME_disk_getpointer(v->edge, v);
+ ok = BME_cycle_validate(v->tflag1, diskbase);
+ if(!ok) VHALT(halt);
+ /*validate that each edge in disk cycle contains V*/
+ for(i=0, e=v->edge; i < v->tflag1; i++, e = BME_disk_nextedge(e,v)){
+ ok = BME_vert_in_edge(e, v);
+ if(!ok) VHALT(halt);
+ }
+ }
+ else VHALT(halt);
+ }
+ }
+ /*validate edges*/
+ for(e=bm->edges.first; e; e=e->next){
+ /*seperate these into BME_disk_hasedge (takes pointer to edge)*/
+ /*search v1 disk cycle for edge*/
+ ok = BME_disk_hasedge(e->v1,e);
+ if(!ok) VHALT(halt);
+ /*search v2 disk cycle for edge*/
+ ok = BME_disk_hasedge(e->v2,e);
+ if(!ok) VHALT(halt);
+ }
+
+ for(e=bm->edges.first; e; e=e->next) e->tflag2 = 0; //store incident faces
+ /*Validate the loop cycle integrity.*/
+ for(f=bm->polys.first; f; f=f->next){
+ ok = BME_cycle_length(f->loopbase);
+ if(ok > 1){
+ f->tflag1 = ok;
+ }
+ else VHALT(halt);
+ for(i=0, l=f->loopbase; i < f->tflag1; i++, l=l->next){
+ /*verify loop->v pointers*/
+ ok = BME_verts_in_edge(l->v, l->next->v, l->e);
+ if(!ok) VHALT(halt);
+ /*verify radial node data pointer*/
+ if(l->radial.data != l) VHALT(halt);
+ /*validate l->e->loop poitner*/
+ if(l->e->loop == NULL) VHALT(halt);
+ /*validate l->f pointer*/
+ if(l->f != f) VHALT(halt);
+ /*see if l->e->loop is actually in radial cycle*/
+
+ l->e->tflag2++;
+ }
+ }
+
+ /*validate length of radial cycle*/
+ for(e=bm->edges.first; e; e=e->next){
+ if(e->loop){
+ ok = BME_cycle_validate(e->tflag2,&(e->loop->radial));
+ if(!ok) VHALT(halt);
+ }
+ }
+
+ /*validate that EIDs are within range... if not indicates corrupted mem*/
+
+ /*if we get this far, pretty safe to return 1*/
+ return 1;
+}
+
+/* Currently just a convient place for a breakpoint.
+ Probably should take an error string
+*/
+void BME_error(void){
+ printf("BME modelling error!");
+}
diff --git a/source/blender/blenkernel/intern/BME_structure.c b/source/blender/blenkernel/intern/BME_structure.c
new file mode 100644
index 00000000000..ca27f5efd10
--- /dev/null
+++ b/source/blender/blenkernel/intern/BME_structure.c
@@ -0,0 +1,627 @@
+/**
+ * BME_structure.c jan 2007
+ *
+ * Low level routines for manipulating the BMesh structure.
+ *
+ * $Id: BME_structure.c,v 1.00 2007/01/17 17:42:01 Briggs Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2007 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Geoffrey Bantle.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include <limits.h>
+#include "MEM_guardedalloc.h"
+
+#include "DNA_listBase.h"
+#include "BKE_utildefines.h"
+#include "BKE_bmesh.h"
+#include "BLI_blenlib.h"
+#include "BLI_linklist.h"
+#include "BLI_ghash.h"
+/**
+ * MISC utility functions.
+ *
+ */
+
+int BME_vert_in_edge(BME_Edge *e, BME_Vert *v){
+ if(e->v1 == v || e->v2 == v) return 1;
+ return 0;
+}
+int BME_verts_in_edge(BME_Vert *v1, BME_Vert *v2, BME_Edge *e){
+ if(e->v1 == v1 && e->v2 == v2) return 1;
+ else if(e->v1 == v2 && e->v2 == v1) return 1;
+ return 0;
+}
+
+BME_Vert *BME_edge_getothervert(BME_Edge *e, BME_Vert *v){
+ if(e->v1 == v) return e->v2;
+ else if(e->v2 == v) return e->v1;
+ return NULL;
+}
+
+int BME_edge_swapverts(BME_Edge *e, BME_Vert *orig, BME_Vert *new){
+ if(e->v1 == orig){
+ e->v1 = new;
+ e->d1.next = NULL;
+ e->d1.prev = NULL;
+ return 1;
+ }
+ else if(e->v2 == orig){
+ e->v2 = new;
+ e->d2.next = NULL;
+ e->d2.prev = NULL;
+ return 1;
+ }
+ return 0;
+}
+
+/**
+ * ALLOCATION/DEALLOCATION FUNCTIONS
+ */
+
+BME_Vert *BME_addvertlist(BME_Mesh *bm, BME_Vert *example){
+ BME_Vert *v=NULL;
+ v = BLI_mempool_alloc(bm->vpool);
+ v->next = v->prev = NULL;
+ v->EID = bm->nextv;
+ v->co[0] = v->co[1] = v->co[2] = 0.0f;
+ v->no[0] = v->no[1] = v->no[2] = 0.0f;
+ v->edge = NULL;
+ v->data = NULL;
+ v->eflag1 = v->eflag2 = v->tflag1 = v->tflag2 = 0;
+ v->flag = v->h = 0;
+ v->bweight = 0.0f;
+ BLI_addtail(&(bm->verts), v);
+ bm->nextv++;
+ bm->totvert++;
+
+ if(example){
+ VECCOPY(v->co,example->co);
+ CustomData_bmesh_copy_data(&bm->vdata, &bm->vdata, example->data, &v->data);
+ }
+ else
+ CustomData_bmesh_set_default(&bm->vdata, &v->data);
+
+ return v;
+}
+BME_Edge *BME_addedgelist(BME_Mesh *bm, BME_Vert *v1, BME_Vert *v2, BME_Edge *example){
+ BME_Edge *e=NULL;
+ e = BLI_mempool_alloc(bm->epool);
+ e->next = e->prev = NULL;
+ e->EID = bm->nexte;
+ e->v1 = v1;
+ e->v2 = v2;
+ e->d1.next = e->d1.prev = e->d2.next = e->d2.prev = NULL;
+ e->d1.data = e;
+ e->d2.data = e;
+ e->loop = NULL;
+ e->data = NULL;
+ e->eflag1 = e->eflag2 = e->tflag1 = e->tflag2 = 0;
+ e->flag = e->h = 0;
+ e->crease = e->bweight = 0.0f;
+ bm->nexte++;
+ bm->totedge++;
+ BLI_addtail(&(bm->edges), e);
+
+ if(example)
+ CustomData_bmesh_copy_data(&bm->edata, &bm->edata, example->data, &e->data);
+ else
+ CustomData_bmesh_set_default(&bm->edata, &e->data);
+
+
+ return e;
+}
+BME_Loop *BME_create_loop(BME_Mesh *bm, BME_Vert *v, BME_Edge *e, BME_Poly *f, BME_Loop *example){
+ BME_Loop *l=NULL;
+ l = BLI_mempool_alloc(bm->lpool);
+ l->next = l->prev = NULL;
+ l->EID = bm->nextl;
+ l->radial.next = l->radial.prev = NULL;
+ l->radial.data = l;
+ l->v = v;
+ l->e = e;
+ l->f = f;
+ l->data = NULL;
+ l->eflag1 = l->eflag2 = l->tflag1 = l->tflag2 = 0;
+ l->flag = l->h = 0; //stupid waste!
+ bm->nextl++;
+ bm->totloop++;
+
+ if(example)
+ CustomData_bmesh_copy_data(&bm->ldata, &bm->ldata, example->data, &l->data);
+ else
+ CustomData_bmesh_set_default(&bm->ldata, &l->data);
+
+ return l;
+}
+
+BME_Poly *BME_addpolylist(BME_Mesh *bm, BME_Poly *example){
+ BME_Poly *f = NULL;
+ f = BLI_mempool_alloc(bm->ppool);
+ f->next = f->prev = NULL;
+ f->EID = bm->nextp;
+ f->loopbase = NULL;
+ f->len = 0;
+ f->data = NULL;
+ f->eflag1 = f->eflag2 = f->tflag1 = f->tflag2 = 0;
+ f->flag = f->h = f->mat_nr;
+ BLI_addtail(&(bm->polys),f);
+ bm->nextp++;
+ bm->totpoly++;
+
+ if(example)
+ CustomData_bmesh_copy_data(&bm->pdata, &bm->pdata, example->data, &f->data);
+ else
+ CustomData_bmesh_set_default(&bm->pdata, &f->data);
+
+
+ return f;
+}
+
+/* free functions dont do much *yet*. When per-vertex, per-edge and per-face/faceloop
+ data is added though these will be needed.
+*/
+void BME_free_vert(BME_Mesh *bm, BME_Vert *v){
+ bm->totvert--;
+ CustomData_bmesh_free_block(&bm->vdata, &v->data);
+ BLI_mempool_free(bm->vpool, v);
+}
+void BME_free_edge(BME_Mesh *bm, BME_Edge *e){
+ bm->totedge--;
+ CustomData_bmesh_free_block(&bm->edata, &e->data);
+ BLI_mempool_free(bm->epool, e);
+}
+void BME_free_poly(BME_Mesh *bm, BME_Poly *f){
+ bm->totpoly--;
+ CustomData_bmesh_free_block(&bm->pdata, &f->data);
+ BLI_mempool_free(bm->ppool, f);
+}
+void BME_free_loop(BME_Mesh *bm, BME_Loop *l){
+ bm->totloop--;
+ CustomData_bmesh_free_block(&bm->ldata, &l->data);
+ BLI_mempool_free(bm->lpool, l);
+}
+/**
+ * BMESH CYCLES
+ *
+ * Cycles are circular doubly linked lists that form the basis of adjacency
+ * information in the BME modeller. Full adjacency relations can be derived
+ * from examining these cycles very quickly. Although each cycle is a double
+ * circular linked list, each one is considered to have a 'base' or 'head',
+ * and care must be taken by Euler code when modifying the contents of a cycle.
+ *
+ * The contents of this file are split into two parts. First there are the
+ * BME_cycle family of functions which are generic circular double linked list
+ * procedures. The second part contains higher level procedures for supporting
+ * modification of specific cycle types.
+ *
+ * The three cycles explicitly stored in the BMesh data structure are as follows:
+ *
+ * 1: The Disk Cycle - A circle of edges around a vertex
+ * Base: vertex->edge pointer.
+ *
+ * This cycle is the most complicated in terms of its structure. Each BME_Edge contains
+ * two BME_CycleNode structures to keep track of that edge's membership in the disk cycle
+ * of each of its vertices. However for any given vertex it may be the first in some edges
+ * in its disk cycle and the second for others. The BME_disk_XXX family of functions contain
+ * some nice utilities for navigating disk cycles in a way that hides this detail from the
+ * tool writer.
+ *
+ * Note that the disk cycle is completley independant from face data. One advantage of this
+ * is that wire edges are fully integrated into the topology database. Another is that the
+ * the disk cycle has no problems dealing with non-manifold conditions involving faces.
+ *
+ * Functions relating to this cycle:
+ *
+ * BME_disk_append_edge
+ * BME_disk_remove_edge
+ * BME_disk_nextedge
+ * BME_disk_getpointer
+ *
+ * 2: The Radial Cycle - A circle of face edges (BME_Loop) around an edge
+ * Base: edge->loop->radial structure.
+ *
+ * The radial cycle is similar to the radial cycle in the radial edge data structure.*
+ * Unlike the radial edge however, the radial cycle does not require a large amount of memory
+ * to store non-manifold conditions since BMesh does not keep track of region/shell
+ * information.
+ *
+ * Functions relating to this cycle:
+ *
+ * BME_radial_append
+ * BME_radial_remove_loop
+ * BME_radial_nextloop
+ * BME_radial_find_face
+ *
+ *
+ * 3: The Loop Cycle - A circle of face edges around a polygon.
+ * Base: polygon->loopbase.
+ *
+ * The loop cycle keeps track of a faces vertices and edges. It should be noted that the
+ * direction of a loop cycle is either CW or CCW depending on the face normal, and is
+ * not oriented to the faces editedges.
+ *
+ * Functions relating to this cycle:
+ *
+ * BME_cycle_XXX family of functions.
+ *
+ *
+ * Note that the order of elements in all cycles except the loop cycle is undefined. This
+ * leads to slightly increased seek time for deriving some adjacency relations, however the
+ * advantage is that no intrinsic properties of the data structures are dependant upon the
+ * cycle order and all non-manifold conditions are represented trivially.
+ *
+*/
+
+
+void BME_cycle_append(void *h, void *nt)
+{
+ BME_CycleNode *oldtail, *head, *newtail;
+
+ head = (BME_CycleNode*)h;
+ newtail = (BME_CycleNode*)nt;
+
+ if(head->next == NULL){
+ head->next = newtail;
+ head->prev = newtail;
+ newtail->next = head;
+ newtail->prev = head;
+ }
+ else{
+ oldtail = head->prev;
+ oldtail->next = newtail;
+ newtail->next = head;
+ newtail->prev = oldtail;
+ head->prev = newtail;
+
+ }
+}
+
+/**
+ * BME_cycle_length
+ *
+ * Count the nodes in a cycle.
+ *
+ * Returns -
+ * Integer
+ */
+
+int BME_cycle_length(void *h){
+
+ int len = 0;
+ BME_CycleNode *head, *curnode;
+ head = (BME_CycleNode*)h;
+
+ if(head){
+ len = 1;
+ for(curnode = head->next; curnode != head; curnode=curnode->next){
+ if(len == INT_MAX){ //check for infinite loop/corrupted cycle
+ return -1;
+ }
+ len++;
+ }
+ }
+ return len;
+}
+
+
+/**
+ * BME_cycle_remove
+ *
+ * Removes a node from a cycle.
+ *
+ * Returns -
+ * 1 for success, 0 for failure.
+ */
+
+int BME_cycle_remove(void *h, void *remn)
+{
+ int i, len;
+ BME_CycleNode *head, *remnode, *curnode;
+
+ head = (BME_CycleNode*)h;
+ remnode = (BME_CycleNode*)remn;
+ len = BME_cycle_length(h);
+
+ if(len == 1 && head == remnode){
+ head->next = NULL;
+ head->prev = NULL;
+ return 1;
+ }
+ else{
+ for(i=0, curnode = head; i < len; curnode = curnode->next){
+ if(curnode == remnode){
+ remnode->prev->next = remnode->next;
+ remnode->next->prev = remnode->prev;
+ /*zero out remnode pointers, important!*/
+ //remnode->next = NULL;
+ //remnode->prev = NULL;
+ return 1;
+
+ }
+ }
+ }
+ return 0;
+}
+
+/**
+ * BME_cycle_validate
+ *
+ * Validates a cycle. Takes as an argument the expected length of the cycle and
+ * a pointer to the cycle head or base.
+ *
+ *
+ * Returns -
+ * 1 for success, 0 for failure.
+ */
+
+int BME_cycle_validate(int len, void *h){
+ int i;
+ BME_CycleNode *curnode, *head;
+ head = (BME_CycleNode*)h;
+
+ /*forward validation*/
+ for(i = 0, curnode = head; i < len; i++, curnode = curnode->next);
+ if(curnode != head) return 0;
+
+ /*reverse validation*/
+ for(i = 0, curnode = head; i < len; i++, curnode = curnode->prev);
+ if(curnode != head) return 0;
+
+ return 1;
+}
+
+/*Begin Disk Cycle routines*/
+
+/**
+ * BME_disk_nextedge
+ *
+ * Find the next edge in a disk cycle
+ *
+ * Returns -
+ * Pointer to the next edge in the disk cycle for the vertex v.
+ */
+
+BME_Edge *BME_disk_nextedge(BME_Edge *e, BME_Vert *v)
+{
+ if(BME_vert_in_edge(e, v)){
+ if(e->v1 == v) return e->d1.next->data;
+ else if(e->v2 == v) return e->d2.next->data;
+ }
+ return NULL;
+}
+
+/**
+ * BME_disk_getpointer
+ *
+ * Given an edge and one of its vertices, find the apporpriate CycleNode
+ *
+ * Returns -
+ * Pointer to BME_CycleNode.
+ */
+BME_CycleNode *BME_disk_getpointer(BME_Edge *e, BME_Vert *v){
+ /*returns pointer to the cycle node for the appropriate vertex in this disk*/
+ if(e->v1 == v) return &(e->d1);
+ else if (e->v2 == v) return &(e->d2);
+ return NULL;
+}
+
+/**
+ * BME_disk_append_edge
+ *
+ * Appends edge to the end of a vertex disk cycle.
+ *
+ * Returns -
+ * 1 for success, 0 for failure
+ */
+
+int BME_disk_append_edge(BME_Edge *e, BME_Vert *v)
+{
+
+ BME_CycleNode *base, *tail;
+
+ if(BME_vert_in_edge(e, v) == 0) return 0; /*check to make sure v is in e*/
+
+ /*check for loose vert first*/
+ if(v->edge == NULL){
+ v->edge = e;
+ base = tail = BME_disk_getpointer(e, v);
+ BME_cycle_append(base, tail); /*circular reference is ok!*/
+ return 1;
+ }
+
+ /*insert e at the end of disk cycle and make it the new v->edge*/
+ base = BME_disk_getpointer(v->edge, v);
+ tail = BME_disk_getpointer(e, v);
+ BME_cycle_append(base, tail);
+ return 1;
+}
+
+/**
+ * BME_disk_remove_edge
+ *
+ * Removes an edge from a disk cycle. If the edge to be removed is
+ * at the base of the cycle, the next edge becomes the new base.
+ *
+ *
+ * Returns -
+ * Nothing
+ */
+
+void BME_disk_remove_edge(BME_Edge *e, BME_Vert *v)
+{
+ BME_CycleNode *base, *remnode;
+ BME_Edge *newbase;
+ int len;
+
+ base = BME_disk_getpointer(v->edge, v);
+ remnode = BME_disk_getpointer(e, v);
+
+ /*first deal with v->edge pointer...*/
+ len = BME_cycle_length(base);
+ if(len == 1) newbase = NULL;
+ else if(v->edge == e) newbase = base->next-> data;
+ else newbase = v->edge;
+
+ /*remove and rebase*/
+ BME_cycle_remove(base, remnode);
+ v->edge = newbase;
+}
+
+/**
+ * BME_disk_next_edgeflag
+ *
+ * Searches the disk cycle of v, starting with e, for the
+ * next edge that has either eflag or tflag.
+ *
+ * BME_Edge pointer.
+ */
+
+BME_Edge *BME_disk_next_edgeflag(BME_Edge *e, BME_Vert *v, int eflag, int tflag){
+
+ BME_CycleNode *diskbase;
+ BME_Edge *curedge;
+ int len, ok;
+
+ if(eflag && tflag) return NULL;
+
+ ok = BME_vert_in_edge(e,v);
+ if(ok){
+ diskbase = BME_disk_getpointer(e, v);
+ len = BME_cycle_length(diskbase);
+ curedge = BME_disk_nextedge(e,v);
+ while(curedge != e){
+ if(tflag){
+ if(curedge->tflag1 == tflag) return curedge;
+ }
+ else if(eflag){
+ if(curedge->eflag1 == eflag) return curedge;
+ }
+ curedge = BME_disk_nextedge(curedge, v);
+ }
+ }
+ return NULL;
+}
+
+/**
+ * BME_disk_count_edgeflag
+ *
+ * Counts number of edges in this verts disk cycle which have
+ * either eflag or tflag (but not both!)
+ *
+ * Returns -
+ * Integer.
+ */
+
+int BME_disk_count_edgeflag(BME_Vert *v, int eflag, int tflag){
+ BME_CycleNode *diskbase;
+ BME_Edge *curedge;
+ int i, len=0, count=0;
+
+ if(v->edge){
+ if(eflag && tflag) return 0; /*tflag and eflag are reserved for different functions!*/
+ diskbase = BME_disk_getpointer(v->edge, v);
+ len = BME_cycle_length(diskbase);
+
+ for(i = 0, curedge=v->edge; i<len; i++){
+ if(tflag){
+ if(curedge->tflag1 == tflag) count++;
+ }
+ else if(eflag){
+ if(curedge->eflag1 == eflag) count++;
+ }
+ curedge = BME_disk_nextedge(curedge, v);
+ }
+ }
+ return count;
+}
+
+int BME_disk_hasedge(BME_Vert *v, BME_Edge *e){
+ BME_CycleNode *diskbase;
+ BME_Edge *curedge;
+ int i, len=0;
+
+ if(v->edge){
+ diskbase = BME_disk_getpointer(v->edge,v);
+ len = BME_cycle_length(diskbase);
+
+ for(i = 0, curedge=v->edge; i<len; i++){
+ if(curedge == e) return 1;
+ else curedge=BME_disk_nextedge(curedge, v);
+ }
+ }
+ return 0;
+}
+/*end disk cycle routines*/
+
+BME_Loop *BME_radial_nextloop(BME_Loop *l){
+ return (BME_Loop*)(l->radial.next->data);
+}
+
+void BME_radial_append(BME_Edge *e, BME_Loop *l){
+ if(e->loop == NULL) e->loop = l;
+ BME_cycle_append(&(e->loop->radial), &(l->radial));
+}
+
+void BME_radial_remove_loop(BME_Loop *l, BME_Edge *e)
+{
+ BME_Loop *newbase;
+ int len;
+
+ /*deal with edge->loop pointer*/
+ len = BME_cycle_length(&(e->loop->radial));
+ if(len == 1) newbase = NULL;
+ else if(e->loop == l) newbase = e->loop->radial.next->data;
+ else newbase = e->loop;
+
+ /*remove and rebase*/
+ BME_cycle_remove(&(e->loop->radial), &(l->radial));
+ e->loop = newbase;
+}
+
+int BME_radial_find_face(BME_Edge *e,BME_Poly *f)
+{
+
+ BME_Loop *curloop;
+ int i, len;
+
+ len = BME_cycle_length(&(e->loop->radial));
+ for(i = 0, curloop = e->loop; i < len; i++, curloop = curloop->radial.next->data){
+ if(curloop->f == f) return 1;
+ }
+ return 0;
+}
+
+struct BME_Loop *BME_loop_find_loop(struct BME_Poly *f, struct BME_Vert *v) {
+ BME_Loop *l;
+ int i, len;
+
+ len = BME_cycle_length(f->loopbase);
+ for (i = 0, l=f->loopbase; i < len; i++, l=l->next) {
+ if (l->v == v) return l;
+ }
+ return NULL;
+}
diff --git a/source/blender/blenkernel/intern/BME_tools.c b/source/blender/blenkernel/intern/BME_tools.c
new file mode 100644
index 00000000000..8aaa7aca023
--- /dev/null
+++ b/source/blender/blenkernel/intern/BME_tools.c
@@ -0,0 +1,1323 @@
+/**
+ * BME_tools.c jan 2007
+ *
+ * Functions for changing the topology of a mesh.
+ *
+ * $Id: BME_eulers.c,v 1.00 2007/01/17 17:42:01 Briggs Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2004 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Geoffrey Bantle and Levi Schooley.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include <math.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_listBase.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_mesh_types.h"
+#include "DNA_object_types.h"
+
+#include "BKE_utildefines.h"
+#include "BKE_bmesh.h"
+#include "BLI_arithb.h"
+#include "BLI_blenlib.h"
+
+/*split this all into a seperate bevel.c file in src*/
+
+/* ------- Bevel code starts here -------- */
+
+BME_TransData_Head *BME_init_transdata(int bufsize) {
+ BME_TransData_Head *td;
+
+ td = MEM_callocN(sizeof(BME_TransData_Head), "BMesh transdata header");
+ td->gh = BLI_ghash_new(BLI_ghashutil_ptrhash,BLI_ghashutil_ptrcmp);
+ td->ma = BLI_memarena_new(bufsize);
+ BLI_memarena_use_calloc(td->ma);
+
+ return td;
+}
+
+void BME_free_transdata(BME_TransData_Head *td) {
+ BLI_ghash_free(td->gh,NULL,NULL);
+ BLI_memarena_free(td->ma);
+ MEM_freeN(td);
+}
+
+BME_TransData *BME_assign_transdata(BME_TransData_Head *td, BME_Mesh *bm, BME_Vert *v,
+ float *co, float *org, float *vec, float *loc,
+ float factor, float weight, float maxfactor, float *max) {
+ BME_TransData *vtd;
+ int is_new = 0;
+
+ if (v == NULL) return NULL;
+
+ if ((vtd = BLI_ghash_lookup(td->gh, v)) == NULL && bm != NULL) {
+ vtd = BLI_memarena_alloc(td->ma, sizeof(*vtd));
+ BLI_ghash_insert(td->gh, v, vtd);
+ td->len++;
+ is_new = 1;
+ }
+
+ vtd->bm = bm;
+ vtd->v = v;
+ if (co != NULL) VECCOPY(vtd->co,co);
+ if (org == NULL && is_new) { VECCOPY(vtd->org,v->co); } /* default */
+ else if (org != NULL) VECCOPY(vtd->org,org);
+ if (vec != NULL) {
+ VECCOPY(vtd->vec,vec);
+ Normalize(vtd->vec);
+ }
+ vtd->loc = loc;
+
+ vtd->factor = factor;
+ vtd->weight = weight;
+ vtd->maxfactor = maxfactor;
+ vtd->max = max;
+
+ return vtd;
+}
+
+BME_TransData *BME_get_transdata(BME_TransData_Head *td, BME_Vert *v) {
+ BME_TransData *vtd;
+ vtd = BLI_ghash_lookup(td->gh, v);
+ return vtd;
+}
+
+/* a hack (?) to use the transdata memarena to allocate floats for use with the max limits */
+float *BME_new_transdata_float(BME_TransData_Head *td) {
+ return BLI_memarena_alloc(td->ma, sizeof(float));
+}
+
+static int BME_is_nonmanifold_vert(BME_Mesh *bm, BME_Vert *v) {
+ BME_Edge *e, *oe;
+ BME_Loop *l;
+ int len, count, flag;
+
+ if (v->edge == NULL) {
+ /* loose vert */
+ return 1;
+ }
+
+ /* count edges while looking for non-manifold edges */
+ oe = v->edge;
+ for (len=0,e=v->edge; e != oe || (e == oe && len == 0); len++,e=BME_disk_nextedge(e,v)) {
+ if (e->loop == NULL) {
+ /* loose edge */
+ return 1;
+ }
+
+ if (BME_cycle_length(&(e->loop->radial)) > 2) {
+ /* edge shared by more than two faces */
+ return 1;
+ }
+ }
+
+ count = 1;
+ flag = 1;
+ e = NULL;
+ oe = v->edge;
+ l = oe->loop;
+ while(e != oe) {
+ if (l->v == v) l = l->prev;
+ else l = l->next;
+ e = l->e;
+ count++; /* count the edges */
+
+ if (flag && l->radial.next->data == l) {
+ /* we've hit the edge of an open mesh, reset once */
+ flag = 0;
+ count = 1;
+ oe = e;
+ e = NULL;
+ l = oe->loop;
+ }
+ else if (l->radial.next->data == l) {
+ /* break the loop */
+ e = oe;
+ }
+ else {
+ l = l->radial.next->data;
+ }
+ }
+
+ if (count < len) {
+ /* vert shared by multiple regions */
+ return 1;
+ }
+
+ return 0;
+}
+
+/* a wrapper for BME_JFKE that [for now just] checks to
+ * make sure loop directions are compatible */
+static BME_Poly *BME_JFKE_safe(BME_Mesh *bm, BME_Poly *f1, BME_Poly *f2, BME_Edge *e) {
+ BME_Loop *l1, *l2;
+
+ l1 = e->loop;
+ l2 = l1->radial.next->data;
+ if (l1->v == l2->v) {
+ BME_loop_reverse(bm, f2);
+ }
+
+ return BME_JFKE(bm, f1, f2, e);
+}
+
+/* a wrapper for BME_SFME that transfers element flags */
+static BME_Poly *BME_split_face(BME_Mesh *bm, BME_Poly *f, BME_Vert *v1, BME_Vert *v2, BME_Loop **nl, BME_Edge *example) {
+ BME_Poly *nf;
+ nf = BME_SFME(bm,f,v1,v2,nl);
+ nf->flag = f->flag;
+ /* if the edge was selected, select this face, too */
+ if (example->flag & SELECT) f->flag |= ME_FACE_SEL;
+ nf->h = f->h;
+ nf->mat_nr = f->mat_nr;
+ if (nl && example) {
+ (*nl)->e->flag = example->flag;
+ (*nl)->e->h = example->h;
+ (*nl)->e->crease = example->crease;
+ (*nl)->e->bweight = example->bweight;
+ }
+
+ return nf;
+}
+
+
+static void BME_data_interp_from_verts(BME_Mesh *bm, BME_Vert *v1, BME_Vert *v2, BME_Vert *v, float fac)
+{
+ void *src[2];
+ float w[2];
+ if (v1->data && v2->data) {
+ src[0]= v1->data;
+ src[1]= v2->data;
+ w[0] = 1.0f-fac;
+ w[1] = fac;
+ CustomData_bmesh_interp(&bm->vdata, src, w, NULL, 2, v->data);
+ }
+}
+
+
+static void BME_data_facevert_edgesplit(BME_Mesh *bm, BME_Vert *v1, BME_Vert *v2, BME_Vert *v, BME_Edge *e1, float fac){
+ void *src[2];
+ float w[2];
+ BME_Loop *l=NULL, *v1loop = NULL, *vloop = NULL, *v2loop = NULL;
+
+ w[0] = 1.0f - fac;
+ w[1] = fac;
+
+ if(!e1->loop) return;
+ l = e1->loop;
+ do{
+ if(l->v == v1){
+ v1loop = l;
+ vloop = v1loop->next;
+ v2loop = vloop->next;
+ }else if(l->v == v){
+ v1loop = l->next;
+ vloop = l;
+ v2loop = l->prev;
+
+ }
+
+ src[0] = v1loop->data;
+ src[1] = v2loop->data;
+
+ CustomData_bmesh_interp(&bm->ldata, src,w, NULL, 2, vloop->data);
+ l = l->radial.next->data;
+ }while(l!=e1->loop);
+}
+
+
+/* a wrapper for BME_SEMV that transfers element flags */ /*add custom data interpolation in here!*/
+static BME_Vert *BME_split_edge(BME_Mesh *bm, BME_Vert *v, BME_Edge *e, BME_Edge **ne, float percent) {
+ BME_Vert *nv, *v2;
+ float len;
+
+ v2 = BME_edge_getothervert(e,v);
+ nv = BME_SEMV(bm,v,e,ne);
+ if (nv == NULL) return NULL;
+ VECSUB(nv->co,v2->co,v->co);
+ len = VecLength(nv->co);
+ VECADDFAC(nv->co,v->co,nv->co,len*percent);
+ nv->flag = v->flag;
+ nv->bweight = v->bweight;
+ if (ne) {
+ (*ne)->flag = e->flag;
+ (*ne)->h = e->h;
+ (*ne)->crease = e->crease;
+ (*ne)->bweight = e->bweight;
+ }
+ /*v->nv->v2*/
+ BME_data_facevert_edgesplit(bm,v2, v, nv, e, 0.75);
+ return nv;
+}
+
+static void BME_collapse_vert(BME_Mesh *bm, BME_Edge *ke, BME_Vert *kv, float fac){
+ void *src[2];
+ float w[2];
+ BME_Loop *l=NULL, *kvloop=NULL, *tvloop=NULL;
+ BME_Vert *tv = BME_edge_getothervert(ke,kv);
+
+ w[0] = 1.0f - fac;
+ w[1] = fac;
+
+ if(ke->loop){
+ l = ke->loop;
+ do{
+ if(l->v == tv && l->next->v == kv){
+ tvloop = l;
+ kvloop = l->next;
+
+ src[0] = kvloop->data;
+ src[1] = tvloop->data;
+ CustomData_bmesh_interp(&bm->ldata, src,w, NULL, 2, kvloop->data);
+ }
+ l=l->radial.next->data;
+ }while(l!=ke->loop);
+ }
+ BME_JEKV(bm,ke,kv);
+}
+
+
+
+static int BME_bevel_is_split_vert(BME_Loop *l) {
+ /* look for verts that have already been added to the edge when
+ * beveling other polys; this can be determined by testing the
+ * vert and the edges around it for originality
+ */
+ if ((l->v->tflag1 & BME_BEVEL_ORIG)==0
+ && (l->e->tflag1 & BME_BEVEL_ORIG)
+ && (l->prev->e->tflag1 & BME_BEVEL_ORIG))
+ {
+ return 1;
+ }
+ return 0;
+}
+
+/* get a vector, vec, that points from v1->co to wherever makes sense to
+ * the bevel operation as a whole based on the relationship between v1 and v2
+ * (won't necessarily be a vec from v1->co to v2->co, though it probably will be);
+ * the return value is -1 for failure, 0 if we used vert co's, and 1 if we used transform origins */
+static int BME_bevel_get_vec(float *vec, BME_Vert *v1, BME_Vert *v2, BME_TransData_Head *td) {
+ BME_TransData *vtd1, *vtd2;
+
+ vtd1 = BME_get_transdata(td,v1);
+ vtd2 = BME_get_transdata(td,v2);
+ if (!vtd1 || !vtd2) {
+ //printf("BME_bevel_get_vec() got called without proper BME_TransData\n");
+ return -1;
+ }
+
+ /* compare the transform origins to see if we can use the vert co's;
+ * if they belong to different origins, then we will use the origins to determine
+ * the vector */
+ if (VecCompare(vtd1->org,vtd2->org,0.000001f)) {
+ VECSUB(vec,v2->co,v1->co);
+ if (VecLength(vec) < 0.000001f) {
+ VecMulf(vec,0);
+ }
+ return 0;
+ }
+ else {
+ VECSUB(vec,vtd2->org,vtd1->org);
+ if (VecLength(vec) < 0.000001f) {
+ VecMulf(vec,0);
+ }
+ return 1;
+ }
+}
+
+/* "Projects" a vector perpendicular to vec2 against vec1, such that
+ * the projected vec1 + vec2 has a min distance of 1 from the "edge" defined by vec2.
+ * note: the direction, is_forward, is used in conjunction with up_vec to determine
+ * whether this is a convex or concave corner. If it is a concave corner, it will
+ * be projected "backwards." If vec1 is before vec2, is_forward should be 0 (we are projecting backwards).
+ * vec1 is the vector to project onto (expected to be normalized)
+ * vec2 is the direction of projection (pointing away from vec1)
+ * up_vec is used for orientation (expected to be normalized)
+ * returns the length of the projected vector that lies along vec1 */
+static float BME_bevel_project_vec(float *vec1, float *vec2, float *up_vec, int is_forward, BME_TransData_Head *td) {
+ float factor, vec3[3], tmp[3],c1,c2;
+
+ Crossf(tmp,vec1,vec2);
+ Normalize(tmp);
+ factor = Inpf(up_vec,tmp);
+ if ((factor > 0 && is_forward) || (factor < 0 && !is_forward)) {
+ Crossf(vec3,vec2,tmp); /* hmm, maybe up_vec should be used instead of tmp */
+ }
+ else {
+ Crossf(vec3,tmp,vec2); /* hmm, maybe up_vec should be used instead of tmp */
+ }
+ Normalize(vec3);
+ c1 = Inpf(vec3,vec1);
+ c2 = Inpf(vec1,vec1);
+ if (fabs(c1) < 0.000001f || fabs(c2) < 0.000001f) {
+ factor = 0.0f;
+ }
+ else {
+ factor = c2/c1;
+ }
+
+ return factor;
+}
+
+/* BME_bevel_split_edge() is the main math work-house; its responsibilities are:
+ * using the vert and the loop passed, get or make the split vert, set its coordinates
+ * and transform properties, and set the max limits.
+ * Finally, return the split vert. */
+static BME_Vert *BME_bevel_split_edge(BME_Mesh *bm, BME_Vert *v, BME_Vert *v1, BME_Loop *l, float *up_vec, float value, BME_TransData_Head *td) {
+ BME_TransData *vtd, *vtd1, *vtd2;
+ BME_Vert *sv, *v2, *v3, *ov;
+ BME_Loop *lv1, *lv2;
+ BME_Edge *ne, *e1, *e2;
+ float maxfactor, scale, len, dis, vec1[3], vec2[3], t_up_vec[3];
+ int is_edge, forward, is_split_vert;
+
+ if (l == NULL) {
+ /* what you call operator overloading in C :)
+ * I wanted to use the same function for both wire edges and poly loops
+ * so... here we walk around edges to find the needed verts */
+ forward = 1;
+ is_split_vert = 0;
+ if (v->edge == NULL) {
+ //printf("We can't split a loose vert's edge!\n");
+ return NULL;
+ }
+ e1 = v->edge; /* we just use the first two edges */
+ e2 = BME_disk_nextedge(v->edge, v);
+ if (e1 == e2) {
+ //printf("You need at least two edges to use BME_bevel_split_edge()\n");
+ return NULL;
+ }
+ v2 = BME_edge_getothervert(e1, v);
+ v3 = BME_edge_getothervert(e2, v);
+ if (v1 != v2 && v1 != v3) {
+ //printf("Error: more than 2 edges in v's disk cycle, or v1 does not share an edge with v\n");
+ return NULL;
+ }
+ if (v1 == v2) {
+ v2 = v3;
+ }
+ else {
+ e1 = e2;
+ }
+ ov = BME_edge_getothervert(e1,v);
+ sv = BME_split_edge(bm,v,e1,&ne,0);
+ //BME_data_interp_from_verts(bm, v, ov, sv, 0.25); /*this is technically wrong...*/
+ //BME_data_interp_from_faceverts(bm, v, ov, sv, 0.25);
+ //BME_data_interp_from_faceverts(bm, ov, v, sv, 0.25);
+ BME_assign_transdata(td, bm, sv, sv->co, sv->co, NULL, sv->co, 0, -1, -1, NULL); /* quick default */
+ sv->tflag1 |= BME_BEVEL_BEVEL;
+ ne->tflag1 = BME_BEVEL_ORIG; /* mark edge as original, even though it isn't */
+ BME_bevel_get_vec(vec1,v1,v,td);
+ BME_bevel_get_vec(vec2,v2,v,td);
+ Crossf(t_up_vec,vec1,vec2);
+ Normalize(t_up_vec);
+ up_vec = t_up_vec;
+ }
+ else {
+ /* establish loop direction */
+ if (l->v == v) {
+ forward = 1;
+ lv1 = l->next;
+ lv2 = l->prev;
+ v1 = l->next->v;
+ v2 = l->prev->v;
+ }
+ else if (l->next->v == v) {
+ forward = 0;
+ lv1 = l;
+ lv2 = l->next->next;
+ v1 = l->v;
+ v2 = l->next->next->v;
+ }
+ else {
+ //printf("ERROR: BME_bevel_split_edge() - v must be adjacent to l\n");
+ return NULL;
+ }
+
+ if (BME_bevel_is_split_vert(lv1)) {
+ is_split_vert = 1;
+ sv = v1;
+ if (forward) v1 = l->next->next->v;
+ else v1 = l->prev->v;
+ }
+ else {
+ is_split_vert = 0;
+ ov = BME_edge_getothervert(l->e,v);
+ sv = BME_split_edge(bm,v,l->e,&ne,0);
+ //BME_data_interp_from_verts(bm, v, ov, sv, 0.25); /*this is technically wrong...*/
+ //BME_data_interp_from_faceverts(bm, v, ov, sv, 0.25);
+ //BME_data_interp_from_faceverts(bm, ov, v, sv, 0.25);
+ BME_assign_transdata(td, bm, sv, sv->co, sv->co, NULL, sv->co, 0, -1, -1, NULL); /* quick default */
+ sv->tflag1 |= BME_BEVEL_BEVEL;
+ ne->tflag1 = BME_BEVEL_ORIG; /* mark edge as original, even though it isn't */
+ }
+
+ if (BME_bevel_is_split_vert(lv2)) {
+ if (forward) v2 = lv2->prev->v;
+ else v2 = lv2->next->v;
+ }
+ }
+
+ is_edge = BME_bevel_get_vec(vec1,v,v1,td); /* get the vector we will be projecting onto */
+ BME_bevel_get_vec(vec2,v,v2,td); /* get the vector we will be projecting parallel to */
+ len = VecLength(vec1);
+ Normalize(vec1);
+
+ vtd = BME_get_transdata(td, sv);
+ vtd1 = BME_get_transdata(td, v);
+ vtd2 = BME_get_transdata(td,v1);
+
+ if (vtd1->loc == NULL) {
+ /* this is a vert with data only for calculating initial weights */
+ if (vtd1->weight < 0) {
+ vtd1->weight = 0;
+ }
+ scale = vtd1->weight/vtd1->factor;
+ if (!vtd1->max) {
+ vtd1->max = BME_new_transdata_float(td);
+ *vtd1->max = -1;
+ }
+ }
+ else {
+ scale = vtd1->weight;
+ }
+ vtd->max = vtd1->max;
+
+ if (is_edge && vtd1->loc != NULL) {
+ maxfactor = vtd1->maxfactor;
+ }
+ else {
+ maxfactor = scale*BME_bevel_project_vec(vec1,vec2,up_vec,forward,td);
+ if (vtd->maxfactor > 0 && vtd->maxfactor < maxfactor) {
+ maxfactor = vtd->maxfactor;
+ }
+ }
+
+ dis = (v1->tflag1 & BME_BEVEL_ORIG)? len/3 : len/2;
+ if (is_edge || dis > maxfactor*value) {
+ dis = maxfactor*value;
+ }
+ VECADDFAC(sv->co,v->co,vec1,dis);
+ VECSUB(vec1,sv->co,vtd1->org);
+ dis = VecLength(vec1);
+ Normalize(vec1);
+ BME_assign_transdata(td, bm, sv, vtd1->org, vtd1->org, vec1, sv->co, dis, scale, maxfactor, vtd->max);
+
+ return sv;
+}
+
+static float BME_bevel_set_max(BME_Vert *v1, BME_Vert *v2, float value, BME_TransData_Head *td) {
+ BME_TransData *vtd1, *vtd2;
+ float max, fac1, fac2, vec1[3], vec2[3], vec3[3];
+
+ BME_bevel_get_vec(vec1,v1,v2,td);
+ vtd1 = BME_get_transdata(td,v1);
+ vtd2 = BME_get_transdata(td,v2);
+
+ if (vtd1->loc == NULL) {
+ fac1 = 0;
+ }
+ else {
+ VECCOPY(vec2,vtd1->vec);
+ VecMulf(vec2,vtd1->factor);
+ if (Inpf(vec1, vec1)) {
+ Projf(vec2,vec2,vec1);
+ fac1 = VecLength(vec2)/value;
+ }
+ else {
+ fac1 = 0;
+ }
+ }
+
+ if (vtd2->loc == NULL) {
+ fac2 = 0;
+ }
+ else {
+ VECCOPY(vec3,vtd2->vec);
+ VecMulf(vec3,vtd2->factor);
+ if (Inpf(vec1, vec1)) {
+ Projf(vec2,vec3,vec1);
+ fac2 = VecLength(vec2)/value;
+ }
+ else {
+ fac2 = 0;
+ }
+ }
+
+ if (fac1 || fac2) {
+ max = VecLength(vec1)/(fac1 + fac2);
+ if (vtd1->max && (*vtd1->max < 0 || max < *vtd1->max)) {
+ *vtd1->max = max;
+ }
+ if (vtd2->max && (*vtd2->max < 0 || max < *vtd2->max)) {
+ *vtd2->max = max;
+ }
+ }
+ else {
+ max = -1;
+ }
+
+ return max;
+}
+
+static BME_Vert *BME_bevel_wire(BME_Mesh *bm, BME_Vert *v, float value, int res, int options, BME_TransData_Head *td) {
+ BME_Vert *ov1, *ov2, *v1, *v2;
+
+ ov1 = BME_edge_getothervert(v->edge, v);
+ ov2 = BME_edge_getothervert(BME_disk_nextedge(v->edge, v), v);
+
+ /* split the edges */
+ v1 = BME_bevel_split_edge(bm,v,ov1,NULL,NULL,value,td);
+ v1->tflag1 |= BME_BEVEL_NONMAN;
+ v2 = BME_bevel_split_edge(bm,v,ov2,NULL,NULL,value,td);
+ v2->tflag1 |= BME_BEVEL_NONMAN;
+
+ if (value > 0.5) {
+ BME_bevel_set_max(v1,ov1,value,td);
+ BME_bevel_set_max(v2,ov2,value,td);
+ }
+
+ /* remove the original vert */
+ if (res) {
+ BME_JEKV(bm,v->edge,v);
+ }
+
+ return v1;
+}
+
+static BME_Loop *BME_bevel_edge(BME_Mesh *bm, BME_Loop *l, float value, int options, float *up_vec, BME_TransData_Head *td) {
+ BME_Vert *v1, *v2, *kv;
+ BME_Loop *kl=NULL, *nl;
+ BME_Edge *e;
+ BME_Poly *f;
+
+ f = l->f;
+ e = l->e;
+
+ if ((l->e->tflag1 & BME_BEVEL_BEVEL) == 0
+ && ((l->v->tflag1 & BME_BEVEL_BEVEL) || (l->next->v->tflag1 & BME_BEVEL_BEVEL)))
+ { /* sanity check */
+ return l;
+ }
+
+ /* checks and operations for prev edge */
+ /* first, check to see if this edge was inset previously */
+ if ((l->prev->e->tflag1 & BME_BEVEL_ORIG) == 0
+ && (l->v->tflag1 & BME_BEVEL_NONMAN) == 0) {
+ kl = l->prev->radial.next->data;
+ if (kl->v == l->v) kl = kl->prev;
+ else kl = kl->next;
+ kv = l->v;
+ }
+ else {
+ kv = NULL;
+ }
+ /* get/make the first vert to be used in SFME */
+ if (l->v->tflag1 & BME_BEVEL_NONMAN){
+ v1 = l->v;
+ }
+ else { /* we'll need to split the previous edge */
+ v1 = BME_bevel_split_edge(bm,l->v,NULL,l->prev,up_vec,value,td);
+ }
+ /* if we need to clean up geometry... */
+ if (kv) {
+ l = l->next;
+ if (kl->v == kv) {
+ BME_split_face(bm,kl->f,kl->prev->v,kl->next->v,&nl,kl->prev->e);
+ BME_JFKE(bm,((BME_Loop*)kl->prev->radial.next->data)->f,kl->f,kl->prev->e);
+ BME_collapse_vert(bm, kl->e, kv, 1.0);
+ //BME_JEKV(bm,kl->e,kv);
+
+ }
+ else {
+ BME_split_face(bm,kl->f,kl->next->next->v,kl->v,&nl,kl->next->e);
+ BME_JFKE(bm,((BME_Loop*)kl->next->radial.next->data)->f,kl->f,kl->next->e);
+ BME_collapse_vert(bm, kl->e, kv, 1.0);
+ //BME_JEKV(bm,kl->e,kv);
+ }
+ l = l->prev;
+ }
+
+ /* checks and operations for the next edge */
+ /* first, check to see if this edge was inset previously */
+ if ((l->next->e->tflag1 & BME_BEVEL_ORIG) == 0
+ && (l->next->v->tflag1 & BME_BEVEL_NONMAN) == 0) {
+ kl = l->next->radial.next->data;
+ if (kl->v == l->next->v) kl = kl->prev;
+ else kl = kl->next;
+ kv = l->next->v;
+ }
+ else {
+ kv = NULL;
+ }
+ /* get/make the second vert to be used in SFME */
+ if (l->next->v->tflag1 & BME_BEVEL_NONMAN) {
+ v2 = l->next->v;
+ }
+ else { /* we'll need to split the next edge */
+ v2 = BME_bevel_split_edge(bm,l->next->v,NULL,l->next,up_vec,value,td);
+ }
+ /* if we need to clean up geometry... */
+ if (kv) {
+ if (kl->v == kv) {
+ BME_split_face(bm,kl->f,kl->prev->v,kl->next->v,&nl,kl->prev->e);
+ BME_JFKE(bm,((BME_Loop*)kl->prev->radial.next->data)->f,kl->f,kl->prev->e);
+ BME_collapse_vert(bm, kl->e, kv, 1.0);
+ //BME_JEKV(bm,kl->e,kv);
+ }
+ else {
+ BME_split_face(bm,kl->f,kl->next->next->v,kl->v,&nl,kl->next->e);
+ BME_JFKE(bm,((BME_Loop*)kl->next->radial.next->data)->f,kl->f,kl->next->e);
+ BME_collapse_vert(bm, kl->e, kv, 1.0);
+ //BME_JEKV(bm,kl->e,kv);
+ }
+ }
+
+ if ((v1->tflag1 & BME_BEVEL_NONMAN)==0 || (v2->tflag1 & BME_BEVEL_NONMAN)==0) {
+ BME_split_face(bm,f,v2,v1,&l,e);
+ l->e->tflag1 = BME_BEVEL_BEVEL;
+ l = l->radial.next->data;
+ }
+
+ if (l->f != f){
+ //printf("Whoops! You got something out of order in BME_bevel_edge()!\n");
+ }
+
+ return l;
+}
+
+static BME_Loop *BME_bevel_vert(BME_Mesh *bm, BME_Loop *l, float value, int options, float *up_vec, BME_TransData_Head *td) {
+ BME_Vert *v1, *v2;
+ BME_Poly *f;
+
+ /* get/make the first vert to be used in SFME */
+ /* may need to split the previous edge */
+ v1 = BME_bevel_split_edge(bm,l->v,NULL,l->prev,up_vec,value,td);
+
+ /* get/make the second vert to be used in SFME */
+ /* may need to split this edge (so move l) */
+ l = l->prev;
+ v2 = BME_bevel_split_edge(bm,l->next->v,NULL,l->next,up_vec,value,td);
+ l = l->next->next;
+
+ /* "cut off" this corner */
+ f = BME_split_face(bm,l->f,v2,v1,NULL,l->e);
+
+ return l;
+}
+
+/**
+ * BME_bevel_poly
+ *
+ * Polygon inset tool:
+ *
+ * Insets a polygon/face based on the tflag1's of its vertices
+ * and edges. Used by the bevel tool only, for now.
+ * The parameter "value" is the distance to inset (should be negative).
+ * The parameter "options" is not currently used.
+ *
+ * Returns -
+ * A BME_Poly pointer to the resulting inner face.
+*/
+static BME_Poly *BME_bevel_poly(BME_Mesh *bm, BME_Poly *f, float value, int options, BME_TransData_Head *td) {
+ BME_Loop *l, *ol;
+ BME_TransData *vtd1, *vtd2;
+ float up_vec[3], vec1[3], vec2[3], vec3[3], fac1, fac2, max = -1;
+ int len, i;
+
+ up_vec[0] = 0.0f;
+ up_vec[1] = 0.0f;
+ up_vec[2] = 0.0f;
+ /* find a good normal for this face (there's better ways, I'm sure) */
+ ol = f->loopbase;
+ l = ol->next;
+ for (i=0,ol=f->loopbase,l=ol->next; l->next!=ol; l=l->next) {
+ BME_bevel_get_vec(vec1,l->next->v,ol->v,td);
+ BME_bevel_get_vec(vec2,l->v,ol->v,td);
+ Crossf(vec3,vec2,vec1);
+ VECADD(up_vec,up_vec,vec3);
+ i++;
+ }
+ VecMulf(up_vec,1.0f/i);
+ Normalize(up_vec);
+
+ for (i=0,len=f->len; i<len; i++,l=l->next) {
+ if ((l->e->tflag1 & BME_BEVEL_BEVEL) && (l->e->tflag1 & BME_BEVEL_ORIG)) {
+ max = 1.0f;
+ l = BME_bevel_edge(bm, l, value, options, up_vec, td);
+ }
+ else if ((l->v->tflag1 & BME_BEVEL_BEVEL) && (l->v->tflag1 & BME_BEVEL_ORIG) && (l->prev->e->tflag1 & BME_BEVEL_BEVEL) == 0) {
+ max = 1.0f;
+ l = BME_bevel_vert(bm, l, value, options, up_vec, td);
+ }
+ }
+
+ /* max pass */
+ if (value > 0.5 && max > 0) {
+ max = -1;
+ for (i=0,len=f->len; i<len; i++,l=l->next) {
+ if ((l->e->tflag1 & BME_BEVEL_BEVEL) || (l->e->tflag1 & BME_BEVEL_ORIG)) {
+ BME_bevel_get_vec(vec1,l->v,l->next->v,td);
+ vtd1 = BME_get_transdata(td,l->v);
+ vtd2 = BME_get_transdata(td,l->next->v);
+ if (vtd1->loc == NULL) {
+ fac1 = 0;
+ }
+ else {
+ VECCOPY(vec2,vtd1->vec);
+ VecMulf(vec2,vtd1->factor);
+ if (Inpf(vec1, vec1)) {
+ Projf(vec2,vec2,vec1);
+ fac1 = VecLength(vec2)/value;
+ }
+ else {
+ fac1 = 0;
+ }
+ }
+ if (vtd2->loc == NULL) {
+ fac2 = 0;
+ }
+ else {
+ VECCOPY(vec3,vtd2->vec);
+ VecMulf(vec3,vtd2->factor);
+ if (Inpf(vec1, vec1)) {
+ Projf(vec2,vec3,vec1);
+ fac2 = VecLength(vec2)/value;
+ }
+ else {
+ fac2 = 0;
+ }
+ }
+ if (fac1 || fac2) {
+ max = VecLength(vec1)/(fac1 + fac2);
+ if (vtd1->max && (*vtd1->max < 0 || max < *vtd1->max)) {
+ *vtd1->max = max;
+ }
+ if (vtd2->max && (*vtd2->max < 0 || max < *vtd2->max)) {
+ *vtd2->max = max;
+ }
+ }
+ }
+ }
+ }
+
+ return l->f;
+}
+
+static void BME_bevel_add_vweight(BME_TransData_Head *td, BME_Mesh *bm, BME_Vert *v, float weight, float factor, int options) {
+ BME_TransData *vtd;
+
+ if (v->tflag1 & BME_BEVEL_NONMAN) return;
+ v->tflag1 |= BME_BEVEL_BEVEL;
+ if ( (vtd = BME_get_transdata(td, v)) ) {
+ if (options & BME_BEVEL_EMIN) {
+ vtd->factor = 1.0;
+ if (vtd->weight < 0 || weight < vtd->weight) {
+ vtd->weight = weight;
+ }
+ }
+ else if (options & BME_BEVEL_EMAX) {
+ vtd->factor = 1.0;
+ if (weight > vtd->weight) {
+ vtd->weight = weight;
+ }
+ }
+ else if (vtd->weight < 0) {
+ vtd->factor = factor;
+ vtd->weight = weight;
+ }
+ else {
+ vtd->factor += factor; /* increment number of edges with weights (will be averaged) */
+ vtd->weight += weight; /* accumulate all the weights */
+ }
+ }
+ else {
+ /* we'll use vtd->loc == NULL to mark that this vert is not moving */
+ vtd = BME_assign_transdata(td, bm, v, v->co, NULL, NULL, NULL, factor, weight, -1, NULL);
+ }
+}
+
+static float BME_bevel_get_angle(BME_Mesh *bm, BME_Edge *e, BME_Vert *v) {
+ BME_Vert *v1, *v2;
+ BME_Loop *l1, *l2;
+ float vec1[3], vec2[3], vec3[3], vec4[3];
+
+ l1 = e->loop;
+ l2 = e->loop->radial.next->data;
+ if (l1->v == v) {
+ v1 = l1->prev->v;
+ v2 = l1->next->v;
+ }
+ else {
+ v1 = l1->next->next->v;
+ v2 = l1->v;
+ }
+ VECSUB(vec1,v1->co,v->co);
+ VECSUB(vec2,v2->co,v->co);
+ Crossf(vec3,vec1,vec2);
+
+ l1 = l2;
+ if (l1->v == v) {
+ v1 = l1->prev->v;
+ v2 = l1->next->v;
+ }
+ else {
+ v1 = l1->next->next->v;
+ v2 = l1->v;
+ }
+ VECSUB(vec1,v1->co,v->co);
+ VECSUB(vec2,v2->co,v->co);
+ Crossf(vec4,vec2,vec1);
+
+ Normalize(vec3);
+ Normalize(vec4);
+
+ return Inpf(vec3,vec4);
+}
+static int BME_face_sharededges(BME_Poly *f1, BME_Poly *f2){
+ BME_Loop *l;
+ int count = 0;
+
+ l = f1->loopbase;
+ do{
+ if(BME_radial_find_face(l->e,f2)) count++;
+ l = l->next;
+ }while(l != f1->loopbase);
+
+ return count;
+}
+/**
+ * BME_bevel_initialize
+ *
+ * Prepare the mesh for beveling:
+ *
+ * Sets the tflag1's of the mesh elements based on the options passed.
+ *
+ * Returns -
+ * A BME_Mesh pointer to the BMesh passed as a parameter.
+*/
+static BME_Mesh *BME_bevel_initialize(BME_Mesh *bm, int options, int defgrp_index, float angle, BME_TransData_Head *td) {
+ BME_Vert *v;
+ BME_Edge *e;
+ BME_Poly *f;
+ BME_TransData *vtd;
+ MDeformVert *dvert;
+ MDeformWeight *dw;
+ int len;
+ float weight, threshold;
+
+ /* vert pass */
+ for (v=bm->verts.first; v; v=v->next) {
+ dvert = NULL;
+ dw = NULL;
+ v->tflag1 = BME_BEVEL_ORIG;
+ /* originally coded, a vertex gets tagged with BME_BEVEL_BEVEL in this pass if
+ * the vert is manifold (or is shared by only two edges - wire bevel)
+ * BME_BEVEL_SELECT is passed and the vert has v->flag&SELECT or
+ * BME_BEVEL_VWEIGHT is passed, and the vert has a defgrp and weight
+ * BME_BEVEL_ANGLE is not passed
+ * BME_BEVEL_EWEIGHT is not passed
+ */
+ /* originally coded, a vertex gets tagged with BME_BEVEL_NONMAN in this pass if
+ * the vert is loose, shared by multiple regions, or is shared by wire edges
+ * note: verts belonging to edges of open meshes are not tagged with BME_BEVEL_NONMAN
+ */
+ /* originally coded, a vertex gets a transform weight set in this pass if
+ * BME_BEVEL_VWEIGHT is passed, and the vert has a defgrp and weight
+ */
+
+ /* get disk cycle length */
+ if (v->edge == NULL) {
+ len = 0;
+ }
+ else {
+ len = BME_cycle_length(BME_disk_getpointer(v->edge,v));
+ /* we'll assign a default transform data to every vert (except the loose ones) */
+ vtd = BME_assign_transdata(td, bm, v, v->co, v->co, NULL, NULL, 0, -1, -1, NULL);
+ }
+
+ /* check for non-manifold vert */
+ if (BME_is_nonmanifold_vert(bm,v)) {
+ v->tflag1 |= BME_BEVEL_NONMAN;
+ }
+
+ /* BME_BEVEL_BEVEL tests */
+ if ((v->tflag1 & BME_BEVEL_NONMAN) == 0 || len == 2) { /* either manifold vert, or wire vert */
+ if (((options & BME_BEVEL_SELECT) && (v->flag & SELECT))
+ || ((options & BME_BEVEL_WEIGHT) && (options & BME_BEVEL_VERT)) /* use weights for verts */
+ || ((options & BME_BEVEL_ANGLE) == 0
+ && (options & BME_BEVEL_SELECT) == 0
+ && (options & BME_BEVEL_WEIGHT) == 0))
+ {
+ if (options & BME_BEVEL_WEIGHT) {
+ /* do vert weight stuff */
+ //~ dvert = CustomData_em_get(&bm->vdata,v->data,CD_MDEFORMVERT);
+ //~ if (!dvert) continue;
+ //~ for (i = 0; i < dvert->totweight; ++i) {
+ //~ if(dvert->dw[i].def_nr == defgrp_index) {
+ //~ dw = &dvert->dw[i];
+ //~ break;
+ //~ }
+ //~ }
+ //~ if (!dw || dw->weight == 0.0) continue;
+ if (v->bweight == 0.0) continue;
+ vtd = BME_assign_transdata(td, bm, v, v->co, v->co, NULL, NULL, 1.0, v->bweight, -1, NULL);
+ v->tflag1 |= BME_BEVEL_BEVEL;
+ }
+ else {
+ vtd = BME_assign_transdata(td, bm, v, v->co, v->co, NULL, NULL, 1.0, 1.0, -1, NULL);
+ v->tflag1 |= BME_BEVEL_BEVEL;
+ }
+ }
+ }
+ }
+
+ /* edge pass */
+ threshold = (float)cos((angle + 0.00001) * M_PI / 180.0);
+ for (e=bm->edges.first; e; e=e->next) {
+ e->tflag1 = BME_BEVEL_ORIG;
+ weight = 0.0;
+ /* originally coded, an edge gets tagged with BME_BEVEL_BEVEL in this pass if
+ * BME_BEVEL_VERT is not set
+ * the edge is manifold (shared by exactly two faces)
+ * BME_BEVEL_SELECT is passed and the edge has e->flag&SELECT or
+ * BME_BEVEL_EWEIGHT is passed, and the edge has the crease set or
+ * BME_BEVEL_ANGLE is passed, and the edge is sharp enough
+ * BME_BEVEL_VWEIGHT is passed, and both verts are set for bevel
+ */
+ /* originally coded, a vertex gets tagged with BME_BEVEL_BEVEL in this pass if
+ * the vert belongs to the edge
+ * the vert is not tagged with BME_BEVEL_NONMAN
+ * the edge is eligible for bevel (even if BME_BEVEL_VERT is set, or the edge is shared by less than 2 faces)
+ */
+ /* originally coded, a vertex gets a transform weight set in this pass if
+ * the vert belongs to the edge
+ * the edge has a weight
+ */
+ /* note: edge weights are cumulative at the verts,
+ * i.e. the vert's weight is the average of the weights of its weighted edges
+ */
+
+ if (e->loop == NULL) {
+ len = 0;
+ e->v1->tflag1 |= BME_BEVEL_NONMAN;
+ e->v2->tflag1 |= BME_BEVEL_NONMAN;
+ }
+ else {
+ len = BME_cycle_length(&(e->loop->radial));
+ }
+
+ if (len > 2) {
+ /* non-manifold edge of the worst kind */
+ continue;
+ }
+
+ if ((options & BME_BEVEL_SELECT) && (e->flag & SELECT)) {
+ weight = 1.0;
+ /* stupid editmode doesn't always flush selections, or something */
+ e->v1->flag |= SELECT;
+ e->v2->flag |= SELECT;
+ }
+ else if ((options & BME_BEVEL_WEIGHT) && (options & BME_BEVEL_VERT) == 0) {
+ weight = e->bweight;
+ }
+ else if (options & BME_BEVEL_ANGLE) {
+ if ((e->v1->tflag1 & BME_BEVEL_NONMAN) == 0 && BME_bevel_get_angle(bm,e,e->v1) < threshold) {
+ e->tflag1 |= BME_BEVEL_BEVEL;
+ e->v1->tflag1 |= BME_BEVEL_BEVEL;
+ BME_bevel_add_vweight(td, bm, e->v1, 1.0, 1.0, options);
+ }
+ else {
+ BME_bevel_add_vweight(td, bm, e->v1, 0.0, 1.0, options);
+ }
+ if ((e->v2->tflag1 & BME_BEVEL_NONMAN) == 0 && BME_bevel_get_angle(bm,e,e->v2) < threshold) {
+ e->tflag1 |= BME_BEVEL_BEVEL;
+ e->v2->tflag1 |= BME_BEVEL_BEVEL;
+ BME_bevel_add_vweight(td, bm, e->v2, 1.0, 1.0, options);
+ }
+ else {
+ BME_bevel_add_vweight(td, bm, e->v2, 0.0, 1.0, options);
+ }
+ }
+ //~ else if ((options & BME_BEVEL_VWEIGHT) && (options & BME_BEVEL_VERT) == 0) {
+ //~ if ((e->v1->tflag1 & BME_BEVEL_BEVEL) && (e->v2->tflag1 & BME_BEVEL_BEVEL)) {
+ //~ e->tflag1 |= BME_BEVEL_BEVEL;
+ //~ }
+ //~ }
+ else if ((options & BME_BEVEL_SELECT) == 0
+ && (options & BME_BEVEL_VERT) == 0)
+ {
+ weight = 1.0;
+ }
+
+ if (weight > 0.0) {
+ e->tflag1 |= BME_BEVEL_BEVEL;
+ BME_bevel_add_vweight(td, bm, e->v1, weight, 1.0, options);
+ BME_bevel_add_vweight(td, bm, e->v2, weight, 1.0, options);
+ }
+
+ if (len != 2 || options & BME_BEVEL_VERT) {
+ e->tflag1 &= ~BME_BEVEL_BEVEL;
+ }
+ }
+
+ /* face pass */
+ for (f=bm->polys.first; f; f=f->next) f->tflag1 = BME_BEVEL_ORIG;
+
+ /*clean up edges with 2 faces that share more than one edge*/
+ for (e=bm->edges.first; e; e=e->next){
+ if(e->tflag1 & BME_BEVEL_BEVEL){
+ int count = 0;
+ count = BME_face_sharededges(e->loop->f, ((BME_Loop*)e->loop->radial.next->data)->f);
+ if(count > 1){
+ e->tflag1 &= ~BME_BEVEL_BEVEL;
+ }
+ }
+ }
+
+ return bm;
+}
+
+/* tags all elements as originals */
+static BME_Mesh *BME_bevel_reinitialize(BME_Mesh *bm) {
+ BME_Vert *v;
+ BME_Edge *e;
+ BME_Poly *f;
+
+ for (v = bm->verts.first; v; v=v->next) {
+ v->tflag1 |= BME_BEVEL_ORIG;
+ }
+
+ for (e=bm->edges.first; e; e=e->next) {
+ e->tflag1 |= BME_BEVEL_ORIG;
+ }
+
+ for (f=bm->polys.first; f; f=f->next) {
+ f->tflag1 |= BME_BEVEL_ORIG;
+ }
+
+ return bm;
+}
+
+/**
+ * BME_bevel_mesh
+ *
+ * Mesh beveling tool:
+ *
+ * Bevels an entire mesh. It currently uses the tflag1's of
+ * its vertices and edges to track topological changes.
+ * The parameter "value" is the distance to inset (should be negative).
+ * The parameter "options" is not currently used.
+ *
+ * Returns -
+ * A BME_Mesh pointer to the BMesh passed as a parameter.
+*/
+
+static void bmesh_dissolve_disk(BME_Mesh *bm, BME_Vert *v){
+ BME_Poly *f;
+ BME_Edge *e;
+ int done, len;
+
+ if(v->edge){
+ done = 0;
+ while(!done){
+ done = 1;
+ e = v->edge; /*loop the edge looking for a edge to dissolve*/
+ do{
+ f = NULL;
+ len = BME_cycle_length(&(e->loop->radial));
+ if(len == 2){
+ f = BME_JFKE_safe(bm,e->loop->f, ((BME_Loop*)(e->loop->radial.next->data))->f, e);
+ }
+ if(f){
+ done = 0;
+ break;
+ }
+ e = BME_disk_nextedge(e,v);
+ }while(e != v->edge);
+ }
+ BME_collapse_vert(bm, v->edge, v, 1.0);
+ //BME_JEKV(bm,v->edge,v);
+ }
+}
+static BME_Mesh *BME_bevel_mesh(BME_Mesh *bm, float value, int res, int options, int defgrp_index, BME_TransData_Head *td) {
+ BME_Vert *v, *nv;
+ BME_Edge *e, *oe;
+ BME_Loop *l, *l2;
+ BME_Poly *f;
+ unsigned int i, len;
+
+ for (f=bm->polys.first; f; f=f->next) {
+ if(f->tflag1 & BME_BEVEL_ORIG) {
+ BME_bevel_poly(bm,f,value,options,td);
+ }
+ }
+
+ /* here we will loop through all the verts to clean up the left over geometry */
+ /* crazy idea. when res == 0, don't remove the original geometry */
+ for (v = bm->verts.first; v; /* we may kill v, so increment in-loop */) {
+ nv = v->next;
+ if ((v->tflag1 & BME_BEVEL_NONMAN) && (v->tflag1 & BME_BEVEL_BEVEL) && (v->tflag1 & BME_BEVEL_ORIG)) {
+ v = BME_bevel_wire(bm, v, value, res, options, td);
+ }
+ else if (res && ((v->tflag1 & BME_BEVEL_BEVEL) && (v->tflag1 & BME_BEVEL_ORIG))) {
+ int count = 0;
+ /* first, make sure we're not sitting on an edge to be removed */
+ oe = v->edge;
+ e = BME_disk_nextedge(oe,v);
+ while ((e->tflag1 & BME_BEVEL_BEVEL) && (e->tflag1 & BME_BEVEL_ORIG)) {
+ e = BME_disk_nextedge(e,v);
+ if (e == oe) {
+ //printf("Something's wrong! We can't remove every edge here!\n");
+ break;
+ }
+ }
+ /* look for original edges, and remove them */
+ oe = e;
+ while ( (e = BME_disk_next_edgeflag(oe, v, 0, BME_BEVEL_ORIG | BME_BEVEL_BEVEL)) ) {
+ count++;
+ /* join the faces (we'll split them later) */
+ f = BME_JFKE_safe(bm,e->loop->f,((BME_Loop*)e->loop->radial.next->data)->f,e);
+ if (!f){
+ //printf("Non-manifold geometry not getting tagged right?\n");
+ }
+ }
+
+ /*need to do double check *before* you bevel to make sure that manifold edges are for two faces that share only *one* edge to make sure it doesnt hang here!*/
+
+
+ /* all original edges marked to be beveled have been removed;
+ * now we need to link up the edges for this "corner" */
+ len = BME_cycle_length(BME_disk_getpointer(v->edge, v));
+ for (i=0,e=v->edge; i < len; i++,e=BME_disk_nextedge(e,v)) {
+ l = e->loop;
+ l2 = l->radial.next->data;
+ if (l->v != v) l = l->next;
+ if (l2->v != v) l2 = l2->next;
+ /* look for faces that have had the original edges removed via JFKE */
+ if (l->f->len > 3) {
+ BME_split_face(bm,l->f,l->next->v,l->prev->v,&l,l->e); /* clip this corner off */
+ if (len > 2) {
+ l->e->tflag1 |= BME_BEVEL_BEVEL;
+ }
+ }
+ if (l2->f->len > 3) {
+ BME_split_face(bm,l2->f,l2->next->v,l2->prev->v,&l,l2->e); /* clip this corner off */
+ if (len > 2) {
+ l->e->tflag1 |= BME_BEVEL_BEVEL;
+ }
+ }
+ }
+ bmesh_dissolve_disk(bm, v);
+ }
+ v = nv;
+ }
+
+ return bm;
+}
+
+static BME_Mesh *BME_tesselate(BME_Mesh *bm) {
+ BME_Loop *l, *nextloop;
+ BME_Poly *f;
+
+ for (f=bm->polys.first; f; f=f->next) {
+ l = f->loopbase;
+ while (l->f->len > 4) {
+ nextloop = l->next->next->next;
+ /* make a quad */
+ BME_split_face(bm,l->f,l->v,nextloop->v,NULL,l->e);
+ l = nextloop;
+ }
+ }
+ return bm;
+}
+
+
+/*Main bevel function:
+ Should be only one exported
+
+*/
+
+/* options that can be passed:
+ * BME_BEVEL_VWEIGHT <---- v, Look at vertex weights; use defgrp_index if option is present
+ * BME_BEVEL_SELECT <---- v,e, check selection for verts and edges
+ * BME_BEVEL_ANGLE <---- v,e, don't bevel-tag verts - tag verts per edge
+ * BME_BEVEL_VERT <---- e, don't tag edges
+ * BME_BEVEL_EWEIGHT <---- e, use crease flag for now
+ * BME_BEVEL_PERCENT <---- Will need to think about this one; will probably need to incorporate into actual bevel routine
+ * BME_BEVEL_RADIUS <---- Will need to think about this one; will probably need to incorporate into actual bevel routine
+ * All weights/limits are stored per-vertex
+ */
+BME_Mesh *BME_bevel(BME_Mesh *bm, float value, int res, int options, int defgrp_index, float angle, BME_TransData_Head **rtd) {
+ BME_Vert *v;
+ BME_TransData_Head *td;
+ BME_TransData *vtd;
+ int i;
+ float fac=1, d;
+
+ td = BME_init_transdata(BLI_MEMARENA_STD_BUFSIZE);
+
+ BME_bevel_initialize(bm, options, defgrp_index, angle, td);
+
+ /* recursion math courtesy of Martin Poirier (theeth) */
+ for (i=0; i<res-1; i++) {
+ if (i==0) fac += 1.0f/3.0f; else fac += 1.0f/(3 * i * 2.0f);
+ }
+ d = 1.0f/fac;
+ /* crazy idea. if res == 0, don't remove original geometry */
+ for (i=0; i<res || (res==0 && i==0); i++) {
+ if (i != 0) BME_bevel_reinitialize(bm);
+ BME_model_begin(bm);
+ BME_bevel_mesh(bm,d,res,options,defgrp_index,td);
+ BME_model_end(bm);
+ if (i==0) d /= 3; else d /= 2;
+ }
+
+ BME_tesselate(bm);
+
+ if (rtd) {
+ *rtd = td;
+ return bm;
+ }
+
+ /* transform pass */
+ for (v = bm->verts.first; v; v=v->next) {
+ if ( (vtd = BME_get_transdata(td, v)) ) {
+ if (vtd->max && (*vtd->max > 0 && value > *vtd->max)) {
+ d = *vtd->max;
+ }
+ else {
+ d = value;
+ }
+ VECADDFAC(v->co,vtd->org,vtd->vec,vtd->factor*d);
+ }
+ v->tflag1 = 0;
+ }
+
+ BME_free_transdata(td);
+ return bm;
+}
diff --git a/source/blender/blenkernel/intern/CCGSubSurf.c b/source/blender/blenkernel/intern/CCGSubSurf.c
index 4e00e29029c..cee032f364e 100644
--- a/source/blender/blenkernel/intern/CCGSubSurf.c
+++ b/source/blender/blenkernel/intern/CCGSubSurf.c
@@ -7,6 +7,8 @@
#include "CCGSubSurf.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
/***/
typedef unsigned char byte;
@@ -35,7 +37,7 @@ typedef struct _EHash {
#define EHASH_alloc(eh, nb) ((eh)->allocatorIFC.alloc((eh)->allocator, nb))
#define EHASH_free(eh, ptr) ((eh)->allocatorIFC.free((eh)->allocator, ptr))
-#define EHASH_hash(eh, item) (((unsigned long) (item))%((unsigned int) (eh)->curSize))
+#define EHASH_hash(eh, item) (((uintptr_t) (item))%((unsigned int) (eh)->curSize))
static EHash *_ehash_new(int estimatedNumEntries, CCGAllocatorIFC *allocatorIFC, CCGAllocatorHDL allocator) {
EHash *eh = allocatorIFC->alloc(allocator, sizeof(*eh));
@@ -199,21 +201,21 @@ static CCGAllocatorIFC *_getStandardAllocatorIFC(void) {
static int VertDataEqual(float *a, float *b) {
return a[0]==b[0] && a[1]==b[1] && a[2]==b[2];
}
-#define VertDataZero(av) { float *a = (float*) av; a[0] = a[1] = a[2] = 0.0f; }
-#define VertDataCopy(av, bv) { float *a = (float*) av, *b = (float*) bv; a[0] =b[0]; a[1] =b[1]; a[2] =b[2]; }
-#define VertDataAdd(av, bv) { float *a = (float*) av, *b = (float*) bv; a[0]+=b[0]; a[1]+=b[1]; a[2]+=b[2]; }
-#define VertDataSub(av, bv) { float *a = (float*) av, *b = (float*) bv; a[0]-=b[0]; a[1]-=b[1]; a[2]-=b[2]; }
-#define VertDataMulN(av, n) { float *a = (float*) av; a[0]*=n; a[1]*=n; a[2]*=n; }
+#define VertDataZero(av) { float *_a = (float*) av; _a[0] = _a[1] = _a[2] = 0.0f; }
+#define VertDataCopy(av, bv) { float *_a = (float*) av, *_b = (float*) bv; _a[0] =_b[0]; _a[1] =_b[1]; _a[2] =_b[2]; }
+#define VertDataAdd(av, bv) { float *_a = (float*) av, *_b = (float*) bv; _a[0]+=_b[0]; _a[1]+=_b[1]; _a[2]+=_b[2]; }
+#define VertDataSub(av, bv) { float *_a = (float*) av, *_b = (float*) bv; _a[0]-=_b[0]; _a[1]-=_b[1]; _a[2]-=_b[2]; }
+#define VertDataMulN(av, n) { float *_a = (float*) av; _a[0]*=n; _a[1]*=n; _a[2]*=n; }
#define VertDataAvg4(tv, av, bv, cv, dv) \
{ \
- float *t = (float*) tv, *a = (float*) av, *b = (float*) bv, *c = (float*) cv, *d = (float*) dv; \
- t[0] = (a[0]+b[0]+c[0]+d[0])*.25; \
- t[1] = (a[1]+b[1]+c[1]+d[1])*.25; \
- t[2] = (a[2]+b[2]+c[2]+d[2])*.25; \
+ float *_t = (float*) tv, *_a = (float*) av, *_b = (float*) bv, *_c = (float*) cv, *_d = (float*) dv; \
+ _t[0] = (_a[0]+_b[0]+_c[0]+_d[0])*.25; \
+ _t[1] = (_a[1]+_b[1]+_c[1]+_d[1])*.25; \
+ _t[2] = (_a[2]+_b[2]+_c[2]+_d[2])*.25; \
}
-#define NormZero(av) { float *a = (float*) av; a[0] = a[1] = a[2] = 0.0f; }
-#define NormCopy(av, bv) { float *a = (float*) av, *b = (float*) bv; a[0] =b[0]; a[1] =b[1]; a[2] =b[2]; }
-#define NormAdd(av, bv) { float *a = (float*) av, *b = (float*) bv; a[0]+=b[0]; a[1]+=b[1]; a[2]+=b[2]; }
+#define NormZero(av) { float *_a = (float*) av; _a[0] = _a[1] = _a[2] = 0.0f; }
+#define NormCopy(av, bv) { float *_a = (float*) av, *_b = (float*) bv; _a[0] =_b[0]; _a[1] =_b[1]; _a[2] =_b[2]; }
+#define NormAdd(av, bv) { float *_a = (float*) av, *_b = (float*) bv; _a[0]+=_b[0]; _a[1]+=_b[1]; _a[2]+=_b[2]; }
static int _edge_isBoundary(CCGEdge *e);
@@ -328,7 +330,7 @@ struct _CCGSubSurf {
/***/
-static CCGVert *_vert_new(CCGVertHDL vHDL, int levels, int dataSize, CCGSubSurf *ss) {
+static CCGVert *_vert_new(CCGVertHDL vHDL, CCGSubSurf *ss) {
CCGVert *v = CCGSUBSURF_alloc(ss, sizeof(CCGVert) + ss->meshIFC.vertDataSize * (ss->subdivLevels+1) + ss->meshIFC.vertUserSize);
byte *userData;
@@ -344,7 +346,7 @@ static CCGVert *_vert_new(CCGVertHDL vHDL, int levels, int dataSize, CCGSubSurf
return v;
}
-static void _vert_remEdge(CCGVert *v, CCGEdge *e, CCGSubSurf *ss) {
+static void _vert_remEdge(CCGVert *v, CCGEdge *e) {
int i;
for (i=0; i<v->numEdges; i++) {
if (v->edges[i]==e) {
@@ -353,7 +355,7 @@ static void _vert_remEdge(CCGVert *v, CCGEdge *e, CCGSubSurf *ss) {
}
}
}
-static void _vert_remFace(CCGVert *v, CCGFace *f, CCGSubSurf *ss) {
+static void _vert_remFace(CCGVert *v, CCGFace *f) {
int i;
for (i=0; i<v->numFaces; i++) {
if (v->faces[i]==f) {
@@ -401,13 +403,13 @@ static void _vert_free(CCGVert *v, CCGSubSurf *ss) {
CCGSUBSURF_free(ss, v);
}
-static int VERT_seam(CCGVert *v, CCGSubSurf *ss) {
+static int VERT_seam(CCGVert *v) {
return ((v->flags & Vert_eSeam) != 0);
}
/***/
-static CCGEdge *_edge_new(CCGEdgeHDL eHDL, CCGVert *v0, CCGVert *v1, float crease, int levels, int dataSize, CCGSubSurf *ss) {
+static CCGEdge *_edge_new(CCGEdgeHDL eHDL, CCGVert *v0, CCGVert *v1, float crease, CCGSubSurf *ss) {
CCGEdge *e = CCGSUBSURF_alloc(ss, sizeof(CCGEdge) + ss->meshIFC.vertDataSize *((ss->subdivLevels+1) + (1<<(ss->subdivLevels+1))-1) + ss->meshIFC.edgeUserSize);
byte *userData;
@@ -427,7 +429,7 @@ static CCGEdge *_edge_new(CCGEdgeHDL eHDL, CCGVert *v0, CCGVert *v1, float creas
return e;
}
-static void _edge_remFace(CCGEdge *e, CCGFace *f, CCGSubSurf *ss) {
+static void _edge_remFace(CCGEdge *e, CCGFace *f) {
int i;
for (i=0; i<e->numFaces; i++) {
if (e->faces[i]==f) {
@@ -476,8 +478,8 @@ static void _edge_free(CCGEdge *e, CCGSubSurf *ss) {
CCGSUBSURF_free(ss, e);
}
static void _edge_unlinkMarkAndFree(CCGEdge *e, CCGSubSurf *ss) {
- _vert_remEdge(e->v0, e, ss);
- _vert_remEdge(e->v1, e, ss);
+ _vert_remEdge(e->v0, e);
+ _vert_remEdge(e->v1, e);
e->v0->flags |= Vert_eEffected;
e->v1->flags |= Vert_eEffected;
_edge_free(e, ss);
@@ -494,7 +496,7 @@ static float EDGE_getSharpness(CCGEdge *e, int lvl) {
return e->crease - lvl;
}
-static CCGFace *_face_new(CCGFaceHDL fHDL, CCGVert **verts, CCGEdge **edges, int numVerts, int levels, int dataSize, CCGSubSurf *ss) {
+static CCGFace *_face_new(CCGFaceHDL fHDL, CCGVert **verts, CCGEdge **edges, int numVerts, CCGSubSurf *ss) {
int maxGridSize = 1 + (1<<(ss->subdivLevels-1));
CCGFace *f = CCGSUBSURF_alloc(ss, sizeof(CCGFace) + sizeof(CCGVert*)*numVerts + sizeof(CCGEdge*)*numVerts + ss->meshIFC.vertDataSize *(1 + numVerts*maxGridSize + numVerts*maxGridSize*maxGridSize) + ss->meshIFC.faceUserSize);
byte *userData;
@@ -608,8 +610,8 @@ static void _face_free(CCGFace *f, CCGSubSurf *ss) {
static void _face_unlinkMarkAndFree(CCGFace *f, CCGSubSurf *ss) {
int j;
for (j=0; j<f->numVerts; j++) {
- _vert_remFace(FACE_getVerts(f)[j], f, ss);
- _edge_remFace(FACE_getEdges(f)[j], f, ss);
+ _vert_remFace(FACE_getVerts(f)[j], f);
+ _edge_remFace(FACE_getEdges(f)[j], f);
FACE_getVerts(f)[j]->flags |= Vert_eEffected;
}
_face_free(f, ss);
@@ -882,7 +884,7 @@ CCGError ccgSubSurf_syncVert(CCGSubSurf *ss, CCGVertHDL vHDL, void *vertData, in
if (ss->syncState==eSyncState_Partial) {
v = _ehash_lookupWithPrev(ss->vMap, vHDL, &prevp);
if (!v) {
- v = _vert_new(vHDL, ss->subdivLevels, ss->meshIFC.vertDataSize, ss);
+ v = _vert_new(vHDL, ss);
VertDataCopy(_vert_getCo(v,0,ss->meshIFC.vertDataSize), vertData);
_ehash_insert(ss->vMap, (EHEntry*) v);
v->flags = Vert_eEffected|seamflag;
@@ -911,7 +913,7 @@ CCGError ccgSubSurf_syncVert(CCGSubSurf *ss, CCGVertHDL vHDL, void *vertData, in
v = _ehash_lookupWithPrev(ss->oldVMap, vHDL, &prevp);
if (!v) {
- v = _vert_new(vHDL, ss->subdivLevels, ss->meshIFC.vertDataSize, ss);
+ v = _vert_new(vHDL, ss);
VertDataCopy(_vert_getCo(v,0,ss->meshIFC.vertDataSize), vertData);
_ehash_insert(ss->vMap, (EHEntry*) v);
v->flags = Vert_eEffected|seamflag;
@@ -941,7 +943,7 @@ CCGError ccgSubSurf_syncEdge(CCGSubSurf *ss, CCGEdgeHDL eHDL, CCGVertHDL e_vHDL0
CCGVert *v0 = _ehash_lookup(ss->vMap, e_vHDL0);
CCGVert *v1 = _ehash_lookup(ss->vMap, e_vHDL1);
- eNew = _edge_new(eHDL, v0, v1, crease, ss->subdivLevels, ss->meshIFC.vertDataSize, ss);
+ eNew = _edge_new(eHDL, v0, v1, crease, ss);
if (e) {
*prevp = eNew;
@@ -966,7 +968,7 @@ CCGError ccgSubSurf_syncEdge(CCGSubSurf *ss, CCGEdgeHDL eHDL, CCGVertHDL e_vHDL0
if (!e || e->v0->vHDL!=e_vHDL0 || e->v1->vHDL!=e_vHDL1|| e->crease!=crease) {
CCGVert *v0 = _ehash_lookup(ss->vMap, e_vHDL0);
CCGVert *v1 = _ehash_lookup(ss->vMap, e_vHDL1);
- e = _edge_new(eHDL, v0, v1, crease, ss->subdivLevels, ss->meshIFC.vertDataSize, ss);
+ e = _edge_new(eHDL, v0, v1, crease, ss);
_ehash_insert(ss->eMap, (EHEntry*) e);
e->v0->flags |= Vert_eEffected;
e->v1->flags |= Vert_eEffected;
@@ -1015,7 +1017,7 @@ CCGError ccgSubSurf_syncFace(CCGSubSurf *ss, CCGFaceHDL fHDL, int numVerts, CCGV
}
if (!f || topologyChanged) {
- fNew = _face_new(fHDL, ss->tempVerts, ss->tempEdges, numVerts, ss->subdivLevels, ss->meshIFC.vertDataSize, ss);
+ fNew = _face_new(fHDL, ss->tempVerts, ss->tempEdges, numVerts, ss);
if (f) {
ss->numGrids += numVerts - f->numVerts;
@@ -1052,7 +1054,7 @@ CCGError ccgSubSurf_syncFace(CCGSubSurf *ss, CCGFaceHDL fHDL, int numVerts, CCGV
if (!ss->tempEdges[k]) {
if (ss->allowEdgeCreation) {
- CCGEdge *e = ss->tempEdges[k] = _edge_new((CCGEdgeHDL) -1, ss->tempVerts[k], ss->tempVerts[(k+1)%numVerts], ss->defaultCreaseValue, ss->subdivLevels, ss->meshIFC.vertDataSize, ss);
+ CCGEdge *e = ss->tempEdges[k] = _edge_new((CCGEdgeHDL) -1, ss->tempVerts[k], ss->tempVerts[(k+1)%numVerts], ss->defaultCreaseValue, ss);
_ehash_insert(ss->eMap, (EHEntry*) e);
e->v0->flags |= Vert_eEffected;
e->v1->flags |= Vert_eEffected;
@@ -1073,7 +1075,7 @@ CCGError ccgSubSurf_syncFace(CCGSubSurf *ss, CCGFaceHDL fHDL, int numVerts, CCGV
}
if (!f || topologyChanged) {
- f = _face_new(fHDL, ss->tempVerts, ss->tempEdges, numVerts, ss->subdivLevels, ss->meshIFC.vertDataSize, ss);
+ f = _face_new(fHDL, ss->tempVerts, ss->tempEdges, numVerts, ss);
_ehash_insert(ss->fMap, (EHEntry*) f);
ss->numGrids += numVerts;
@@ -1226,7 +1228,7 @@ static void ccgSubSurf__sync(CCGSubSurf *ss) {
void *nCo = VERT_getCo(v, nextLvl);
int sharpCount = 0, allSharp = 1;
float avgSharpness = 0.0;
- int seam = VERT_seam(v, ss), seamEdges = 0;
+ int seam = VERT_seam(v), seamEdges = 0;
for (i=0; i<v->numEdges; i++) {
CCGEdge *e = v->edges[i];
@@ -1243,9 +1245,11 @@ static void ccgSubSurf__sync(CCGSubSurf *ss) {
}
}
- avgSharpness /= sharpCount;
- if (avgSharpness>1.0) {
- avgSharpness = 1.0;
+ if(sharpCount) {
+ avgSharpness /= sharpCount;
+ if (avgSharpness>1.0) {
+ avgSharpness = 1.0;
+ }
}
if (seam && seamEdges < 2)
@@ -1293,7 +1297,7 @@ static void ccgSubSurf__sync(CCGSubSurf *ss) {
VertDataMulN(nCo, 1.0f/numEdges);
}
- if ((sharpCount>1 && v->numFaces) || seam) {
+ if (sharpCount>1 || seam) {
VertDataZero(q);
if (seam) {
@@ -1524,7 +1528,7 @@ static void ccgSubSurf__sync(CCGSubSurf *ss) {
void *nCo = VERT_getCo(v, nextLvl);
int sharpCount = 0, allSharp = 1;
float avgSharpness = 0.0;
- int seam = VERT_seam(v, ss), seamEdges = 0;
+ int seam = VERT_seam(v), seamEdges = 0;
for (i=0; i<v->numEdges; i++) {
CCGEdge *e = v->edges[i];
@@ -1541,9 +1545,11 @@ static void ccgSubSurf__sync(CCGSubSurf *ss) {
}
}
- avgSharpness /= sharpCount;
- if (avgSharpness>1.0) {
- avgSharpness = 1.0;
+ if(sharpCount) {
+ avgSharpness /= sharpCount;
+ if (avgSharpness>1.0) {
+ avgSharpness = 1.0;
+ }
}
if (seam && seamEdges < 2)
@@ -2069,7 +2075,7 @@ int ccgSubSurf_getGridLevelSize(CCGSubSurf *ss, int level) {
/* Vert accessors */
-CCGVertHDL ccgSubSurf_getVertVertHandle(CCGSubSurf *ss, CCGVert *v) {
+CCGVertHDL ccgSubSurf_getVertVertHandle(CCGVert *v) {
return v->vHDL;
}
int ccgSubSurf_getVertAge(CCGSubSurf *ss, CCGVert *v) {
@@ -2083,20 +2089,20 @@ int ccgSubSurf_getVertAge(CCGSubSurf *ss, CCGVert *v) {
void *ccgSubSurf_getVertUserData(CCGSubSurf *ss, CCGVert *v) {
return VERT_getLevelData(v) + ss->meshIFC.vertDataSize*(ss->subdivLevels+1);
}
-int ccgSubSurf_getVertNumFaces(CCGSubSurf *ss, CCGVert *v) {
+int ccgSubSurf_getVertNumFaces(CCGVert *v) {
return v->numFaces;
}
-CCGFace *ccgSubSurf_getVertFace(CCGSubSurf *ss, CCGVert *v, int index) {
+CCGFace *ccgSubSurf_getVertFace(CCGVert *v, int index) {
if (index<0 || index>=v->numFaces) {
return NULL;
} else {
return v->faces[index];
}
}
-int ccgSubSurf_getVertNumEdges(CCGSubSurf *ss, CCGVert *v) {
+int ccgSubSurf_getVertNumEdges(CCGVert *v) {
return v->numEdges;
}
-CCGEdge *ccgSubSurf_getVertEdge(CCGSubSurf *ss, CCGVert *v, int index) {
+CCGEdge *ccgSubSurf_getVertEdge(CCGVert *v, int index) {
if (index<0 || index>=v->numEdges) {
return NULL;
} else {
@@ -2116,7 +2122,7 @@ void *ccgSubSurf_getVertLevelData(CCGSubSurf *ss, CCGVert *v, int level) {
/* Edge accessors */
-CCGEdgeHDL ccgSubSurf_getEdgeEdgeHandle(CCGSubSurf *ss, CCGEdge *e) {
+CCGEdgeHDL ccgSubSurf_getEdgeEdgeHandle(CCGEdge *e) {
return e->eHDL;
}
int ccgSubSurf_getEdgeAge(CCGSubSurf *ss, CCGEdge *e) {
@@ -2130,20 +2136,20 @@ int ccgSubSurf_getEdgeAge(CCGSubSurf *ss, CCGEdge *e) {
void *ccgSubSurf_getEdgeUserData(CCGSubSurf *ss, CCGEdge *e) {
return EDGE_getLevelData(e) + ss->meshIFC.vertDataSize *((ss->subdivLevels+1) + (1<<(ss->subdivLevels+1))-1);
}
-int ccgSubSurf_getEdgeNumFaces(CCGSubSurf *ss, CCGEdge *e) {
+int ccgSubSurf_getEdgeNumFaces(CCGEdge *e) {
return e->numFaces;
}
-CCGFace *ccgSubSurf_getEdgeFace(CCGSubSurf *ss, CCGEdge *e, int index) {
+CCGFace *ccgSubSurf_getEdgeFace(CCGEdge *e, int index) {
if (index<0 || index>=e->numFaces) {
return NULL;
} else {
return e->faces[index];
}
}
-CCGVert *ccgSubSurf_getEdgeVert0(CCGSubSurf *ss, CCGEdge *e) {
+CCGVert *ccgSubSurf_getEdgeVert0(CCGEdge *e) {
return e->v0;
}
-CCGVert *ccgSubSurf_getEdgeVert1(CCGSubSurf *ss, CCGEdge *e) {
+CCGVert *ccgSubSurf_getEdgeVert1(CCGEdge *e) {
return e->v1;
}
void *ccgSubSurf_getEdgeDataArray(CCGSubSurf *ss, CCGEdge *e) {
@@ -2159,7 +2165,7 @@ void *ccgSubSurf_getEdgeLevelData(CCGSubSurf *ss, CCGEdge *e, int x, int level)
return _edge_getCo(e, level, x, ss->meshIFC.vertDataSize);
}
}
-float ccgSubSurf_getEdgeCrease(CCGSubSurf *ss, CCGEdge *e) {
+float ccgSubSurf_getEdgeCrease(CCGEdge *e) {
return e->crease;
}
@@ -2180,7 +2186,7 @@ void *ccgSubSurf_getFaceUserData(CCGSubSurf *ss, CCGFace *f) {
int maxGridSize = 1 + (1<<(ss->subdivLevels-1));
return FACE_getCenterData(f) + ss->meshIFC.vertDataSize *(1 + f->numVerts*maxGridSize + f->numVerts*maxGridSize*maxGridSize);
}
-int ccgSubSurf_getFaceNumVerts(CCGSubSurf *ss, CCGFace *f) {
+int ccgSubSurf_getFaceNumVerts(CCGFace *f) {
return f->numVerts;
}
CCGVert *ccgSubSurf_getFaceVert(CCGSubSurf *ss, CCGFace *f, int index) {
@@ -2197,7 +2203,7 @@ CCGEdge *ccgSubSurf_getFaceEdge(CCGSubSurf *ss, CCGFace *f, int index) {
return FACE_getEdges(f)[index];
}
}
-int ccgSubSurf_getFaceEdgeIndex(CCGSubSurf *ss, CCGFace *f, CCGEdge *e) {
+int ccgSubSurf_getFaceEdgeIndex(CCGFace *f, CCGEdge *e) {
int i;
for (i=0; i<f->numVerts; i++)
@@ -2206,7 +2212,7 @@ int ccgSubSurf_getFaceEdgeIndex(CCGSubSurf *ss, CCGFace *f, CCGEdge *e) {
return -1;
}
-void *ccgSubSurf_getFaceCenterData(CCGSubSurf *ss, CCGFace *f) {
+void *ccgSubSurf_getFaceCenterData(CCGFace *f) {
return FACE_getCenterData(f);
}
void *ccgSubSurf_getFaceGridEdgeDataArray(CCGSubSurf *ss, CCGFace *f, int gridIndex) {
diff --git a/source/blender/blenkernel/intern/CCGSubSurf.h b/source/blender/blenkernel/intern/CCGSubSurf.h
index 91f3ffab43b..fbd0aecc0a5 100644
--- a/source/blender/blenkernel/intern/CCGSubSurf.h
+++ b/source/blender/blenkernel/intern/CCGSubSurf.h
@@ -82,11 +82,11 @@ int ccgSubSurf_getGridSize (CCGSubSurf *ss);
int ccgSubSurf_getGridLevelSize (CCGSubSurf *ss, int level);
CCGVert* ccgSubSurf_getVert (CCGSubSurf *ss, CCGVertHDL v);
-CCGVertHDL ccgSubSurf_getVertVertHandle (CCGSubSurf *ss, CCGVert *v);
-int ccgSubSurf_getVertNumFaces (CCGSubSurf *ss, CCGVert *v);
-CCGFace* ccgSubSurf_getVertFace (CCGSubSurf *ss, CCGVert *v, int index);
-int ccgSubSurf_getVertNumEdges (CCGSubSurf *ss, CCGVert *v);
-CCGEdge* ccgSubSurf_getVertEdge (CCGSubSurf *ss, CCGVert *v, int index);
+CCGVertHDL ccgSubSurf_getVertVertHandle (CCGVert *v);
+int ccgSubSurf_getVertNumFaces (CCGVert *v);
+CCGFace* ccgSubSurf_getVertFace (CCGVert *v, int index);
+int ccgSubSurf_getVertNumEdges (CCGVert *v);
+CCGEdge* ccgSubSurf_getVertEdge (CCGVert *v, int index);
int ccgSubSurf_getVertAge (CCGSubSurf *ss, CCGVert *v);
void* ccgSubSurf_getVertUserData (CCGSubSurf *ss, CCGVert *v);
@@ -94,12 +94,12 @@ void* ccgSubSurf_getVertData (CCGSubSurf *ss, CCGVert *v);
void* ccgSubSurf_getVertLevelData (CCGSubSurf *ss, CCGVert *v, int level);
CCGEdge* ccgSubSurf_getEdge (CCGSubSurf *ss, CCGEdgeHDL e);
-CCGEdgeHDL ccgSubSurf_getEdgeEdgeHandle (CCGSubSurf *ss, CCGEdge *e);
-int ccgSubSurf_getEdgeNumFaces (CCGSubSurf *ss, CCGEdge *e);
-CCGFace* ccgSubSurf_getEdgeFace (CCGSubSurf *ss, CCGEdge *e, int index);
-CCGVert* ccgSubSurf_getEdgeVert0 (CCGSubSurf *ss, CCGEdge *e);
-CCGVert* ccgSubSurf_getEdgeVert1 (CCGSubSurf *ss, CCGEdge *e);
-float ccgSubSurf_getEdgeCrease (CCGSubSurf *ss, CCGEdge *e);
+CCGEdgeHDL ccgSubSurf_getEdgeEdgeHandle (CCGEdge *e);
+int ccgSubSurf_getEdgeNumFaces (CCGEdge *e);
+CCGFace* ccgSubSurf_getEdgeFace (CCGEdge *e, int index);
+CCGVert* ccgSubSurf_getEdgeVert0 (CCGEdge *e);
+CCGVert* ccgSubSurf_getEdgeVert1 (CCGEdge *e);
+float ccgSubSurf_getEdgeCrease (CCGEdge *e);
int ccgSubSurf_getEdgeAge (CCGSubSurf *ss, CCGEdge *e);
void* ccgSubSurf_getEdgeUserData (CCGSubSurf *ss, CCGEdge *e);
@@ -109,14 +109,14 @@ void* ccgSubSurf_getEdgeLevelData (CCGSubSurf *ss, CCGEdge *e, int x, int lev
CCGFace* ccgSubSurf_getFace (CCGSubSurf *ss, CCGFaceHDL f);
CCGFaceHDL ccgSubSurf_getFaceFaceHandle (CCGSubSurf *ss, CCGFace *f);
-int ccgSubSurf_getFaceNumVerts (CCGSubSurf *ss, CCGFace *f);
+int ccgSubSurf_getFaceNumVerts (CCGFace *f);
CCGVert* ccgSubSurf_getFaceVert (CCGSubSurf *ss, CCGFace *f, int index);
CCGEdge* ccgSubSurf_getFaceEdge (CCGSubSurf *ss, CCGFace *f, int index);
-int ccgSubSurf_getFaceEdgeIndex (CCGSubSurf *ss, CCGFace *f, CCGEdge *e);
+int ccgSubSurf_getFaceEdgeIndex (CCGFace *f, CCGEdge *e);
int ccgSubSurf_getFaceAge (CCGSubSurf *ss, CCGFace *f);
void* ccgSubSurf_getFaceUserData (CCGSubSurf *ss, CCGFace *f);
-void* ccgSubSurf_getFaceCenterData (CCGSubSurf *ss, CCGFace *f);
+void* ccgSubSurf_getFaceCenterData (CCGFace *f);
void* ccgSubSurf_getFaceGridEdgeDataArray (CCGSubSurf *ss, CCGFace *f, int gridIndex);
void* ccgSubSurf_getFaceGridEdgeData (CCGSubSurf *ss, CCGFace *f, int gridIndex, int x);
void* ccgSubSurf_getFaceGridDataArray (CCGSubSurf *ss, CCGFace *f, int gridIndex);
diff --git a/source/blender/blenkernel/intern/DerivedMesh.c b/source/blender/blenkernel/intern/DerivedMesh.c
index 473c64f58f2..aab39a099bf 100644
--- a/source/blender/blenkernel/intern/DerivedMesh.c
+++ b/source/blender/blenkernel/intern/DerivedMesh.c
@@ -33,8 +33,6 @@
#include <config.h>
#endif
-#include <zlib.h>
-
#include "PIL_time.h"
#include "MEM_guardedalloc.h"
@@ -59,6 +57,7 @@
#include "BLI_edgehash.h"
#include "BLI_editVert.h"
#include "BLI_linklist.h"
+#include "BLI_memarena.h"
#include "BKE_cdderivedmesh.h"
#include "BKE_customdata.h"
@@ -66,17 +65,21 @@
#include "BKE_deform.h"
#include "BKE_displist.h"
#include "BKE_effect.h"
+#include "BKE_fluidsim.h"
#include "BKE_global.h"
#include "BKE_key.h"
#include "BKE_material.h"
#include "BKE_modifier.h"
#include "BKE_mesh.h"
+#include "BKE_multires.h"
#include "BKE_object.h"
#include "BKE_subsurf.h"
#include "BKE_texture.h"
#include "BKE_utildefines.h"
#include "BKE_particle.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
#ifdef WITH_VERSE
#include "BKE_verse.h"
#endif
@@ -85,16 +88,15 @@
#include "BIF_glutil.h"
//XXX #include "multires.h"
-
-// headers for fluidsim bobj meshes
-#include <stdlib.h>
-#include "LBM_fluidsim.h"
-#include "elbeem.h"
+//
+#include "GPU_draw.h"
+#include "GPU_extensions.h"
+#include "GPU_material.h"
///////////////////////////////////
///////////////////////////////////
-MVert *dm_getVertArray(DerivedMesh *dm)
+static MVert *dm_getVertArray(DerivedMesh *dm)
{
MVert *mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
@@ -108,7 +110,7 @@ MVert *dm_getVertArray(DerivedMesh *dm)
return mvert;
}
-MEdge *dm_getEdgeArray(DerivedMesh *dm)
+static MEdge *dm_getEdgeArray(DerivedMesh *dm)
{
MEdge *medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
@@ -122,7 +124,7 @@ MEdge *dm_getEdgeArray(DerivedMesh *dm)
return medge;
}
-MFace *dm_getFaceArray(DerivedMesh *dm)
+static MFace *dm_getFaceArray(DerivedMesh *dm)
{
MFace *mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
@@ -136,7 +138,7 @@ MFace *dm_getFaceArray(DerivedMesh *dm)
return mface;
}
-MVert *dm_dupVertArray(DerivedMesh *dm)
+static MVert *dm_dupVertArray(DerivedMesh *dm)
{
MVert *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumVerts(dm),
"dm_dupVertArray tmp");
@@ -146,7 +148,7 @@ MVert *dm_dupVertArray(DerivedMesh *dm)
return tmp;
}
-MEdge *dm_dupEdgeArray(DerivedMesh *dm)
+static MEdge *dm_dupEdgeArray(DerivedMesh *dm)
{
MEdge *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumEdges(dm),
"dm_dupEdgeArray tmp");
@@ -156,7 +158,7 @@ MEdge *dm_dupEdgeArray(DerivedMesh *dm)
return tmp;
}
-MFace *dm_dupFaceArray(DerivedMesh *dm)
+static MFace *dm_dupFaceArray(DerivedMesh *dm)
{
MFace *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumFaces(dm),
"dm_dupFaceArray tmp");
@@ -187,10 +189,6 @@ void DM_init_funcs(DerivedMesh *dm)
void DM_init(DerivedMesh *dm,
int numVerts, int numEdges, int numFaces)
{
- CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, numVerts);
- CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
- CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numFaces);
-
dm->numVertData = numVerts;
dm->numEdgeData = numEdges;
dm->numFaceData = numFaces;
@@ -413,39 +411,20 @@ void DM_swap_face_data(DerivedMesh *dm, int index, int *corner_indices)
CustomData_swap(&dm->faceData, index, corner_indices);
}
+///
+
static DerivedMesh *getMeshDerivedMesh(Mesh *me, Object *ob, float (*vertCos)[3])
{
DerivedMesh *dm = CDDM_from_mesh(me, ob);
- int i, dofluidsim;
-
- dofluidsim = ((ob->fluidsimFlag & OB_FLUIDSIM_ENABLE) &&
- (ob->fluidsimSettings->type & OB_FLUIDSIM_DOMAIN)&&
- (ob->fluidsimSettings->meshSurface) &&
- (1) && (!give_parteff(ob)) && // doesnt work together with particle systems!
- (me->totvert == ((Mesh *)(ob->fluidsimSettings->meshSurface))->totvert));
-
- if (vertCos && !dofluidsim)
+
+ if(!dm)
+ return NULL;
+
+ if (vertCos)
CDDM_apply_vert_coords(dm, vertCos);
CDDM_calc_normals(dm);
- /* apply fluidsim normals */
- if (dofluidsim) {
- // use normals from readBobjgz
- // TODO? check for modifiers!?
- MVert *fsvert = ob->fluidsimSettings->meshSurfNormals;
- short (*normals)[3] = MEM_mallocN(sizeof(short)*3*me->totvert, "fluidsim nor");
-
- for (i=0; i<me->totvert; i++) {
- VECCOPY(normals[i], fsvert[i].no);
- //mv->no[0]= 30000; mv->no[1]= mv->no[2]= 0; // DEBUG fixed test normals
- }
-
- CDDM_apply_vert_normals(dm, normals);
-
- MEM_freeN(normals);
- }
-
return dm;
}
@@ -484,7 +463,7 @@ static void emDM_foreachMappedEdge(DerivedMesh *dm, void (*func)(void *userData,
EditVert *eve;
for (i=0,eve=emdm->em->verts.first; eve; eve= eve->next)
- eve->tmp.l = (long) i++;
+ eve->tmp.l = (intptr_t) i++;
for(i=0,eed= emdm->em->edges.first; eed; i++,eed= eed->next)
func(userData, i, emdm->vertexCos[(int) eed->v1->tmp.l], emdm->vertexCos[(int) eed->v2->tmp.l]);
} else {
@@ -502,7 +481,7 @@ static void emDM_drawMappedEdges(DerivedMesh *dm, int (*setDrawOptions)(void *us
EditVert *eve;
for (i=0,eve=emdm->em->verts.first; eve; eve= eve->next)
- eve->tmp.l = (long) i++;
+ eve->tmp.l = (intptr_t) i++;
glBegin(GL_LINES);
for(i=0,eed= emdm->em->edges.first; eed; i++,eed= eed->next) {
@@ -537,7 +516,7 @@ static void emDM_drawMappedEdgesInterp(DerivedMesh *dm, int (*setDrawOptions)(vo
EditVert *eve;
for (i=0,eve=emdm->em->verts.first; eve; eve= eve->next)
- eve->tmp.l = (long) i++;
+ eve->tmp.l = (intptr_t) i++;
glBegin(GL_LINES);
for (i=0,eed= emdm->em->edges.first; eed; i++,eed= eed->next) {
@@ -624,7 +603,7 @@ static void emDM_foreachMappedFaceCenter(DerivedMesh *dm, void (*func)(void *use
if (emdm->vertexCos) {
for (i=0,eve=emdm->em->verts.first; eve; eve= eve->next)
- eve->tmp.l = (long) i++;
+ eve->tmp.l = (intptr_t) i++;
}
for(i=0,efa= emdm->em->faces.first; efa; i++,efa= efa->next) {
@@ -634,7 +613,6 @@ static void emDM_foreachMappedFaceCenter(DerivedMesh *dm, void (*func)(void *use
}
static void emDM_drawMappedFaces(DerivedMesh *dm, int (*setDrawOptions)(void *userData, int index, int *drawSmooth_r), void *userData, int useColors)
{
- GLubyte act_face_stipple[32*32/8] = DM_FACE_STIPPLE;
EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
EditFace *efa;
int i, draw;
@@ -643,7 +621,7 @@ static void emDM_drawMappedFaces(DerivedMesh *dm, int (*setDrawOptions)(void *us
EditVert *eve;
for (i=0,eve=emdm->em->verts.first; eve; eve= eve->next)
- eve->tmp.l = (long) i++;
+ eve->tmp.l = (intptr_t) i++;
for (i=0,efa= emdm->em->faces.first; efa; i++,efa= efa->next) {
int drawSmooth = (efa->flag & ME_SMOOTH);
@@ -651,7 +629,7 @@ static void emDM_drawMappedFaces(DerivedMesh *dm, int (*setDrawOptions)(void *us
if(draw) {
if (draw==2) { /* enabled with stipple */
glEnable(GL_POLYGON_STIPPLE);
- glPolygonStipple(act_face_stipple);
+ glPolygonStipple(0); //XXX stipple_quarttone);
}
glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
@@ -688,7 +666,7 @@ static void emDM_drawMappedFaces(DerivedMesh *dm, int (*setDrawOptions)(void *us
if(draw) {
if (draw==2) { /* enabled with stipple */
glEnable(GL_POLYGON_STIPPLE);
- glPolygonStipple(act_face_stipple);
+ glPolygonStipple(0); //XXX stipple_quarttone);
}
glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
@@ -732,11 +710,14 @@ static void emDM_drawFacesTex_common(DerivedMesh *dm,
EditFace *efa;
int i;
+ /* always use smooth shading even for flat faces, else vertex colors wont interpolate */
+ glShadeModel(GL_SMOOTH);
+
if (vertexCos) {
EditVert *eve;
for (i=0,eve=em->verts.first; eve; eve= eve->next)
- eve->tmp.l = (long) i++;
+ eve->tmp.l = (intptr_t) i++;
for (i=0,efa= em->faces.first; efa; i++,efa= efa->next) {
MTFace *tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
@@ -753,11 +734,16 @@ static void emDM_drawFacesTex_common(DerivedMesh *dm,
flag= 1;
if(flag != 0) { /* flag 0 == the face is hidden or invisible */
- if (flag==1 && mcol)
- cp= (unsigned char*)mcol;
-
- glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
-
+
+ /* we always want smooth here since otherwise vertex colors dont interpolate */
+ if (mcol) {
+ if (flag==1) {
+ cp= (unsigned char*)mcol;
+ }
+ } else {
+ glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
+ }
+
glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
if (!drawSmooth) {
glNormal3fv(emdm->faceNos[i]);
@@ -821,10 +807,14 @@ static void emDM_drawFacesTex_common(DerivedMesh *dm,
flag= 1;
if(flag != 0) { /* flag 0 == the face is hidden or invisible */
- if (flag==1 && mcol)
- cp= (unsigned char*)mcol;
-
- glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
+ /* we always want smooth here since otherwise vertex colors dont interpolate */
+ if (mcol) {
+ if (flag==1) {
+ cp= (unsigned char*)mcol;
+ }
+ } else {
+ glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
+ }
glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
if (!drawSmooth) {
@@ -886,6 +876,162 @@ static void emDM_drawMappedFacesTex(DerivedMesh *dm, int (*setDrawOptions)(void
emDM_drawFacesTex_common(dm, NULL, setDrawOptions, userData);
}
+static void emDM_drawMappedFacesGLSL(DerivedMesh *dm,
+ int (*setMaterial)(int, void *attribs),
+ int (*setDrawOptions)(void *userData, int index), void *userData)
+{
+ EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
+ EditMesh *em= emdm->em;
+ float (*vertexCos)[3]= emdm->vertexCos;
+ float (*vertexNos)[3]= emdm->vertexNos;
+ EditVert *eve;
+ EditFace *efa;
+ DMVertexAttribs attribs;
+ GPUVertexAttribs gattribs;
+ MTFace *tf;
+ int transp, new_transp, orig_transp, tfoffset;
+ int i, b, matnr, new_matnr, dodraw, layer;
+
+ dodraw = 0;
+ matnr = -1;
+
+ transp = GPU_get_material_blend_mode();
+ orig_transp = transp;
+ layer = CustomData_get_layer_index(&em->fdata, CD_MTFACE);
+ tfoffset = (layer == -1)? -1: em->fdata.layers[layer].offset;
+
+ memset(&attribs, 0, sizeof(attribs));
+
+ /* always use smooth shading even for flat faces, else vertex colors wont interpolate */
+ glShadeModel(GL_SMOOTH);
+
+ for (i=0,eve=em->verts.first; eve; eve= eve->next)
+ eve->tmp.l = (long) i++;
+
+#define PASSATTRIB(efa, eve, vert) { \
+ if(attribs.totorco) { \
+ float *orco = attribs.orco.array[eve->tmp.l]; \
+ glVertexAttrib3fvARB(attribs.orco.glIndex, orco); \
+ } \
+ for(b = 0; b < attribs.tottface; b++) { \
+ MTFace *_tf = (MTFace*)((char*)efa->data + attribs.tface[b].emOffset); \
+ glVertexAttrib2fvARB(attribs.tface[b].glIndex, _tf->uv[vert]); \
+ } \
+ for(b = 0; b < attribs.totmcol; b++) { \
+ MCol *cp = (MCol*)((char*)efa->data + attribs.mcol[b].emOffset); \
+ GLubyte col[4]; \
+ col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a; \
+ glVertexAttrib4ubvARB(attribs.mcol[b].glIndex, col); \
+ } \
+ if(attribs.tottang) { \
+ float *tang = attribs.tang.array[i*4 + vert]; \
+ glVertexAttrib3fvARB(attribs.tang.glIndex, tang); \
+ } \
+}
+
+ for (i=0,efa= em->faces.first; efa; i++,efa= efa->next) {
+ int drawSmooth= (efa->flag & ME_SMOOTH);
+
+ if(setDrawOptions && !setDrawOptions(userData, i))
+ continue;
+
+ new_matnr = efa->mat_nr + 1;
+ if(new_matnr != matnr) {
+ dodraw = setMaterial(matnr = new_matnr, &gattribs);
+ if(dodraw)
+ DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
+ }
+
+ if(tfoffset != -1) {
+ tf = (MTFace*)((char*)efa->data)+tfoffset;
+ new_transp = tf->transp;
+
+ if(new_transp != transp) {
+ if(new_transp == GPU_BLEND_SOLID && orig_transp != GPU_BLEND_SOLID)
+ GPU_set_material_blend_mode(orig_transp);
+ else
+ GPU_set_material_blend_mode(new_transp);
+ transp = new_transp;
+ }
+ }
+
+ if(dodraw) {
+ glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
+ if (!drawSmooth) {
+ if(vertexCos) glNormal3fv(emdm->faceNos[i]);
+ else glNormal3fv(efa->n);
+
+ PASSATTRIB(efa, efa->v1, 0);
+ if(vertexCos) glVertex3fv(vertexCos[(int) efa->v1->tmp.l]);
+ else glVertex3fv(efa->v1->co);
+
+ PASSATTRIB(efa, efa->v2, 1);
+ if(vertexCos) glVertex3fv(vertexCos[(int) efa->v2->tmp.l]);
+ else glVertex3fv(efa->v2->co);
+
+ PASSATTRIB(efa, efa->v3, 2);
+ if(vertexCos) glVertex3fv(vertexCos[(int) efa->v3->tmp.l]);
+ else glVertex3fv(efa->v3->co);
+
+ if(efa->v4) {
+ PASSATTRIB(efa, efa->v4, 3);
+ if(vertexCos) glVertex3fv(vertexCos[(int) efa->v4->tmp.l]);
+ else glVertex3fv(efa->v4->co);
+ }
+ } else {
+ PASSATTRIB(efa, efa->v1, 0);
+ if(vertexCos) {
+ glNormal3fv(vertexNos[(int) efa->v1->tmp.l]);
+ glVertex3fv(vertexCos[(int) efa->v1->tmp.l]);
+ }
+ else {
+ glNormal3fv(efa->v1->no);
+ glVertex3fv(efa->v1->co);
+ }
+
+ PASSATTRIB(efa, efa->v2, 1);
+ if(vertexCos) {
+ glNormal3fv(vertexNos[(int) efa->v2->tmp.l]);
+ glVertex3fv(vertexCos[(int) efa->v2->tmp.l]);
+ }
+ else {
+ glNormal3fv(efa->v2->no);
+ glVertex3fv(efa->v2->co);
+ }
+
+ PASSATTRIB(efa, efa->v3, 2);
+ if(vertexCos) {
+ glNormal3fv(vertexNos[(int) efa->v3->tmp.l]);
+ glVertex3fv(vertexCos[(int) efa->v3->tmp.l]);
+ }
+ else {
+ glNormal3fv(efa->v3->no);
+ glVertex3fv(efa->v3->co);
+ }
+
+ if(efa->v4) {
+ PASSATTRIB(efa, efa->v4, 3);
+ if(vertexCos) {
+ glNormal3fv(vertexNos[(int) efa->v4->tmp.l]);
+ glVertex3fv(vertexCos[(int) efa->v4->tmp.l]);
+ }
+ else {
+ glNormal3fv(efa->v4->no);
+ glVertex3fv(efa->v4->co);
+ }
+ }
+ }
+ glEnd();
+ }
+ }
+}
+
+static void emDM_drawFacesGLSL(DerivedMesh *dm,
+ int (*setMaterial)(int, void *attribs))
+{
+ dm->drawMappedFacesGLSL(dm, setMaterial, NULL, NULL);
+}
+
static void emDM_getMinMax(DerivedMesh *dm, float min_r[3], float max_r[3])
{
EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
@@ -925,7 +1071,7 @@ static int emDM_getNumFaces(DerivedMesh *dm)
return BLI_countlist(&emdm->em->faces);
}
-void emDM_getVert(DerivedMesh *dm, int index, MVert *vert_r)
+static void emDM_getVert(DerivedMesh *dm, int index, MVert *vert_r)
{
EditVert *ev = ((EditMeshDerivedMesh *)dm)->em->verts.first;
int i;
@@ -940,9 +1086,10 @@ void emDM_getVert(DerivedMesh *dm, int index, MVert *vert_r)
/* TODO what to do with vert_r->flag and vert_r->mat_nr? */
vert_r->mat_nr = 0;
+ vert_r->bweight = (unsigned char) (ev->bweight*255.0f);
}
-void emDM_getEdge(DerivedMesh *dm, int index, MEdge *edge_r)
+static void emDM_getEdge(DerivedMesh *dm, int index, MEdge *edge_r)
{
EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
EditEdge *ee = em->edges.first;
@@ -952,6 +1099,7 @@ void emDM_getEdge(DerivedMesh *dm, int index, MEdge *edge_r)
for(i = 0; i < index; ++i) ee = ee->next;
edge_r->crease = (unsigned char) (ee->crease*255.0f);
+ edge_r->bweight = (unsigned char) (ee->bweight*255.0f);
/* TODO what to do with edge_r->flag? */
edge_r->flag = ME_EDGEDRAW|ME_EDGERENDER;
if (ee->seam) edge_r->flag |= ME_SEAM;
@@ -976,7 +1124,7 @@ void emDM_getEdge(DerivedMesh *dm, int index, MEdge *edge_r)
}
}
-void emDM_getFace(DerivedMesh *dm, int index, MFace *face_r)
+static void emDM_getFace(DerivedMesh *dm, int index, MFace *face_r)
{
EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
EditFace *ef = em->faces.first;
@@ -1018,7 +1166,7 @@ void emDM_getFace(DerivedMesh *dm, int index, MFace *face_r)
test_index_face(face_r, NULL, 0, ef->v4?4:3);
}
-void emDM_copyVertArray(DerivedMesh *dm, MVert *vert_r)
+static void emDM_copyVertArray(DerivedMesh *dm, MVert *vert_r)
{
EditVert *ev = ((EditMeshDerivedMesh *)dm)->em->verts.first;
@@ -1032,10 +1180,11 @@ void emDM_copyVertArray(DerivedMesh *dm, MVert *vert_r)
/* TODO what to do with vert_r->flag and vert_r->mat_nr? */
vert_r->mat_nr = 0;
vert_r->flag = 0;
+ vert_r->bweight = (unsigned char) (ev->bweight*255.0f);
}
}
-void emDM_copyEdgeArray(DerivedMesh *dm, MEdge *edge_r)
+static void emDM_copyEdgeArray(DerivedMesh *dm, MEdge *edge_r)
{
EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
EditEdge *ee = em->edges.first;
@@ -1044,10 +1193,11 @@ void emDM_copyEdgeArray(DerivedMesh *dm, MEdge *edge_r)
/* store vertex indices in tmp union */
for(ev = em->verts.first, i = 0; ev; ev = ev->next, ++i)
- ev->tmp.l = (long) i++;
+ ev->tmp.l = (intptr_t) i;
for( ; ee; ee = ee->next, ++edge_r) {
edge_r->crease = (unsigned char) (ee->crease*255.0f);
+ edge_r->bweight = (unsigned char) (ee->bweight*255.0f);
/* TODO what to do with edge_r->flag? */
edge_r->flag = ME_EDGEDRAW|ME_EDGERENDER;
if (ee->seam) edge_r->flag |= ME_SEAM;
@@ -1062,7 +1212,7 @@ void emDM_copyEdgeArray(DerivedMesh *dm, MEdge *edge_r)
}
}
-void emDM_copyFaceArray(DerivedMesh *dm, MFace *face_r)
+static void emDM_copyFaceArray(DerivedMesh *dm, MFace *face_r)
{
EditMesh *em = ((EditMeshDerivedMesh *)dm)->em;
EditFace *ef = em->faces.first;
@@ -1071,7 +1221,7 @@ void emDM_copyFaceArray(DerivedMesh *dm, MFace *face_r)
/* store vertexes indices in tmp union */
for(ev = em->verts.first, i = 0; ev; ev = ev->next, ++i)
- ev->tmp.l = (long) i;
+ ev->tmp.l = (intptr_t) i;
for( ; ef; ef = ef->next, ++face_r) {
face_r->mat_nr = ef->mat_nr;
@@ -1087,6 +1237,43 @@ void emDM_copyFaceArray(DerivedMesh *dm, MFace *face_r)
}
}
+static void *emDM_getFaceDataArray(DerivedMesh *dm, int type)
+{
+ EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
+ EditMesh *em= emdm->em;
+ EditFace *efa;
+ char *data, *emdata;
+ void *datalayer;
+ int index, offset, size;
+
+ datalayer = DM_get_face_data_layer(dm, type);
+ if(datalayer)
+ return datalayer;
+
+ /* layers are store per face for editmesh, we convert to a temporary
+ * data layer array in the derivedmesh when these are requested */
+ if(type == CD_MTFACE || type == CD_MCOL) {
+ index = CustomData_get_layer_index(&em->fdata, type);
+
+ if(index != -1) {
+ offset = em->fdata.layers[index].offset;
+ size = CustomData_sizeof(type);
+
+ DM_add_face_layer(dm, type, CD_CALLOC, NULL);
+ index = CustomData_get_layer_index(&dm->faceData, type);
+ dm->faceData.layers[index].flag |= CD_FLAG_TEMPORARY;
+
+ data = datalayer = DM_get_face_data_layer(dm, type);
+ for(efa=em->faces.first; efa; efa=efa->next, data+=size) {
+ emdata = CustomData_em_get(&em->fdata, efa->data, type);
+ memcpy(data, emdata, size);
+ }
+ }
+ }
+
+ return datalayer;
+}
+
static void emDM_release(DerivedMesh *dm)
{
EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm;
@@ -1122,6 +1309,7 @@ static DerivedMesh *getEditMeshDerivedMesh(EditMesh *em, Object *ob,
emdm->dm.copyVertArray = emDM_copyVertArray;
emdm->dm.copyEdgeArray = emDM_copyEdgeArray;
emdm->dm.copyFaceArray = emDM_copyFaceArray;
+ emdm->dm.getFaceDataArray = emDM_getFaceDataArray;
emdm->dm.foreachMappedVert = emDM_foreachMappedVert;
emdm->dm.foreachMappedEdge = emDM_foreachMappedEdge;
@@ -1132,7 +1320,9 @@ static DerivedMesh *getEditMeshDerivedMesh(EditMesh *em, Object *ob,
emdm->dm.drawMappedEdgesInterp = emDM_drawMappedEdgesInterp;
emdm->dm.drawMappedFaces = emDM_drawMappedFaces;
emdm->dm.drawMappedFacesTex = emDM_drawMappedFacesTex;
+ emdm->dm.drawMappedFacesGLSL = emDM_drawMappedFacesGLSL;
emdm->dm.drawFacesTex = emDM_drawFacesTex;
+ emdm->dm.drawFacesGLSL = emDM_drawFacesGLSL;
emdm->dm.drawUVEdges = emDM_drawUVEdges;
emdm->dm.release = emDM_release;
@@ -1158,7 +1348,7 @@ static DerivedMesh *getEditMeshDerivedMesh(EditMesh *em, Object *ob,
int i;
for (i=0,eve=em->verts.first; eve; eve= eve->next)
- eve->tmp.l = (long) i++;
+ eve->tmp.l = (intptr_t) i++;
emdm->vertexNos = MEM_callocN(sizeof(*emdm->vertexNos)*i, "emdm_vno");
emdm->faceNos = MEM_mallocN(sizeof(*emdm->faceNos)*totface, "emdm_vno");
@@ -1316,6 +1506,7 @@ void vDM_getEdge(DerivedMesh *dm, int index, MEdge *edge_r)
/* not supported yet */
edge_r->flag = 0;
edge_r->crease = 0;
+ edge_r->bweight = 0;
break;
}
}
@@ -1422,6 +1613,7 @@ void vDM_copyEdgeArray(DerivedMesh *dm, MEdge *edge_r)
/* not supported yet */
edge_r->flag = 0;
edge_r->crease = 0;
+ edge_r->bweight = 0;
}
}
}
@@ -1560,7 +1752,7 @@ static void vDM_drawUVEdges(DerivedMesh *dm)
}
/* draw all VerseFaces */
-static void vDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int))
+static void vDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int, void *attribs))
{
VDerivedMesh *vdm = (VDerivedMesh*)dm;
struct VerseFace *vface;
@@ -1660,6 +1852,8 @@ static void vDM_drawMappedFacesTex(
int (*setDrawParams)(void *userData, int index),
void *userData)
{
+ /* not supported yet */
+ vDM_drawFacesTex(dm, NULL);
}
/**/
@@ -1801,19 +1995,23 @@ CustomDataMask get_viewedit_datamask()
ScrArea *sa;
/* check if we need tfaces & mcols due to face select or texture paint */
- if(FACESEL_PAINT_TEST || G.f & G_TEXTUREPAINT) {
+ if(FACESEL_PAINT_TEST || G.f & G_TEXTUREPAINT)
mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
- } else {
- /* check if we need tfaces & mcols due to view mode */
- for(sa = G.curscreen->areabase.first; sa; sa = sa->next) {
- if(sa->spacetype == SPACE_VIEW3D) {
- View3D *view = sa->spacedata.first;
- if(view->drawtype == OB_SHADED) {
- /* this includes normals for mesh_create_shadedColors */
- mask |= CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_NORMAL | CD_MASK_ORCO;
- }
- if((view->drawtype == OB_TEXTURE) || ((view->drawtype == OB_SOLID) && (view->flag2 & V3D_SOLID_TEX))) {
- mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
+
+ /* check if we need tfaces & mcols due to view mode */
+ for(sa = G.curscreen->areabase.first; sa; sa = sa->next) {
+ if(sa->spacetype == SPACE_VIEW3D) {
+ View3D *view = sa->spacedata.first;
+ if(view->drawtype == OB_SHADED) {
+ /* this includes normals for mesh_create_shadedColors */
+ mask |= CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_NORMAL | CD_MASK_ORCO;
+ }
+ if((view->drawtype == OB_TEXTURE) || ((view->drawtype == OB_SOLID) && (view->flag2 & V3D_SOLID_TEX))) {
+ mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
+
+ if((G.fileflags & G_FILE_GAME_MAT) &&
+ (G.fileflags & G_FILE_GAME_MAT_GLSL)) {
+ mask |= CD_MASK_ORCO;
}
}
}
@@ -1826,13 +2024,41 @@ CustomDataMask get_viewedit_datamask()
return mask;
}
-static DerivedMesh *create_orco_dm(Object *ob, Mesh *me)
+static float *get_editmesh_orco_verts(EditMesh *em)
+{
+ EditVert *eve;
+ float *orco;
+ int a, totvert;
+
+ /* these may not really be the orco's, but it's only for preview.
+ * could be solver better once, but isn't simple */
+
+ totvert= 0;
+ for(eve=em->verts.first; eve; eve=eve->next)
+ totvert++;
+
+ orco = MEM_mallocN(sizeof(float)*3*totvert, "EditMesh Orco");
+
+ for(a=0, eve=em->verts.first; eve; eve=eve->next, a+=3)
+ VECCOPY(orco+a, eve->co);
+
+ return orco;
+}
+
+static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, EditMesh *em)
{
DerivedMesh *dm;
float (*orco)[3];
- dm= CDDM_from_mesh(me, ob);
- orco= (float(*)[3])get_mesh_orco_verts(ob);
+ if(em) {
+ dm= CDDM_from_editmesh(em, me);
+ orco= (float(*)[3])get_editmesh_orco_verts(em);
+ }
+ else {
+ dm= CDDM_from_mesh(me, ob);
+ orco= (float(*)[3])get_mesh_orco_verts(ob);
+ }
+
CDDM_apply_vert_coords(dm, orco);
CDDM_calc_normals(dm);
MEM_freeN(orco);
@@ -1840,7 +2066,7 @@ static DerivedMesh *create_orco_dm(Object *ob, Mesh *me)
return dm;
}
-static void add_orco_dm(Object *ob, DerivedMesh *dm, DerivedMesh *orcodm)
+static void add_orco_dm(Object *ob, EditMesh *em, DerivedMesh *dm, DerivedMesh *orcodm)
{
float (*orco)[3], (*layerorco)[3];
int totvert;
@@ -1855,8 +2081,10 @@ static void add_orco_dm(Object *ob, DerivedMesh *dm, DerivedMesh *orcodm)
else
dm->getVertCos(dm, orco);
}
- else
- orco= (float(*)[3])get_mesh_orco_verts(ob);
+ else {
+ if(em) orco= (float(*)[3])get_editmesh_orco_verts(em);
+ else orco= (float(*)[3])get_mesh_orco_verts(ob);
+ }
transform_mesh_orco_verts(ob->data, orco, totvert, 0);
@@ -1871,7 +2099,7 @@ static void add_orco_dm(Object *ob, DerivedMesh *dm, DerivedMesh *orcodm)
static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
DerivedMesh **deform_r, DerivedMesh **final_r,
int useRenderParams, int useDeform,
- int needMapping, CustomDataMask dataMask)
+ int needMapping, CustomDataMask dataMask, int index)
{
Mesh *me = ob->data;
ModifierData *firstmd, *md;
@@ -1880,7 +2108,6 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
float (*deformedVerts)[3] = NULL;
DerivedMesh *dm, *orcodm, *finaldm;
int numVerts = me->totvert;
- int fluidsimMeshUsed = 0;
int required_mode;
md = firstmd = modifiers_getVirtualModifierList(ob);
@@ -1896,22 +2123,6 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
if(deform_r) *deform_r = NULL;
*final_r = NULL;
- /* replace original mesh by fluidsim surface mesh for fluidsim
- * domain objects
- */
- if((G.obedit!=ob) && !needMapping) {
- if((ob->fluidsimFlag & OB_FLUIDSIM_ENABLE) &&
- (1) && (!give_parteff(ob)) ) { // doesnt work together with particle systems!
- if(ob->fluidsimSettings->type & OB_FLUIDSIM_DOMAIN) {
- loadFluidsimMesh(ob,useRenderParams);
- fluidsimMeshUsed = 1;
- /* might have changed... */
- me = ob->data;
- numVerts = me->totvert;
- }
- }
- }
-
if(useRenderParams) required_mode = eModifierMode_Render;
else required_mode = eModifierMode_Realtime;
@@ -1920,7 +2131,7 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
deformedVerts = mesh_getVertexCos(me, &numVerts);
/* Apply all leading deforming modifiers */
- for(; md; md = md->next, curr = curr->next) {
+ for(;md; md = md->next, curr = curr->next) {
ModifierTypeInfo *mti = modifierType_getInfo(md->type);
if((md->mode & required_mode) != required_mode) continue;
@@ -1934,6 +2145,10 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
} else {
break;
}
+
+ /* grab modifiers until index i */
+ if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
+ break;
}
/* Result of all leading deforming modifiers is cached for
@@ -1959,18 +2174,11 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
#endif
}
} else {
- if(!fluidsimMeshUsed) {
- /* default behaviour for meshes */
- if(inputVertexCos)
- deformedVerts = inputVertexCos;
- else
- deformedVerts = mesh_getRefKeyCos(me, &numVerts);
- } else {
- /* the fluid sim mesh might have more vertices than the original
- * one, so inputVertexCos shouldnt be used
- */
- deformedVerts = mesh_getVertexCos(me, &numVerts);
- }
+ /* default behaviour for meshes */
+ if(inputVertexCos)
+ deformedVerts = inputVertexCos;
+ else
+ deformedVerts = mesh_getRefKeyCos(me, &numVerts);
}
@@ -1987,14 +2195,13 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
if(me->vnode) dm = derivedmesh_from_versemesh(me->vnode, deformedVerts);
#endif
- for(; md; md = md->next, curr = curr->next) {
+ for(;md; md = md->next, curr = curr->next) {
ModifierTypeInfo *mti = modifierType_getInfo(md->type);
if((md->mode & required_mode) != required_mode) continue;
if(mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
- modifier_setError(md, "Internal error, modifier requires "
- "original data (bad stack position).");
+ modifier_setError(md, "Modifier requires original data, bad stack position.");
continue;
}
if(mti->isDisabled && mti->isDisabled(md)) continue;
@@ -2004,7 +2211,7 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
if(dm && mti->requiredDataMask) {
mask = mti->requiredDataMask(md);
if(mask & CD_MASK_ORCO)
- add_orco_dm(ob, dm, orcodm);
+ add_orco_dm(ob, NULL, dm, orcodm);
}
/* How to apply modifier depends on (a) what we already have as
@@ -2057,7 +2264,7 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
mask= (CustomDataMask)curr->link;
if(mask & CD_MASK_ORCO) {
if(!orcodm)
- orcodm= create_orco_dm(ob, me);
+ orcodm= create_orco_dm(ob, me, NULL);
mask &= ~CD_MASK_ORCO;
DM_set_only_copy(orcodm, mask);
@@ -2094,6 +2301,10 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
}
}
}
+
+ /* grab modifiers until index i */
+ if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
+ break;
}
for(md=firstmd; md; md=md->next)
@@ -2133,8 +2344,12 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
}
/* add an orco layer if needed */
- if(dataMask & CD_MASK_ORCO)
- add_orco_dm(ob, finaldm, orcodm);
+ if(dataMask & CD_MASK_ORCO) {
+ add_orco_dm(ob, NULL, finaldm, orcodm);
+
+ if(deform_r && *deform_r)
+ add_orco_dm(ob, NULL, *deform_r, NULL);
+ }
*final_r = finaldm;
@@ -2145,9 +2360,6 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3],
MEM_freeN(deformedVerts);
BLI_linklist_free(datamasks, NULL);
-
- /* restore mesh in any case */
- if(fluidsimMeshUsed) ob->data = ob->fluidsimSettings->orgMesh;
}
static float (*editmesh_getVertexCos(EditMesh *em, int *numVerts_r))[3]
@@ -2171,8 +2383,7 @@ static int editmesh_modifier_is_enabled(ModifierData *md, DerivedMesh *dm)
if((md->mode & required_mode) != required_mode) return 0;
if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
- modifier_setError(md, "Internal error, modifier requires"
- "original data (bad stack position).");
+ modifier_setError(md, "Modifier requires original data, bad stack position.");
return 0;
}
if(mti->isDisabled && mti->isDisabled(md)) return 0;
@@ -2190,7 +2401,8 @@ static void editmesh_calc_modifiers(DerivedMesh **cage_r,
EditMesh *em = G.editMesh;
ModifierData *md;
float (*deformedVerts)[3] = NULL;
- DerivedMesh *dm;
+ CustomDataMask mask;
+ DerivedMesh *dm, *orcodm = NULL;
int i, numVerts = 0, cageIndex = modifiers_getCageIndex(ob, NULL);
LinkNode *datamasks, *curr;
@@ -2215,6 +2427,13 @@ static void editmesh_calc_modifiers(DerivedMesh **cage_r,
if(!editmesh_modifier_is_enabled(md, dm))
continue;
+ /* add an orco layer if needed by this modifier */
+ if(dm && mti->requiredDataMask) {
+ mask = mti->requiredDataMask(md);
+ if(mask & CD_MASK_ORCO)
+ add_orco_dm(ob, em, dm, orcodm);
+ }
+
/* How to apply modifier depends on (a) what we already have as
* a result of previous modifiers (could be a DerivedMesh or just
* deformed vertices) and (b) what type the modifier is.
@@ -2265,6 +2484,23 @@ static void editmesh_calc_modifiers(DerivedMesh **cage_r,
}
}
+ /* create an orco derivedmesh in parallel */
+ mask= (CustomDataMask)curr->link;
+ if(mask & CD_MASK_ORCO) {
+ if(!orcodm)
+ orcodm= create_orco_dm(ob, ob->data, em);
+
+ mask &= ~CD_MASK_ORCO;
+ DM_set_only_copy(orcodm, mask);
+ ndm = mti->applyModifierEM(md, ob, em, orcodm);
+
+ if(ndm) {
+ /* if the modifier returned a new dm, release the old one */
+ if(orcodm && orcodm != ndm) orcodm->release(orcodm);
+ orcodm = ndm;
+ }
+ }
+
/* set the DerivedMesh to only copy needed data */
DM_set_only_copy(dm, (CustomDataMask)curr->link);
@@ -2323,6 +2559,13 @@ static void editmesh_calc_modifiers(DerivedMesh **cage_r,
deformedVerts = NULL;
}
+ /* add an orco layer if needed */
+ if(dataMask & CD_MASK_ORCO)
+ add_orco_dm(ob, em, *final_r, orcodm);
+
+ if(orcodm)
+ orcodm->release(orcodm);
+
if(deformedVerts)
MEM_freeN(deformedVerts);
}
@@ -2460,21 +2703,26 @@ static void mesh_build_data(Object *ob, CustomDataMask dataMask)
if( (G.f & G_WEIGHTPAINT) && ob==obact ) {
MCol *wpcol = (MCol*)calc_weightpaint_colors(ob);
int layernum = CustomData_number_of_layers(&me->fdata, CD_MCOL);
+ int prevactive = CustomData_get_active_layer(&me->fdata, CD_MCOL);
+ int prevrender = CustomData_get_render_layer(&me->fdata, CD_MCOL);
/* ugly hack here, we temporarily add a new active mcol layer with
weightpaint colors in it, that is then duplicated in CDDM_from_mesh */
CustomData_add_layer(&me->fdata, CD_MCOL, CD_ASSIGN, wpcol, me->totface);
CustomData_set_layer_active(&me->fdata, CD_MCOL, layernum);
+ CustomData_set_layer_render(&me->fdata, CD_MCOL, layernum);
mesh_calc_modifiers(ob, NULL, &ob->derivedDeform,
&ob->derivedFinal, 0, 1,
- needMapping, dataMask);
+ needMapping, dataMask, -1);
CustomData_free_layer_active(&me->fdata, CD_MCOL, me->totface);
+ CustomData_set_layer_active(&me->fdata, CD_MCOL, prevactive);
+ CustomData_set_layer_render(&me->fdata, CD_MCOL, prevrender);
} else {
mesh_calc_modifiers(ob, NULL, &ob->derivedDeform,
- &ob->derivedFinal, 0, 1,
- needMapping, dataMask);
+ &ob->derivedFinal, G.rendering, 1,
+ needMapping, dataMask, -1);
}
INIT_MINMAX(min, max);
@@ -2532,14 +2780,7 @@ void makeDerivedMesh(Object *ob, CustomDataMask dataMask)
if (ob==G.obedit) {
editmesh_build_data(dataMask);
} else {
- PartEff *paf= give_parteff(ob);
-
mesh_build_data(ob, dataMask);
-
- if(paf) {
- if((paf->flag & PAF_STATIC) || (ob->recalc & OB_RECALC_TIME)==0)
- build_particle_system(ob);
- }
}
}
@@ -2572,7 +2813,7 @@ float *multires_render_pin(Object *ob, Mesh *me, int *orig_lvl)
{
float *vert_copy= NULL;
- if(me->mr) {
+ if(me->mr && !(me->mr->flag & MULTIRES_NO_RENDER)) {
MultiresLevel *lvl= NULL;
int i;
@@ -2598,16 +2839,22 @@ float *multires_render_pin(Object *ob, Mesh *me, int *orig_lvl)
void multires_render_final(Object *ob, Mesh *me, DerivedMesh **dm, float *vert_copy,
const int orig_lvl, CustomDataMask dataMask)
{
- if(me->mr) {
+ if(me->mr && !(me->mr->flag & MULTIRES_NO_RENDER)) {
if((*dm)->getNumVerts(*dm) == me->totvert &&
(*dm)->getNumFaces(*dm) == me->totface) {
//XXX MultiresLevel *lvl= multires_level_n(me->mr, BLI_countlist(&me->mr->levels));
DerivedMesh *old= NULL;
+ MVert *vertdup= NULL;
int i;
- (*dm)->copyVertArray(*dm, me->mvert);
+ /* Copy the verts into the mesh */
+ vertdup= (*dm)->dupVertArray(*dm);
(*dm)->release(*dm);
-
+ for(i=0; i<me->totvert; ++i)
+ me->mvert[i]= vertdup[i];
+ /* Free vertdup after use*/
+ MEM_freeN(vertdup);
+ /* Go to the render level */
me->mr->newlvl= me->mr->renderlvl;
//XXX multires_set_level(ob, me, 1);
(*dm)= getMeshDerivedMesh(me, ob, NULL);
@@ -2618,7 +2865,7 @@ void multires_render_final(Object *ob, Mesh *me, DerivedMesh **dm, float *vert_c
old->release(old);
if(dataMask & CD_MASK_ORCO)
- add_orco_dm(ob, *dm, NULL);
+ add_orco_dm(ob, NULL, *dm, NULL);
/* Restore the original verts */
me->mr->newlvl= BLI_countlist(&me->mr->levels);
@@ -2646,7 +2893,21 @@ DerivedMesh *mesh_create_derived_render(Object *ob, CustomDataMask dataMask)
int orig_lvl= 0;
vert_copy= multires_render_pin(ob, me, &orig_lvl);
- mesh_calc_modifiers(ob, NULL, NULL, &final, 1, 1, 0, dataMask);
+ mesh_calc_modifiers(ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1);
+ multires_render_final(ob, me, &final, vert_copy, orig_lvl, dataMask);
+
+ return final;
+}
+
+DerivedMesh *mesh_create_derived_index_render(Object *ob, CustomDataMask dataMask, int index)
+{
+ DerivedMesh *final;
+ Mesh *me= get_mesh(ob);
+ float *vert_copy= NULL;
+ int orig_lvl= 0;
+
+ vert_copy= multires_render_pin(ob, me, &orig_lvl);
+ mesh_calc_modifiers(ob, NULL, NULL, &final, 1, 1, 0, dataMask, index);
multires_render_final(ob, me, &final, vert_copy, orig_lvl, dataMask);
return final;
@@ -2656,7 +2917,7 @@ DerivedMesh *mesh_create_derived_view(Object *ob, CustomDataMask dataMask)
{
DerivedMesh *final;
- mesh_calc_modifiers(ob, NULL, NULL, &final, 0, 1, 0, dataMask);
+ mesh_calc_modifiers(ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1);
return final;
}
@@ -2666,7 +2927,7 @@ DerivedMesh *mesh_create_derived_no_deform(Object *ob, float (*vertCos)[3],
{
DerivedMesh *final;
- mesh_calc_modifiers(ob, vertCos, NULL, &final, 0, 0, 0, dataMask);
+ mesh_calc_modifiers(ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1);
return final;
}
@@ -2681,7 +2942,7 @@ DerivedMesh *mesh_create_derived_no_deform_render(Object *ob,
int orig_lvl= 0;
vert_copy= multires_render_pin(ob, me, &orig_lvl);
- mesh_calc_modifiers(ob, vertCos, NULL, &final, 1, 0, 0, dataMask);
+ mesh_calc_modifiers(ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1);
multires_render_final(ob, me, &final, vert_copy, orig_lvl, dataMask);
return final;
@@ -2833,580 +3094,211 @@ int editmesh_get_first_deform_matrices(float (**deformmats)[3][3], float (**defo
return numleft;
}
-/* ************************* fluidsim bobj file handling **************************** */
-
-#ifndef DISABLE_ELBEEM
-
-#ifdef WIN32
-#ifndef snprintf
-#define snprintf _snprintf
-#endif
-#endif
+/* ******************* GLSL ******************** */
-/* write .bobj.gz file for a mesh object */
-void writeBobjgz(char *filename, struct Object *ob, int useGlobalCoords, int append, float time)
+void DM_add_tangent_layer(DerivedMesh *dm)
{
- char debugStrBuffer[256];
- int wri,i,j,totvert,totface;
- float wrf;
- gzFile gzf;
- DerivedMesh *dm;
- float vec[3];
- float rotmat[3][3];
- MVert *mvert;
- MFace *mface;
- //if(append)return; // DEBUG
-
- if(!ob->data || (ob->type!=OB_MESH)) {
- snprintf(debugStrBuffer,256,"Writing GZ_BOBJ Invalid object %s ...\n", ob->id.name);
- elbeemDebugOut(debugStrBuffer);
- return;
- }
- if((ob->size[0]<0.0) || (ob->size[0]<0.0) || (ob->size[0]<0.0) ) {
- snprintf(debugStrBuffer,256,"\nfluidSim::writeBobjgz:: Warning object %s has negative scaling - check triangle ordering...?\n\n", ob->id.name);
- elbeemDebugOut(debugStrBuffer);
- }
+ /* mesh vars */
+ MTFace *mtface, *tf;
+ MFace *mface, *mf;
+ MVert *mvert, *v1, *v2, *v3, *v4;
+ MemArena *arena= NULL;
+ VertexTangent **vtangents= NULL;
+ float (*orco)[3]= NULL, (*tangent)[3];
+ float *uv1, *uv2, *uv3, *uv4, *vtang;
+ float fno[3], tang[3], uv[4][2];
+ int i, j, len, mf_vi[4], totvert, totface;
- snprintf(debugStrBuffer,256,"Writing GZ_BOBJ '%s' ... ",filename); elbeemDebugOut(debugStrBuffer);
- if(append) gzf = gzopen(filename, "a+b9");
- else gzf = gzopen(filename, "wb9");
- if (!gzf) {
- snprintf(debugStrBuffer,256,"writeBobjgz::error - Unable to open file for writing '%s'\n", filename);
- elbeemDebugOut(debugStrBuffer);
+ if(CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
return;
- }
- dm = mesh_create_derived_render(ob, CD_MASK_BAREMESH);
- //dm = mesh_create_derived_no_deform(ob,NULL);
+ /* check we have all the needed layers */
+ totvert= dm->getNumVerts(dm);
+ totface= dm->getNumFaces(dm);
- mvert = dm->getVertArray(dm);
- mface = dm->getFaceArray(dm);
- totvert = dm->getNumVerts(dm);
- totface = dm->getNumFaces(dm);
+ mvert= dm->getVertArray(dm);
+ mface= dm->getFaceArray(dm);
+ mtface= dm->getFaceDataArray(dm, CD_MTFACE);
- // write time value for appended anim mesh
- if(append) {
- gzwrite(gzf, &time, sizeof(time));
+ if(!mtface) {
+ orco= dm->getVertDataArray(dm, CD_ORCO);
+ if(!orco)
+ return;
}
-
- // continue with verts/norms
- if(sizeof(wri)!=4) { snprintf(debugStrBuffer,256,"Writing GZ_BOBJ, Invalid int size %d...\n", wri); elbeemDebugOut(debugStrBuffer); return; } // paranoia check
- wri = dm->getNumVerts(dm);
- mvert = dm->getVertArray(dm);
- gzwrite(gzf, &wri, sizeof(wri));
- for(i=0; i<wri;i++) {
- VECCOPY(vec, mvert[i].co);
- if(useGlobalCoords) { Mat4MulVecfl(ob->obmat, vec); }
- for(j=0; j<3; j++) {
- wrf = vec[j];
- gzwrite(gzf, &wrf, sizeof( wrf ));
+
+ /* create tangent layer */
+ DM_add_face_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
+ tangent= DM_get_face_data_layer(dm, CD_TANGENT);
+
+ /* allocate some space */
+ arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
+ BLI_memarena_use_calloc(arena);
+ vtangents= MEM_callocN(sizeof(VertexTangent*)*totvert, "VertexTangent");
+
+ /* sum tangents at connected vertices */
+ for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++) {
+ v1= &mvert[mf->v1];
+ v2= &mvert[mf->v2];
+ v3= &mvert[mf->v3];
+
+ if (mf->v4) {
+ v4= &mvert[mf->v4];
+ CalcNormFloat4(v4->co, v3->co, v2->co, v1->co, fno);
}
- }
-
- // should be the same as Vertices.size
- wri = totvert;
- gzwrite(gzf, &wri, sizeof(wri));
- EulToMat3(ob->rot, rotmat);
- for(i=0; i<wri;i++) {
- VECCOPY(vec, mvert[i].no);
- Normalize(vec);
- if(useGlobalCoords) { Mat3MulVecfl(rotmat, vec); }
- for(j=0; j<3; j++) {
- wrf = vec[j];
- gzwrite(gzf, &wrf, sizeof( wrf ));
+ else {
+ v4= NULL;
+ CalcNormFloat(v3->co, v2->co, v1->co, fno);
}
- }
-
- // append only writes verts&norms
- if(!append) {
- //float side1[3],side2[3],norm1[3],norm2[3];
- //float inpf;
-
- // compute no. of triangles
- wri = 0;
- for(i=0; i<totface; i++) {
- wri++;
- if(mface[i].v4) { wri++; }
+
+ if(mtface) {
+ uv1= tf->uv[0];
+ uv2= tf->uv[1];
+ uv3= tf->uv[2];
+ uv4= tf->uv[3];
}
- gzwrite(gzf, &wri, sizeof(wri));
- for(i=0; i<totface; i++) {
-
- int face[4];
- face[0] = mface[i].v1;
- face[1] = mface[i].v2;
- face[2] = mface[i].v3;
- face[3] = mface[i].v4;
- //snprintf(debugStrBuffer,256,"F %s %d = %d,%d,%d,%d \n",ob->id.name, i, face[0],face[1],face[2],face[3] ); elbeemDebugOut(debugStrBuffer);
- //VecSubf(side1, mvert[face[1]].co,mvert[face[0]].co);
- //VecSubf(side2, mvert[face[2]].co,mvert[face[0]].co);
- //Crossf(norm1,side1,side2);
- gzwrite(gzf, &(face[0]), sizeof( face[0] ));
- gzwrite(gzf, &(face[1]), sizeof( face[1] ));
- gzwrite(gzf, &(face[2]), sizeof( face[2] ));
- if(face[3]) {
- //VecSubf(side1, mvert[face[2]].co,mvert[face[0]].co);
- //VecSubf(side2, mvert[face[3]].co,mvert[face[0]].co);
- //Crossf(norm2,side1,side2);
- //inpf = Inpf(norm1,norm2);
- //if(inpf>0.) {
- gzwrite(gzf, &(face[0]), sizeof( face[0] ));
- gzwrite(gzf, &(face[2]), sizeof( face[2] ));
- gzwrite(gzf, &(face[3]), sizeof( face[3] ));
- //} else {
- //gzwrite(gzf, &(face[0]), sizeof( face[0] ));
- //gzwrite(gzf, &(face[3]), sizeof( face[3] ));
- //gzwrite(gzf, &(face[2]), sizeof( face[2] ));
- //}
- } // quad
+ else {
+ uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
+ spheremap(orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2], &uv[0][0], &uv[0][1]);
+ spheremap(orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2], &uv[1][0], &uv[1][1]);
+ spheremap(orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2], &uv[2][0], &uv[2][1]);
+ if(v4)
+ spheremap(orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2], &uv[3][0], &uv[3][1]);
}
- }
-
- snprintf(debugStrBuffer,256,"Done. #Vertices: %d, #Triangles: %d\n", totvert, totface );
- elbeemDebugOut(debugStrBuffer);
-
- gzclose( gzf );
- dm->release(dm);
-}
-
-void initElbeemMesh(struct Object *ob,
- int *numVertices, float **vertices,
- int *numTriangles, int **triangles,
- int useGlobalCoords)
-{
- DerivedMesh *dm = NULL;
- MVert *mvert;
- MFace *mface;
- int countTris=0, i, totvert, totface;
- float *verts;
- int *tris;
-
- dm = mesh_create_derived_render(ob, CD_MASK_BAREMESH);
- //dm = mesh_create_derived_no_deform(ob,NULL);
-
- mvert = dm->getVertArray(dm);
- mface = dm->getFaceArray(dm);
- totvert = dm->getNumVerts(dm);
- totface = dm->getNumFaces(dm);
-
- *numVertices = totvert;
- verts = MEM_callocN( totvert*3*sizeof(float), "elbeemmesh_vertices");
- for(i=0; i<totvert; i++) {
- VECCOPY( &verts[i*3], mvert[i].co);
- if(useGlobalCoords) { Mat4MulVecfl(ob->obmat, &verts[i*3]); }
- }
- *vertices = verts;
-
- for(i=0; i<totface; i++) {
- countTris++;
- if(mface[i].v4) { countTris++; }
- }
- *numTriangles = countTris;
- tris = MEM_callocN( countTris*3*sizeof(int), "elbeemmesh_triangles");
- countTris = 0;
- for(i=0; i<totface; i++) {
- int face[4];
- face[0] = mface[i].v1;
- face[1] = mface[i].v2;
- face[2] = mface[i].v3;
- face[3] = mface[i].v4;
-
- tris[countTris*3+0] = face[0];
- tris[countTris*3+1] = face[1];
- tris[countTris*3+2] = face[2];
- countTris++;
- if(face[3]) {
- tris[countTris*3+0] = face[0];
- tris[countTris*3+1] = face[2];
- tris[countTris*3+2] = face[3];
- countTris++;
+
+ tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang);
+ sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
+ sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2);
+ sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
+
+ if(mf->v4) {
+ v4= &mvert[mf->v4];
+
+ tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, fno, tang);
+ sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
+ sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
+ sum_or_add_vertex_tangent(arena, &vtangents[mf->v4], tang, uv4);
}
}
- *triangles = tris;
-
- dm->release(dm);
-}
-
-/* read .bobj.gz file into a fluidsimDerivedMesh struct */
-Mesh* readBobjgz(char *filename, Mesh *orgmesh, float* bbstart, float *bbsize) //, fluidsimDerivedMesh *fsdm)
-{
- int wri,i,j;
- char debugStrBuffer[256];
- float wrf;
- Mesh *newmesh;
- const int debugBobjRead = 1;
- // init data from old mesh (materials,flags)
- MFace *origMFace = &((MFace*) orgmesh->mface)[0];
- int mat_nr = -1;
- int flag = -1;
- MFace *fsface = NULL;
- int gotBytes;
- gzFile gzf;
-
- if(!orgmesh) return NULL;
- if(!origMFace) return NULL;
- mat_nr = origMFace->mat_nr;
- flag = origMFace->flag;
-
- // similar to copy_mesh
- newmesh = MEM_dupallocN(orgmesh);
- newmesh->mat= orgmesh->mat;
-
- newmesh->mvert= NULL;
- newmesh->medge= NULL;
- newmesh->mface= NULL;
- newmesh->mtface= NULL;
-
- newmesh->dvert = NULL;
-
- newmesh->mcol= NULL;
- newmesh->msticky= NULL;
- newmesh->texcomesh= NULL;
- memset(&newmesh->vdata, 0, sizeof(newmesh->vdata));
- memset(&newmesh->edata, 0, sizeof(newmesh->edata));
- memset(&newmesh->fdata, 0, sizeof(newmesh->fdata));
-
- newmesh->key= NULL;
- newmesh->totface = 0;
- newmesh->totvert = 0;
- newmesh->totedge = 0;
- newmesh->medge = NULL;
-
-
- snprintf(debugStrBuffer,256,"Reading '%s' GZ_BOBJ... ",filename); elbeemDebugOut(debugStrBuffer);
- gzf = gzopen(filename, "rb");
- // gzf = fopen(filename, "rb");
- // debug: fread(b,c,1,a) = gzread(a,b,c)
- if (!gzf) {
- //snprintf(debugStrBuffer,256,"readBobjgz::error - Unable to open file for reading '%s'\n", filename); // DEBUG
- MEM_freeN(newmesh);
- return NULL;
- }
-
- //if(sizeof(wri)!=4) { snprintf(debugStrBuffer,256,"Reading GZ_BOBJ, Invalid int size %d...\n", wri); return NULL; } // paranoia check
- gotBytes = gzread(gzf, &wri, sizeof(wri));
- newmesh->totvert = wri;
- newmesh->mvert = CustomData_add_layer(&newmesh->vdata, CD_MVERT, CD_CALLOC, NULL, newmesh->totvert);
- if(debugBobjRead){ snprintf(debugStrBuffer,256,"#vertices %d ", newmesh->totvert); elbeemDebugOut(debugStrBuffer); } //DEBUG
- for(i=0; i<newmesh->totvert;i++) {
- //if(debugBobjRead) snprintf(debugStrBuffer,256,"V %d = ",i);
- for(j=0; j<3; j++) {
- gotBytes = gzread(gzf, &wrf, sizeof( wrf ));
- newmesh->mvert[i].co[j] = wrf;
- //if(debugBobjRead) snprintf(debugStrBuffer,256,"%25.20f ", wrf);
+
+ /* write tangent to layer */
+ for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++, tangent+=4) {
+ len= (mf->v4)? 4 : 3;
+
+ if(mtface) {
+ uv1= tf->uv[0];
+ uv2= tf->uv[1];
+ uv3= tf->uv[2];
+ uv4= tf->uv[3];
}
- //if(debugBobjRead) snprintf(debugStrBuffer,256,"\n");
- }
-
- // should be the same as Vertices.size
- gotBytes = gzread(gzf, &wri, sizeof(wri));
- if(wri != newmesh->totvert) {
- // complain #vertices has to be equal to #normals, reset&abort
- CustomData_free_layer_active(&newmesh->vdata, CD_MVERT, newmesh->totvert);
- MEM_freeN(newmesh);
- snprintf(debugStrBuffer,256,"Reading GZ_BOBJ, #normals=%d, #vertices=%d, aborting...\n", wri,newmesh->totvert );
- return NULL;
- }
- for(i=0; i<newmesh->totvert;i++) {
- for(j=0; j<3; j++) {
- gotBytes = gzread(gzf, &wrf, sizeof( wrf ));
- newmesh->mvert[i].no[j] = (short)(wrf*32767.0f);
- //newmesh->mvert[i].no[j] = 0.5; // DEBUG tst
+ else {
+ uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
+ spheremap(orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2], &uv[0][0], &uv[0][1]);
+ spheremap(orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2], &uv[1][0], &uv[1][1]);
+ spheremap(orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2], &uv[2][0], &uv[2][1]);
+ if(len==4)
+ spheremap(orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2], &uv[3][0], &uv[3][1]);
}
- //fprintf(stderr," DEBDPCN nm%d, %d = %d,%d,%d \n",
- //(int)(newmesh->mvert), i, newmesh->mvert[i].no[0], newmesh->mvert[i].no[1], newmesh->mvert[i].no[2]);
- }
- //fprintf(stderr," DPCN 0 = %d,%d,%d \n", newmesh->mvert[0].no[0], newmesh->mvert[0].no[1], newmesh->mvert[0].no[2]);
+
+ mf_vi[0]= mf->v1;
+ mf_vi[1]= mf->v2;
+ mf_vi[2]= mf->v3;
+ mf_vi[3]= mf->v4;
+
+ for(j=0; j<len; j++) {
+ vtang= find_vertex_tangent(vtangents[mf_vi[j]], mtface ? tf->uv[j] : uv[j]);
-
- /* compute no. of triangles */
- gotBytes = gzread(gzf, &wri, sizeof(wri));
- newmesh->totface = wri;
- newmesh->mface = CustomData_add_layer(&newmesh->fdata, CD_MFACE, CD_CALLOC, NULL, newmesh->totface);
- if(debugBobjRead){ snprintf(debugStrBuffer,256,"#faces %d ", newmesh->totface); elbeemDebugOut(debugStrBuffer); } //DEBUG
- fsface = newmesh->mface;
- for(i=0; i<newmesh->totface; i++) {
- int face[4];
-
- gotBytes = gzread(gzf, &(face[0]), sizeof( face[0] ));
- gotBytes = gzread(gzf, &(face[1]), sizeof( face[1] ));
- gotBytes = gzread(gzf, &(face[2]), sizeof( face[2] ));
- face[3] = 0;
-
- fsface[i].v1 = face[0];
- fsface[i].v2 = face[1];
- fsface[i].v3 = face[2];
- fsface[i].v4 = face[3];
- }
-
- // correct triangles with v3==0 for blender, cycle verts
- for(i=0; i<newmesh->totface; i++) {
- if(!fsface[i].v3) {
- int temp = fsface[i].v1;
- fsface[i].v1 = fsface[i].v2;
- fsface[i].v2 = fsface[i].v3;
- fsface[i].v3 = temp;
+ VECCOPY(tangent[j], vtang);
+ Normalize(tangent[j]);
}
}
- gzclose( gzf );
- for(i=0;i<newmesh->totface;i++) {
- fsface[i].mat_nr = mat_nr;
- fsface[i].flag = flag;
- fsface[i].edcode = ME_V1V2 | ME_V2V3 | ME_V3V1;
- //snprintf(debugStrBuffer,256,"%d : %d,%d,%d\n", i,fsface[i].mat_nr, fsface[i].flag, fsface[i].edcode );
- }
-
- snprintf(debugStrBuffer,256," (%d,%d) done\n", newmesh->totvert,newmesh->totface); elbeemDebugOut(debugStrBuffer); //DEBUG
- return newmesh;
-}
-
-/* read zipped fluidsim velocities into the co's of the fluidsimsettings normals struct */
-void readVelgz(char *filename, Object *srcob)
-{
- char debugStrBuffer[256];
- int wri, i, j;
- float wrf;
- gzFile gzf;
- MVert *vverts = srcob->fluidsimSettings->meshSurfNormals;
- int len = strlen(filename);
- Mesh *mesh = srcob->data;
- // mesh and vverts have to be valid from loading...
-
- // clean up in any case
- for(i=0; i<mesh->totvert;i++) {
- for(j=0; j<3; j++) {
- vverts[i].co[j] = 0.;
- }
- }
- if(srcob->fluidsimSettings->domainNovecgen>0) return;
-
- if(len<7) {
- //printf("readVelgz Eror: invalid filename '%s'\n",filename); // DEBUG
- return;
- }
-
- // .bobj.gz , correct filename
- // 87654321
- filename[len-6] = 'v';
- filename[len-5] = 'e';
- filename[len-4] = 'l';
-
- snprintf(debugStrBuffer,256,"Reading '%s' GZ_VEL... ",filename); elbeemDebugOut(debugStrBuffer);
- gzf = gzopen(filename, "rb");
- if (!gzf) {
- //printf("readVelgz Eror: unable to open file '%s'\n",filename); // DEBUG
- return;
- }
-
- gzread(gzf, &wri, sizeof( wri ));
- if(wri != mesh->totvert) {
- //printf("readVelgz Eror: invalid no. of velocities %d vs. %d aborting.\n" ,wri ,mesh->totvert ); // DEBUG
- return;
- }
-
- for(i=0; i<mesh->totvert;i++) {
- for(j=0; j<3; j++) {
- gzread(gzf, &wrf, sizeof( wrf ));
- vverts[i].co[j] = wrf;
- }
- //if(i<20) fprintf(stderr, "GZ_VELload %d = %f,%f,%f \n",i,vverts[i].co[0],vverts[i].co[1],vverts[i].co[2]); // DEBUG
- }
-
- gzclose(gzf);
+ BLI_memarena_free(arena);
+ MEM_freeN(vtangents);
}
-
-/* ***************************** fluidsim derived mesh ***************************** */
-
-/* check which file to load, and replace old mesh of the object with it */
-/* this replacement is undone at the end of mesh_calc_modifiers */
-void loadFluidsimMesh(Object *srcob, int useRenderParams)
+void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
{
- Mesh *mesh = NULL;
- float *bbStart = NULL, *bbSize = NULL;
- float lastBB[3];
- int displaymode = 0;
- int curFrame = G.scene->r.cfra - 1 /*G.scene->r.sfra*/; /* start with 0 at start frame */
- char targetDir[FILE_MAXFILE+FILE_MAXDIR], targetFile[FILE_MAXFILE+FILE_MAXDIR];
- char debugStrBuffer[256];
- //snprintf(debugStrBuffer,256,"loadFluidsimMesh call (obid '%s', rp %d)\n", srcob->id.name, useRenderParams); // debug
+ CustomData *vdata, *fdata, *tfdata = NULL;
+ int a, b, layer;
- if((!srcob)||(!srcob->fluidsimSettings)) {
- snprintf(debugStrBuffer,256,"DEBUG - Invalid loadFluidsimMesh call, rp %d, dm %d)\n", useRenderParams, displaymode); // debug
- elbeemDebugOut(debugStrBuffer); // debug
- return;
- }
- // make sure the original mesh data pointer is stored
- if(!srcob->fluidsimSettings->orgMesh) {
- srcob->fluidsimSettings->orgMesh = srcob->data;
- }
+ /* From the layers requested by the GLSL shader, figure out which ones are
+ * actually available for this derivedmesh, and retrieve the pointers */
- // free old mesh, if there is one (todo, check if it's still valid?)
- if(srcob->fluidsimSettings->meshSurface) {
- Mesh *freeFsMesh = srcob->fluidsimSettings->meshSurface;
+ memset(attribs, 0, sizeof(DMVertexAttribs));
- // similar to free_mesh(...) , but no things like unlink...
- CustomData_free(&freeFsMesh->vdata, freeFsMesh->totvert);
- CustomData_free(&freeFsMesh->edata, freeFsMesh->totedge);
- CustomData_free(&freeFsMesh->fdata, freeFsMesh->totface);
- MEM_freeN(freeFsMesh);
-
- if(srcob->data == srcob->fluidsimSettings->meshSurface)
- srcob->data = srcob->fluidsimSettings->orgMesh;
- srcob->fluidsimSettings->meshSurface = NULL;
-
- if(srcob->fluidsimSettings->meshSurfNormals) MEM_freeN(srcob->fluidsimSettings->meshSurfNormals);
- srcob->fluidsimSettings->meshSurfNormals = NULL;
- }
-
- // init bounding box
- bbStart = srcob->fluidsimSettings->bbStart;
- bbSize = srcob->fluidsimSettings->bbSize;
- lastBB[0] = bbSize[0]; // TEST
- lastBB[1] = bbSize[1];
- lastBB[2] = bbSize[2];
- fluidsimGetAxisAlignedBB(srcob->fluidsimSettings->orgMesh, srcob->obmat, bbStart, bbSize, &srcob->fluidsimSettings->meshBB);
- // check free fsmesh... TODO
-
- if(!useRenderParams) {
- displaymode = srcob->fluidsimSettings->guiDisplayMode;
- } else {
- displaymode = srcob->fluidsimSettings->renderDisplayMode;
- }
-
- snprintf(debugStrBuffer,256,"loadFluidsimMesh call (obid '%s', rp %d, dm %d), curFra=%d, sFra=%d #=%d \n",
- srcob->id.name, useRenderParams, displaymode, G.scene->r.cfra, G.scene->r.sfra, curFrame ); // debug
- elbeemDebugOut(debugStrBuffer); // debug
-
- strncpy(targetDir, srcob->fluidsimSettings->surfdataPath, FILE_MAXDIR);
- // use preview or final mesh?
- if(displaymode==1) {
- // just display original object
- srcob->data = srcob->fluidsimSettings->orgMesh;
- return;
- } else if(displaymode==2) {
- strcat(targetDir,"fluidsurface_preview_#");
- } else { // 3
- strcat(targetDir,"fluidsurface_final_#");
- }
- BLI_convertstringcode(targetDir, G.sce, curFrame); // fixed #frame-no
- strcpy(targetFile,targetDir);
- strcat(targetFile, ".bobj.gz");
+ vdata = &dm->vertData;
+ fdata = &dm->faceData;
- snprintf(debugStrBuffer,256,"loadFluidsimMesh call (obid '%s', rp %d, dm %d) '%s' \n", srcob->id.name, useRenderParams, displaymode, targetFile); // debug
- elbeemDebugOut(debugStrBuffer); // debug
+ /* ugly hack, editmesh derivedmesh doesn't copy face data, this way we
+ * can use offsets instead */
+ if(dm->release == emDM_release)
+ tfdata = &((EditMeshDerivedMesh*)dm)->em->fdata;
+ else
+ tfdata = fdata;
+
+ /* add a tangent layer if necessary */
+ for(b = 0; b < gattribs->totlayer; b++)
+ if(gattribs->layer[b].type == CD_TANGENT)
+ if(CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
+ DM_add_tangent_layer(dm);
+
+ for(b = 0; b < gattribs->totlayer; b++) {
+ if(gattribs->layer[b].type == CD_MTFACE) {
+ /* uv coordinates */
+ if(gattribs->layer[b].name[0])
+ layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
+ gattribs->layer[b].name);
+ else
+ layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
- if(displaymode!=2) { // dont add bounding box for final
- mesh = readBobjgz(targetFile, srcob->fluidsimSettings->orgMesh ,NULL,NULL);
- } else {
- mesh = readBobjgz(targetFile, srcob->fluidsimSettings->orgMesh, bbSize,bbSize );
- }
- if(!mesh) {
- // switch, abort background rendering when fluidsim mesh is missing
- const char *strEnvName2 = "BLENDER_ELBEEMBOBJABORT"; // from blendercall.cpp
- if(G.background==1) {
- if(getenv(strEnvName2)) {
- int elevel = atoi(getenv(strEnvName2));
- if(elevel>0) {
- printf("Env. var %s set, fluid sim mesh '%s' not found, aborting render...\n",strEnvName2, targetFile);
- exit(1);
- }
+ if(layer != -1) {
+ a = attribs->tottface++;
+
+ attribs->tface[a].array = tfdata->layers[layer].data;
+ attribs->tface[a].emOffset = tfdata->layers[layer].offset;
+ attribs->tface[a].glIndex = gattribs->layer[b].glindex;
}
}
-
- // display org. object upon failure
- srcob->data = srcob->fluidsimSettings->orgMesh;
- return;
- }
+ else if(gattribs->layer[b].type == CD_MCOL) {
+ /* vertex colors */
+ if(gattribs->layer[b].name[0])
+ layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
+ gattribs->layer[b].name);
+ else
+ layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
- if((mesh)&&(mesh->totvert>0)) {
- make_edges(mesh, 0); // 0 = make all edges draw
- }
- srcob->fluidsimSettings->meshSurface = mesh;
- srcob->data = mesh;
- srcob->fluidsimSettings->meshSurfNormals = MEM_dupallocN(mesh->mvert);
+ if(layer != -1) {
+ a = attribs->totmcol++;
- // load vertex velocities, if they exist...
- // TODO? use generate flag as loading flag as well?
- // warning, needs original .bobj.gz mesh loading filename
- if(displaymode==3) {
- readVelgz(targetFile, srcob);
- } else {
- // no data for preview, only clear...
- int i,j;
- for(i=0; i<mesh->totvert;i++) { for(j=0; j<3; j++) { srcob->fluidsimSettings->meshSurfNormals[i].co[j] = 0.; }}
- }
+ attribs->mcol[a].array = tfdata->layers[layer].data;
+ attribs->mcol[a].emOffset = tfdata->layers[layer].offset;
+ attribs->mcol[a].glIndex = gattribs->layer[b].glindex;
+ }
+ }
+ else if(gattribs->layer[b].type == CD_TANGENT) {
+ /* tangents */
+ layer = CustomData_get_layer_index(fdata, CD_TANGENT);
- //fprintf(stderr,"LOADFLM DEBXHCH fs=%d 3:%d,%d,%d \n", (int)mesh, ((Mesh *)(srcob->fluidsimSettings->meshSurface))->mvert[3].no[0], ((Mesh *)(srcob->fluidsimSettings->meshSurface))->mvert[3].no[1], ((Mesh *)(srcob->fluidsimSettings->meshSurface))->mvert[3].no[2]);
- return;
-}
+ if(layer != -1) {
+ attribs->tottang = 1;
-/* helper function */
-/* init axis aligned BB for mesh object */
-void fluidsimGetAxisAlignedBB(struct Mesh *mesh, float obmat[][4],
- /*RET*/ float start[3], /*RET*/ float size[3], /*RET*/ struct Mesh **bbmesh )
-{
- float bbsx=0.0, bbsy=0.0, bbsz=0.0;
- float bbex=1.0, bbey=1.0, bbez=1.0;
- int i;
- float vec[3];
-
- VECCOPY(vec, mesh->mvert[0].co);
- Mat4MulVecfl(obmat, vec);
- bbsx = vec[0]; bbsy = vec[1]; bbsz = vec[2];
- bbex = vec[0]; bbey = vec[1]; bbez = vec[2];
-
- for(i=1; i<mesh->totvert;i++) {
- VECCOPY(vec, mesh->mvert[i].co);
- Mat4MulVecfl(obmat, vec);
-
- if(vec[0] < bbsx){ bbsx= vec[0]; }
- if(vec[1] < bbsy){ bbsy= vec[1]; }
- if(vec[2] < bbsz){ bbsz= vec[2]; }
- if(vec[0] > bbex){ bbex= vec[0]; }
- if(vec[1] > bbey){ bbey= vec[1]; }
- if(vec[2] > bbez){ bbez= vec[2]; }
- }
-
- // return values...
- if(start) {
- start[0] = bbsx;
- start[1] = bbsy;
- start[2] = bbsz;
- }
- if(size) {
- size[0] = bbex-bbsx;
- size[1] = bbey-bbsy;
- size[2] = bbez-bbsz;
- }
-
- // init bounding box mesh?
- if(bbmesh) {
- int i,j;
- Mesh *newmesh = NULL;
- if(!(*bbmesh)) { newmesh = MEM_callocN(sizeof(Mesh), "fluidsimGetAxisAlignedBB_meshbb"); }
- else { newmesh = *bbmesh; }
-
- newmesh->totvert = 8;
- if(!newmesh->mvert)
- newmesh->mvert = CustomData_add_layer(&newmesh->vdata, CD_MVERT, CD_CALLOC, NULL, newmesh->totvert);
- for(i=0; i<8; i++) {
- for(j=0; j<3; j++) newmesh->mvert[i].co[j] = start[j];
+ attribs->tang.array = fdata->layers[layer].data;
+ attribs->tang.emOffset = fdata->layers[layer].offset;
+ attribs->tang.glIndex = gattribs->layer[b].glindex;
+ }
}
+ else if(gattribs->layer[b].type == CD_ORCO) {
+ /* original coordinates */
+ layer = CustomData_get_layer_index(vdata, CD_ORCO);
- newmesh->totface = 6;
- if(!newmesh->mface)
- newmesh->mface = CustomData_add_layer(&newmesh->fdata, CD_MFACE, CD_CALLOC, NULL, newmesh->totface);
+ if(layer != -1) {
+ attribs->totorco = 1;
- *bbmesh = newmesh;
+ attribs->orco.array = vdata->layers[layer].data;
+ attribs->orco.emOffset = vdata->layers[layer].offset;
+ attribs->orco.glIndex = gattribs->layer[b].glindex;
+ }
+ }
}
}
-#else // DISABLE_ELBEEM
-
-/* dummy for mesh_calc_modifiers */
-void loadFluidsimMesh(Object *srcob, int useRenderParams) {
-}
-
-#endif // DISABLE_ELBEEM
-
diff --git a/source/blender/blenkernel/intern/Makefile b/source/blender/blenkernel/intern/Makefile
index 94aa3db3f9e..4cfc8f91efe 100644
--- a/source/blender/blenkernel/intern/Makefile
+++ b/source/blender/blenkernel/intern/Makefile
@@ -36,6 +36,7 @@ include nan_compile.mk
CFLAGS += $(LEVEL_1_C_WARNINGS)
# OpenGL and Python
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION)
@@ -66,6 +67,7 @@ CPPFLAGS += $(NAN_SDLCFLAGS)
CPPFLAGS += -I$(NAN_IKSOLVER)/include
CPPFLAGS += -I$(NAN_DECIMATION)/include
CPPFLAGS += -I$(NAN_ELBEEM)/include
+CPPFLAGS += -I$(NAN_OPENNL)/include
# path to zlib
CPPFLAGS += -I$(NAN_ZLIB)/include
@@ -73,9 +75,15 @@ CPPFLAGS += -I$(NAN_ZLIB)/include
#path to nodes
CPPFLAGS += -I../../nodes
+#path to gpu
+CPPFLAGS += -I../../gpu
+
# path to our own external headerfiles
CPPFLAGS += -I..
+# path to bullet2, for cloth
+CPPFLAGS += -I../../../../extern/bullet2/src
+
ifeq ($(WITH_FREETYPE2), true)
CPPFLAGS += -DWITH_FREETYPE2
CPPFLAGS += -I$(NAN_FREETYPE)/include
diff --git a/source/blender/blenkernel/intern/action.c b/source/blender/blenkernel/intern/action.c
index 3011cc2f99b..1c720cea21f 100644
--- a/source/blender/blenkernel/intern/action.c
+++ b/source/blender/blenkernel/intern/action.c
@@ -62,6 +62,7 @@
#include "BLI_arithb.h"
#include "BLI_blenlib.h"
+#include "BLI_ghash.h"
//XXX #include "nla.h"
@@ -174,24 +175,51 @@ void free_action (bAction *act)
if (act->chanbase.first)
BLI_freelistN(&act->chanbase);
+
+ /* Free groups */
+ if (act->groups.first)
+ BLI_freelistN(&act->groups);
+
+ /* Free pose-references (aka local markers) */
+ if (act->markers.first)
+ BLI_freelistN(&act->markers);
}
bAction *copy_action (bAction *src)
{
bAction *dst = NULL;
bActionChannel *dchan, *schan;
+ bActionGroup *dgrp, *sgrp;
if (!src) return NULL;
dst= copy_libblock(src);
+
BLI_duplicatelist(&(dst->chanbase), &(src->chanbase));
+ BLI_duplicatelist(&(dst->groups), &(src->groups));
+ BLI_duplicatelist(&(dst->markers), &(src->markers));
- for (dchan=dst->chanbase.first, schan=src->chanbase.first; dchan; dchan=dchan->next, schan=schan->next){
+ for (dchan=dst->chanbase.first, schan=src->chanbase.first; dchan; dchan=dchan->next, schan=schan->next) {
+ for (dgrp=dst->groups.first, sgrp=src->groups.first; dgrp && sgrp; dgrp=dgrp->next, sgrp=sgrp->next) {
+ if (dchan->grp == sgrp) {
+ dchan->grp= dgrp;
+
+ if (dgrp->channels.first == schan)
+ dgrp->channels.first= dchan;
+ if (dgrp->channels.last == schan)
+ dgrp->channels.last= dchan;
+
+ break;
+ }
+ }
+
dchan->ipo = copy_ipo(dchan->ipo);
copy_constraint_channels(&dchan->constraintChannels, &schan->constraintChannels);
}
+
dst->id.flag |= LIB_FAKEUSER;
dst->id.us++;
+
return dst;
}
@@ -263,6 +291,12 @@ void copy_pose(bPose **dst, bPose *src, int copycon)
return;
}
+ if (*dst==src) {
+ printf("copy_pose source and target are the same\n");
+ *dst=NULL;
+ return;
+ }
+
outPose= MEM_callocN(sizeof(bPose), "pose");
BLI_duplicatelist (&outPose->chanbase, &src->chanbase);
@@ -282,13 +316,82 @@ void free_pose_channels(bPose *pose)
{
bPoseChannel *pchan;
- if (pose->chanbase.first){
+ if (pose->chanbase.first) {
for (pchan = pose->chanbase.first; pchan; pchan=pchan->next){
- if(pchan->path)
+ if (pchan->path)
MEM_freeN(pchan->path);
free_constraints(&pchan->constraints);
}
- BLI_freelistN (&pose->chanbase);
+ BLI_freelistN(&pose->chanbase);
+ }
+}
+
+void free_pose(bPose *pose)
+{
+ if (pose) {
+ /* free pose-channels */
+ free_pose_channels(pose);
+
+ /* free pose-groups */
+ if (pose->agroups.first)
+ BLI_freelistN(&pose->agroups);
+
+ /* free pose */
+ MEM_freeN(pose);
+ }
+}
+
+void game_copy_pose(bPose **dst, bPose *src)
+{
+ bPose *out;
+ bPoseChannel *pchan, *outpchan;
+ GHash *ghash;
+
+ /* the game engine copies the current armature pose and then swaps
+ * the object pose pointer. this makes it possible to change poses
+ * without affecting the original blender data. */
+
+ if (!src) {
+ *dst=NULL;
+ return;
+ }
+ else if (*dst==src) {
+ printf("copy_pose source and target are the same\n");
+ *dst=NULL;
+ return;
+ }
+
+ out= MEM_dupallocN(src);
+ out->agroups.first= out->agroups.last= NULL;
+ BLI_duplicatelist(&out->chanbase, &src->chanbase);
+
+ /* remap pointers */
+ ghash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
+
+ pchan= src->chanbase.first;
+ outpchan= out->chanbase.first;
+ for (; pchan; pchan=pchan->next, outpchan=outpchan->next)
+ BLI_ghash_insert(ghash, pchan, outpchan);
+
+ for (pchan=out->chanbase.first; pchan; pchan=pchan->next) {
+ pchan->parent= BLI_ghash_lookup(ghash, pchan->parent);
+ pchan->child= BLI_ghash_lookup(ghash, pchan->child);
+ pchan->path= NULL;
+ }
+
+ BLI_ghash_free(ghash, NULL, NULL);
+
+ *dst=out;
+}
+
+void game_free_pose(bPose *pose)
+{
+ if (pose) {
+ /* we don't free constraints, those are owned by the original pose */
+ if(pose->chanbase.first)
+ BLI_freelistN(&pose->chanbase);
+
+ MEM_freeN(pose);
}
}
@@ -299,16 +402,20 @@ static void copy_pose_channel_data(bPoseChannel *pchan, const bPoseChannel *chan
VECCOPY(pchan->loc, chan->loc);
VECCOPY(pchan->size, chan->size);
QUATCOPY(pchan->quat, chan->quat);
+ Mat4CpyMat4(pchan->chan_mat, (float(*)[4])chan->chan_mat);
+ Mat4CpyMat4(pchan->pose_mat, (float(*)[4])chan->pose_mat);
pchan->flag= chan->flag;
con= chan->constraints.first;
- for(pcon= pchan->constraints.first; pcon; pcon= pcon->next) {
+ for(pcon= pchan->constraints.first; pcon; pcon= pcon->next, con= con->next) {
pcon->enforce= con->enforce;
pcon->headtail= con->headtail;
}
}
-/* checks for IK constraint, can do more constraints flags later */
+/* checks for IK constraint, and also for Follow-Path constraint.
+ * can do more constraints flags later
+ */
/* pose should be entirely OK */
void update_pose_constraint_flags(bPose *pose)
{
@@ -316,13 +423,15 @@ void update_pose_constraint_flags(bPose *pose)
bConstraint *con;
/* clear */
- for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
+ for (pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
pchan->constflag= 0;
}
+ pose->flag &= ~POSE_CONSTRAINTS_TIMEDEPEND;
+
/* detect */
- for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
- for(con= pchan->constraints.first; con; con= con->next) {
- if(con->type==CONSTRAINT_TYPE_KINEMATIC) {
+ for (pchan= pose->chanbase.first; pchan; pchan=pchan->next) {
+ for (con= pchan->constraints.first; con; con= con->next) {
+ if (con->type==CONSTRAINT_TYPE_KINEMATIC) {
bKinematicConstraint *data = (bKinematicConstraint*)con->data;
pchan->constflag |= PCHAN_HAS_IK;
@@ -345,7 +454,20 @@ void update_pose_constraint_flags(bPose *pose)
}
}
}
- else pchan->constflag |= PCHAN_HAS_CONST;
+ else if (con->type == CONSTRAINT_TYPE_FOLLOWPATH) {
+ bFollowPathConstraint *data= (bFollowPathConstraint *)con->data;
+
+ /* for drawing constraint colors when color set allows this */
+ pchan->constflag |= PCHAN_HAS_CONST;
+
+ /* if we have a valid target, make sure that this will get updated on frame-change
+ * (needed for when there is no anim-data for this pose)
+ */
+ if ((data->tar) && (data->tar->type==OB_CURVE))
+ pose->flag |= POSE_CONSTRAINTS_TIMEDEPEND;
+ }
+ else
+ pchan->constflag |= PCHAN_HAS_CONST;
}
}
}
@@ -385,7 +507,7 @@ bActionChannel *get_action_channel(bAction *act, const char *name)
if (!act || !name)
return NULL;
- for (chan = act->chanbase.first; chan; chan=chan->next){
+ for (chan = act->chanbase.first; chan; chan=chan->next) {
if (!strcmp (chan->name, name))
return chan;
}
@@ -393,18 +515,16 @@ bActionChannel *get_action_channel(bAction *act, const char *name)
return NULL;
}
-/* returns existing channel, or adds new one. In latter case it doesnt activate it, context is required for that*/
+/* returns existing channel, or adds new one. In latter case it doesnt activate it, context is required for that */
bActionChannel *verify_action_channel(bAction *act, const char *name)
{
bActionChannel *chan;
chan= get_action_channel(act, name);
- if(chan==NULL) {
- if (!chan) {
- chan = MEM_callocN (sizeof(bActionChannel), "actionChannel");
- strncpy (chan->name, name, 31);
- BLI_addtail (&act->chanbase, chan);
- }
+ if (chan == NULL) {
+ chan = MEM_callocN (sizeof(bActionChannel), "actionChannel");
+ strncpy(chan->name, name, 31);
+ BLI_addtail(&act->chanbase, chan);
}
return chan;
}
@@ -432,8 +552,11 @@ static float get_actionstrip_frame(bActionStrip *strip, float cframe, int invert
{
float length, actlength, repeat, scale;
+ if (strip->repeat == 0.0f) strip->repeat = 1.0f;
repeat = (strip->flag & ACTSTRIP_USESTRIDE) ? (1.0f) : (strip->repeat);
- scale = abs(strip->scale); /* scale must be positive (for now) */
+
+ if (strip->scale == 0.0f) strip->scale= 1.0f;
+ scale = fabs(strip->scale); /* scale must be positive (for now) */
actlength = strip->actend-strip->actstart;
if (actlength == 0.0f) actlength = 1.0f;
@@ -680,6 +803,11 @@ void extract_pose_from_pose(bPose *pose, const bPose *src)
const bPoseChannel *schan;
bPoseChannel *pchan= pose->chanbase.first;
+ if (pose==src) {
+ printf("extract_pose_from_pose source and target are the same\n");
+ return;
+ }
+
for (schan=src->chanbase.first; schan; schan=schan->next, pchan= pchan->next) {
copy_pose_channel_data(pchan, schan);
}
@@ -757,6 +885,12 @@ void copy_pose_result(bPose *to, bPose *from)
return;
}
+ if (to==from) {
+ printf("copy_pose_result source and target are the same\n");
+ return;
+ }
+
+
for(pchanfrom= from->chanbase.first; pchanfrom; pchanfrom= pchanfrom->next) {
pchanto= get_pose_channel(to, pchanfrom->name);
if(pchanto) {
@@ -783,7 +917,7 @@ typedef struct NlaIpoChannel {
int type;
} NlaIpoChannel;
-static void extract_ipochannels_from_action(ListBase *lb, ID *id, bAction *act, char *name, float ctime)
+void extract_ipochannels_from_action(ListBase *lb, ID *id, bAction *act, const char *name, float ctime)
{
bActionChannel *achan= get_action_channel(act, name);
IpoCurve *icu;
@@ -876,15 +1010,18 @@ static void blend_ipochannels(ListBase *dst, ListBase *src, float srcweight, int
}
}
-static void execute_ipochannels(ListBase *lb)
+int execute_ipochannels(ListBase *lb)
{
NlaIpoChannel *nic;
+ int count = 0;
for(nic= lb->first; nic; nic= nic->next) {
if(nic->poin) {
write_ipo_poin(nic->poin, nic->type, nic->val);
+ count++;
}
}
+ return count;
}
/* nla timing */
@@ -901,11 +1038,7 @@ static float nla_time(float cfra, float unit)
/* global time */
cfra*= G.scene->r.framelen;
-
-
- /* decide later... */
-// if(no_speed_curve==0) if(ob && ob->ipo) cfra= calc_ipo_time(ob->ipo, cfra);
-
+
return cfra;
}
@@ -915,7 +1048,7 @@ static float nla_time(float cfra, float unit)
static float stridechannel_frame(Object *ob, float sizecorr, bActionStrip *strip, Path *path, float pathdist, float *stride_offset)
{
bAction *act= strip->act;
- char *name= strip->stridechannel;
+ const char *name= strip->stridechannel;
bActionChannel *achan= get_action_channel(act, name);
int stride_axis= strip->stride_axis;
@@ -1083,12 +1216,13 @@ void what_does_obaction (Object *ob, bAction *act, float cframe)
workob.constraints.first = ob->constraints.first;
workob.constraints.last = ob->constraints.last;
- strcpy(workob.parsubstr, ob->parsubstr);
+ strcpy(workob.parsubstr, ob->parsubstr);
+ strcpy(workob.id.name, ob->id.name);
/* extract_ipochannels_from_action needs id's! */
workob.action= act;
- extract_ipochannels_from_action(&tchanbase, &ob->id, act, "Object", bsystem_time(&workob, cframe, 0.0));
+ extract_ipochannels_from_action(&tchanbase, &workob.id, act, "Object", bsystem_time(&workob, cframe, 0.0));
if (tchanbase.first) {
execute_ipochannels(&tchanbase);
@@ -1308,10 +1442,8 @@ static void do_nla(Object *ob, int blocktype)
}
/* free */
- if (tpose){
- free_pose_channels(tpose);
- MEM_freeN(tpose);
- }
+ if (tpose)
+ free_pose(tpose);
if(chanbase.first)
BLI_freelistN(&chanbase);
}
diff --git a/source/blender/blenkernel/intern/anim.c b/source/blender/blenkernel/intern/anim.c
index 08648aa6e10..aeddabf8c1b 100644
--- a/source/blender/blenkernel/intern/anim.c
+++ b/source/blender/blenkernel/intern/anim.c
@@ -44,6 +44,7 @@
#include "DNA_key_types.h"
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
+#include "DNA_modifier_types.h"
#include "DNA_object_types.h"
#include "DNA_particle_types.h"
#include "DNA_scene_types.h"
@@ -51,6 +52,7 @@
#include "DNA_vfont_types.h"
#include "BKE_anim.h"
+#include "BKE_curve.h"
#include "BKE_DerivedMesh.h"
#include "BKE_displist.h"
#include "BKE_effect.h"
@@ -61,6 +63,7 @@
#include "BKE_key.h"
#include "BKE_lattice.h"
#include "BKE_main.h"
+#include "BKE_mesh.h"
#include "BKE_object.h"
#include "BKE_particle.h"
#include "BKE_utildefines.h"
@@ -69,6 +72,8 @@
#include <config.h>
#endif
+static void object_duplilist_recursive(ID *id, Object *ob, ListBase *duplilist, float par_space_mat[][4], int level, int animated);
+
void free_path(Path *path)
{
if(path->data) MEM_freeN(path->data);
@@ -112,7 +117,7 @@ void calc_curvepath(Object *ob)
path->len= tot+1;
/* exception: vector handle paths and polygon paths should be subdivided at least a factor resolu */
- if(path->len<nu->resolu*nu->pntsu) path->len= nu->resolu*nu->pntsu;
+ if(path->len<nu->resolu*SEGMENTSU(nu)) path->len= nu->resolu*SEGMENTSU(nu);
dist= (float *)MEM_mallocN((tot+1)*4, "calcpathdist");
@@ -275,7 +280,7 @@ int where_on_path(Object *ob, float ctime, float *vec, float *dir) /* returns OK
/* ****************** DUPLICATOR ************** */
-static DupliObject *new_dupli_object(ListBase *lb, Object *ob, float mat[][4], int lay, int index)
+static DupliObject *new_dupli_object(ListBase *lb, Object *ob, float mat[][4], int lay, int index, int type, int animated)
{
DupliObject *dob= MEM_callocN(sizeof(DupliObject), "dupliobject");
@@ -285,50 +290,66 @@ static DupliObject *new_dupli_object(ListBase *lb, Object *ob, float mat[][4], i
Mat4CpyMat4(dob->omat, ob->obmat);
dob->origlay= ob->lay;
dob->index= index;
+ dob->type= type;
+ dob->animated= (type == OB_DUPLIGROUP) && animated;
ob->lay= lay;
return dob;
}
-static void group_duplilist(ListBase *lb, Object *ob, int level)
+static void group_duplilist(ListBase *lb, Object *ob, int level, int animated)
{
DupliObject *dob;
Group *group;
GroupObject *go;
- float mat[4][4];
+ float mat[4][4], tmat[4][4];
if(ob->dup_group==NULL) return;
group= ob->dup_group;
/* simple preventing of too deep nested groups */
- if(level>4) return;
+ if(level>MAX_DUPLI_RECUR) return;
/* handles animated groups, and */
/* we need to check update for objects that are not in scene... */
group_handle_recalc_and_update(ob, group);
+ animated= animated || group_is_animated(ob, group);
for(go= group->gobject.first; go; go= go->next) {
/* note, if you check on layer here, render goes wrong... it still deforms verts and uses parent imat */
if(go->ob!=ob) {
- Mat4MulMat4(mat, go->ob->obmat, ob->obmat);
- dob= new_dupli_object(lb, go->ob, mat, ob->lay, 0);
+
+ /* Group Dupli Offset, should apply after everything else */
+ if (group->dupli_ofs[0] || group->dupli_ofs[1] || group->dupli_ofs[2]) {
+ Mat4CpyMat4(tmat, go->ob->obmat);
+ VecSubf(tmat[3], tmat[3], group->dupli_ofs);
+ Mat4MulMat4(mat, tmat, ob->obmat);
+ } else {
+ Mat4MulMat4(mat, go->ob->obmat, ob->obmat);
+ }
+
+ dob= new_dupli_object(lb, go->ob, mat, ob->lay, 0, OB_DUPLIGROUP, animated);
dob->no_draw= (dob->origlay & group->layer)==0;
- if(go->ob->dup_group && (go->ob->transflag & OB_DUPLIGROUP)) {
+ if(go->ob->transflag & OB_DUPLI) {
Mat4CpyMat4(dob->ob->obmat, dob->mat);
- group_duplilist(lb, go->ob, level+1);
+ object_duplilist_recursive((ID *)group, go->ob, lb, ob->obmat, level+1, animated);
Mat4CpyMat4(dob->ob->obmat, dob->omat);
}
}
}
}
-static void frames_duplilist(ListBase *lb, Object *ob)
+static void frames_duplilist(ListBase *lb, Object *ob, int level, int animated)
{
extern int enable_cu_speed; /* object.c */
Object copyob;
+ DupliObject *dob;
int cfrao, ok;
+ /* simple preventing of too deep nested groups */
+ if(level>MAX_DUPLI_RECUR) return;
+
cfrao= G.scene->r.cfra;
if(ob->parent==NULL && ob->track==NULL && ob->ipo==NULL && ob->constraints.first==NULL) return;
@@ -347,7 +368,8 @@ static void frames_duplilist(ListBase *lb, Object *ob)
if(ok) {
do_ob_ipo(ob);
where_is_object_time(ob, (float)G.scene->r.cfra);
- new_dupli_object(lb, ob, ob->obmat, ob->lay, G.scene->r.cfra);
+ dob= new_dupli_object(lb, ob, ob->obmat, ob->lay, G.scene->r.cfra, OB_DUPLIFRAMES, animated);
+ Mat4CpyMat4(dob->omat, copyob.obmat);
}
}
@@ -357,22 +379,28 @@ static void frames_duplilist(ListBase *lb, Object *ob)
}
struct vertexDupliData {
+ ID *id; /* scene or group, for recursive loops */
+ int level;
+ int animated;
ListBase *lb;
float pmat[4][4];
+ float obmat[4][4]; /* Only used for dupliverts inside dupligroups, where the ob->obmat is modified */
Object *ob, *par;
+ float (*orco)[3];
};
static void vertex_dupli__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
{
+ DupliObject *dob;
struct vertexDupliData *vdd= userData;
- float vec[3], *q2, mat[3][3], tmat[4][4], obmat[4][4];
+ float vec[3], q2[4], mat[3][3], tmat[4][4], obmat[4][4];
VECCOPY(vec, co);
Mat4MulVecfl(vdd->pmat, vec);
VecSubf(vec, vec, vdd->pmat[3]);
- VecAddf(vec, vec, vdd->ob->obmat[3]);
+ VecAddf(vec, vec, vdd->obmat[3]);
- Mat4CpyMat4(obmat, vdd->ob->obmat);
+ Mat4CpyMat4(obmat, vdd->obmat);
VECCOPY(obmat[3], vec);
if(vdd->par->transflag & OB_DUPLIROT) {
@@ -383,44 +411,98 @@ static void vertex_dupli__mapFunc(void *userData, int index, float *co, float *n
vec[0]= -no_s[0]; vec[1]= -no_s[1]; vec[2]= -no_s[2];
}
- q2= vectoquat(vec, vdd->ob->trackflag, vdd->ob->upflag);
+ vectoquat(vec, vdd->ob->trackflag, vdd->ob->upflag, q2);
QuatToMat3(q2, mat);
Mat4CpyMat4(tmat, obmat);
Mat4MulMat43(obmat, tmat, mat);
}
- new_dupli_object(vdd->lb, vdd->ob, obmat, vdd->par->lay, index);
+ dob= new_dupli_object(vdd->lb, vdd->ob, obmat, vdd->par->lay, index, OB_DUPLIVERTS, vdd->animated);
+ if(vdd->orco)
+ VECCOPY(dob->orco, vdd->orco[index]);
+
+ if(vdd->ob->transflag & OB_DUPLI) {
+ float tmpmat[4][4];
+ Mat4CpyMat4(tmpmat, vdd->ob->obmat);
+ Mat4CpyMat4(vdd->ob->obmat, obmat); /* pretend we are really this mat */
+ object_duplilist_recursive((ID *)vdd->id, vdd->ob, vdd->lb, obmat, vdd->level+1, vdd->animated);
+ Mat4CpyMat4(vdd->ob->obmat, tmpmat);
+ }
}
-static void vertex_duplilist(ListBase *lb, Scene *sce, Object *par)
+static void vertex_duplilist(ListBase *lb, ID *id, Object *par, float par_space_mat[][4], int level, int animated)
{
- Object *ob;
- Base *base;
+ Object *ob, *ob_iter;
+ Mesh *me;
+ Base *base = NULL;
float vec[3], no[3], pmat[4][4];
- int lay, totvert, a;
+ int lay, totvert, a, oblay;
DerivedMesh *dm;
+ struct vertexDupliData vdd;
+ Scene *sce = NULL;
+ Group *group = NULL;
+ GroupObject * go = NULL;
Mat4CpyMat4(pmat, par->obmat);
- lay= G.scene->lay;
-
+ /* simple preventing of too deep nested groups */
+ if(level>MAX_DUPLI_RECUR) return;
+
if(par==G.obedit)
dm= editmesh_get_derived_cage(CD_MASK_BAREMESH);
else
- dm = mesh_get_derived_deform(par, CD_MASK_BAREMESH);
+ dm= mesh_get_derived_deform(par, CD_MASK_BAREMESH);
+
+ if(G.rendering) {
+ me= par->data;
+ vdd.orco= (float(*)[3])get_mesh_orco_verts(par);
+ transform_mesh_orco_verts(me, vdd.orco, me->totvert, 0);
+ }
+ else
+ vdd.orco= NULL;
totvert = dm->getNumVerts(dm);
- base= sce->base.first;
- while(base) {
-
- if(base->object->type>0 && (lay & base->lay) && G.obedit!=base->object) {
- ob= base->object->parent;
+ /* having to loop on scene OR group objects is NOT FUN */
+ if (GS(id->name) == ID_SCE) {
+ sce = (Scene *)id;
+ lay= sce->lay;
+ base= sce->base.first;
+ } else {
+ group = (Group *)id;
+ lay= group->layer;
+ go = group->gobject.first;
+ }
+
+ /* Start looping on Scene OR Group objects */
+ while (base || go) {
+ if (sce) {
+ ob_iter= base->object;
+ oblay = base->lay;
+ } else {
+ ob_iter= go->ob;
+ oblay = ob_iter->lay;
+ }
+
+ if (lay & oblay && G.obedit!=ob_iter) {
+ ob=ob_iter->parent;
while(ob) {
if(ob==par) {
- struct vertexDupliData vdd;
+ ob = ob_iter;
+ /* End Scene/Group object loop, below is generic */
- ob= base->object;
+
+ /* par_space_mat - only used for groups so we can modify the space dupli's are in
+ when par_space_mat is NULL ob->obmat can be used instead of ob__obmat
+ */
+ if(par_space_mat)
+ Mat4MulMat4(vdd.obmat, ob->obmat, par_space_mat);
+ else
+ Mat4CpyMat4(vdd.obmat, ob->obmat);
+
+ vdd.id= id;
+ vdd.level= level;
+ vdd.animated= animated;
vdd.lb= lb;
vdd.ob= ob;
vdd.par= par;
@@ -446,26 +528,37 @@ static void vertex_duplilist(ListBase *lb, Scene *sce, Object *par)
ob= ob->parent;
}
}
- base= base->next;
+ if (sce) base= base->next; /* scene loop */
+ else go= go->next; /* group loop */
}
+ if(vdd.orco)
+ MEM_freeN(vdd.orco);
dm->release(dm);
}
-static void face_duplilist(ListBase *lb, Scene *sce, Object *par)
+static void face_duplilist(ListBase *lb, ID *id, Object *par, float par_space_mat[][4], int level, int animated)
{
- Object *ob;
- Base *base;
+ Object *ob, *ob_iter;
+ Base *base = NULL;
+ DupliObject *dob;
DerivedMesh *dm;
+ Mesh *me;
+ MTFace *mtface;
MFace *mface;
MVert *mvert;
- float pmat[4][4], imat[3][3];
- int lay, totface, a;
-
- Mat4CpyMat4(pmat, par->obmat);
+ float pmat[4][4], imat[3][3], (*orco)[3] = NULL, w;
+ int lay, oblay, totface, a;
+ Scene *sce = NULL;
+ Group *group = NULL;
+ GroupObject *go = NULL;
+ float ob__obmat[4][4]; /* needed for groups where the object matrix needs to be modified */
- lay= G.scene->lay;
+ /* simple preventing of too deep nested groups */
+ if(level>MAX_DUPLI_RECUR) return;
+ Mat4CpyMat4(pmat, par->obmat);
+
if(par==G.obedit) {
int totvert;
dm= editmesh_get_derived_cage(CD_MASK_BAREMESH);
@@ -484,26 +577,69 @@ static void face_duplilist(ListBase *lb, Scene *sce, Object *par)
mface= dm->getFaceArray(dm);
mvert= dm->getVertArray(dm);
}
+
+ if(G.rendering) {
+ me= (Mesh*)par->data;
+
+ orco= (float(*)[3])get_mesh_orco_verts(par);
+ transform_mesh_orco_verts(me, orco, me->totvert, 0);
+ mtface= me->mtface;
+ }
+ else {
+ orco= NULL;
+ mtface= NULL;
+ }
+ /* having to loop on scene OR group objects is NOT FUN */
+ if (GS(id->name) == ID_SCE) {
+ sce = (Scene *)id;
+ lay= sce->lay;
+ base= sce->base.first;
+ } else {
+ group = (Group *)id;
+ lay= group->layer;
+ go = group->gobject.first;
+ }
- for(base= sce->base.first; base; base= base->next) {
+ /* Start looping on Scene OR Group objects */
+ while (base || go) {
+ if (sce) {
+ ob_iter= base->object;
+ oblay = base->lay;
+ } else {
+ ob_iter= go->ob;
+ oblay = ob_iter->lay;
+ }
- if(base->object->type>0 && (lay & base->lay) && G.obedit!=base->object) {
- ob= base->object->parent;
+ if (lay & oblay && G.obedit!=ob_iter) {
+ ob=ob_iter->parent;
while(ob) {
if(ob==par) {
+ ob = ob_iter;
+ /* End Scene/Group object loop, below is generic */
- ob= base->object;
- Mat3CpyMat4(imat, ob->parentinv);
+ /* par_space_mat - only used for groups so we can modify the space dupli's are in
+ when par_space_mat is NULL ob->obmat can be used instead of ob__obmat
+ */
+ if(par_space_mat)
+ Mat4MulMat4(ob__obmat, ob->obmat, par_space_mat);
+ else
+ Mat4CpyMat4(ob__obmat, ob->obmat);
+ Mat3CpyMat4(imat, ob->parentinv);
+
/* mballs have a different dupli handling */
if(ob->type!=OB_MBALL) ob->flag |= OB_DONE; /* doesnt render */
for(a=0; a<totface; a++) {
- float *v1= mvert[ mface[a].v1 ].co;
- float *v2= mvert[ mface[a].v2 ].co;
- float *v3= mvert[ mface[a].v3 ].co;
- float *v4= mface[a].v4?mvert[ mface[a].v4 ].co:NULL;
+ int mv1 = mface[a].v1;
+ int mv2 = mface[a].v2;
+ int mv3 = mface[a].v3;
+ int mv4 = mface[a].v4;
+ float *v1= mvert[mv1].co;
+ float *v2= mvert[mv2].co;
+ float *v3= mvert[mv3].co;
+ float *v4= (mv4)? mvert[mv4].co: NULL;
float cent[3], quat[4], mat[3][3], mat3[3][3], tmat[4][4], obmat[4][4];
/* translation */
@@ -514,9 +650,10 @@ static void face_duplilist(ListBase *lb, Scene *sce, Object *par)
Mat4MulVecfl(pmat, cent);
VecSubf(cent, cent, pmat[3]);
- VecAddf(cent, cent, ob->obmat[3]);
+ VecAddf(cent, cent, ob__obmat[3]);
+
+ Mat4CpyMat4(obmat, ob__obmat);
- Mat4CpyMat4(obmat, ob->obmat);
VECCOPY(obmat[3], cent);
/* rotation */
@@ -536,8 +673,40 @@ static void face_duplilist(ListBase *lb, Scene *sce, Object *par)
Mat4CpyMat4(tmat, obmat);
Mat4MulMat43(obmat, tmat, mat);
- new_dupli_object(lb, ob, obmat, lay, a);
-
+ dob= new_dupli_object(lb, ob, obmat, lay, a, OB_DUPLIFACES, animated);
+ if(G.rendering) {
+ w= (mv4)? 0.25f: 1.0f/3.0f;
+
+ if(orco) {
+ VECADDFAC(dob->orco, dob->orco, orco[mv1], w);
+ VECADDFAC(dob->orco, dob->orco, orco[mv2], w);
+ VECADDFAC(dob->orco, dob->orco, orco[mv3], w);
+ if(mv4)
+ VECADDFAC(dob->orco, dob->orco, orco[mv4], w);
+ }
+
+ if(mtface) {
+ dob->uv[0] += w*mtface[a].uv[0][0];
+ dob->uv[1] += w*mtface[a].uv[0][1];
+ dob->uv[0] += w*mtface[a].uv[1][0];
+ dob->uv[1] += w*mtface[a].uv[1][1];
+ dob->uv[0] += w*mtface[a].uv[2][0];
+ dob->uv[1] += w*mtface[a].uv[2][1];
+
+ if(mv4) {
+ dob->uv[0] += w*mtface[a].uv[3][0];
+ dob->uv[1] += w*mtface[a].uv[3][1];
+ }
+ }
+ }
+
+ if(ob->transflag & OB_DUPLI) {
+ float tmpmat[4][4];
+ Mat4CpyMat4(tmpmat, ob->obmat);
+ Mat4CpyMat4(ob->obmat, obmat); /* pretend we are really this mat */
+ object_duplilist_recursive((ID *)id, ob, lb, ob->obmat, level+1, animated);
+ Mat4CpyMat4(ob->obmat, tmpmat);
+ }
}
break;
@@ -545,34 +714,51 @@ static void face_duplilist(ListBase *lb, Scene *sce, Object *par)
ob= ob->parent;
}
}
+ if (sce) base= base->next; /* scene loop */
+ else go= go->next; /* group loop */
}
if(par==G.obedit) {
MEM_freeN(mface);
MEM_freeN(mvert);
}
+
+ if(orco)
+ MEM_freeN(orco);
dm->release(dm);
}
-static void new_particle_duplilist(ListBase *lb, Scene *sce, Object *par, ParticleSystem *psys)
+static void new_particle_duplilist(ListBase *lb, ID *id, Object *par, float par_space_mat[][4], ParticleSystem *psys, int level, int animated)
{
GroupObject *go;
- Object *ob, **oblist=0;
+ Object *ob=0, **oblist=0, obcopy, *obcopylist=0;
+ DupliObject *dob;
ParticleSettings *part;
ParticleData *pa;
+ ChildParticle *cpa=0;
ParticleKey state;
- float ctime, pa_time;
- float tmat[4][4], mat[3][3], obrotmat[3][3], parotmat[3][3], size=0.0;
- float xvec[3] = {-1.0, 0.0, 0.0}, *q;
- int lay, a, k, step_nbr = 0, counter;
+ ParticleCacheKey *cache;
+ ParticleSystemModifierData *psmd;
+ float ctime, pa_time, scale = 1.0f;
+ float tmat[4][4], mat[4][4], pamat[4][4], size=0.0;
+ float (*obmat)[4], (*oldobmat)[4];
+ int lay, a, b, k, step_nbr = 0, counter, hair = 0;
int totpart, totchild, totgroup=0, pa_num;
if(psys==0) return;
+ /* simple preventing of too deep nested groups */
+ if(level>MAX_DUPLI_RECUR) return;
+
part=psys->part;
+ psmd= psys_get_modifier(par, psys);
+
+ if(part==0)
+ return;
- if(part==0) return;
+ if(!psys_check_enabled(par, psys))
+ return;
ctime = bsystem_time(par, (float)G.scene->r.cfra, 0.0);
@@ -580,7 +766,7 @@ static void new_particle_duplilist(ListBase *lb, Scene *sce, Object *par, Partic
totchild = psys->totchild;
BLI_srandom(31415926 + psys->seed);
-
+
lay= G.scene->lay;
if((part->draw_as == PART_DRAW_OB && part->dup_ob) ||
(part->draw_as == PART_DRAW_GR && part->dup_group && part->dup_group->gobject.first)) {
@@ -590,103 +776,171 @@ static void new_particle_duplilist(ListBase *lb, Scene *sce, Object *par, Partic
else
step_nbr = 0;
+ /* if we have a hair particle system, use the path cache */
+ if(part->type == PART_HAIR) {
+ if(psys->flag & PSYS_HAIR_DONE)
+ hair= (totchild == 0 || psys->childcache) && psys->pathcache;
+ if(!hair)
+ return;
+
+ /* we use cache, update totchild according to cached data */
+ totchild = psys->totchildcache;
+ totpart = psys->totcached;
+ }
+
psys->lattice = psys_get_lattice(par, psys);
+ /* gather list of objects or single object */
if(part->draw_as==PART_DRAW_GR) {
group_handle_recalc_and_update(par, part->dup_group);
- go= part->dup_group->gobject.first;
- while(go) {
- go=go->next;
+ for(go=part->dup_group->gobject.first; go; go=go->next)
totgroup++;
- }
- oblist= MEM_callocN(totgroup*sizeof(Object *), "dupgroup object list");
- go= part->dup_group->gobject.first;
- for(a=0; a<totgroup; a++, go=go->next)
- oblist[a]=go->ob;
+ /* we also copy the actual objects to restore afterwards, since
+ * where_is_object_time will change the object which breaks transform */
+ oblist = MEM_callocN(totgroup*sizeof(Object *), "dupgroup object list");
+ obcopylist = MEM_callocN(totgroup*sizeof(Object), "dupgroup copy list");
+
+ go = part->dup_group->gobject.first;
+ for(a=0; a<totgroup; a++, go=go->next) {
+ oblist[a] = go->ob;
+ obcopylist[a] = *go->ob;
+ }
+ }
+ else {
+ ob = part->dup_ob;
+ obcopy = *ob;
}
if(totchild==0 || part->draw & PART_DRAW_PARENT)
- a=0;
+ a = 0;
else
- a=totpart;
+ a = totpart;
for(pa=psys->particles,counter=0; a<totpart+totchild; a++,pa++,counter++) {
if(a<totpart) {
- if(pa->flag & (PARS_UNEXIST+PARS_NO_DISP)) continue;
-
- pa_num=pa->num;
+ /* handle parent particle */
+ if(pa->flag & (PARS_UNEXIST+PARS_NO_DISP))
+ continue;
- pa_time=pa->time;
-
- size=pa->size;
+ pa_num = pa->num;
+ pa_time = pa->time;
+ size = pa->size;
}
else {
- /* TODO: figure these two out */
- pa_num = a;
- pa_time = psys->particles[psys->child[a - totpart].parent].time;
+ /* handle child particle */
+ cpa = &psys->child[a - totpart];
- size=psys_get_child_size(psys, &psys->child[a - totpart], ctime, 0);
+ pa_num = a;
+ pa_time = psys->particles[cpa->parent].time;
+ size = psys_get_child_size(psys, cpa, ctime, 0);
}
if(part->draw_as==PART_DRAW_GR) {
+ /* for groups, pick the object based on settings */
if(part->draw&PART_DRAW_RAND_GR)
- ob = oblist[BLI_rand() % totgroup];
+ b= BLI_rand() % totgroup;
else if(part->from==PART_FROM_PARTICLE)
- ob = oblist[pa_num % totgroup];
+ b= pa_num % totgroup;
else
- ob = oblist[a % totgroup];
+ b= a % totgroup;
+
+ ob = oblist[b];
+ obmat = oblist[b]->obmat;
+ oldobmat = obcopylist[b].obmat;
+ }
+ else {
+ obmat= ob->obmat;
+ oldobmat= obcopy.obmat;
}
- else
- ob = part->dup_ob;
for(k=0; k<=step_nbr; k++, counter++) {
- if(step_nbr) {
+ if(hair) {
+ /* hair we handle separate and compute transform based on hair keys */
+ if(a < totpart) {
+ cache = psys->pathcache[a];
+ psys_get_dupli_path_transform(par, psys, psmd, pa, 0, cache, pamat, &scale);
+ }
+ else {
+ cache = psys->childcache[a-totpart];
+ psys_get_dupli_path_transform(par, psys, psmd, 0, cpa, cache, pamat, &scale);
+ }
+
+ VECCOPY(pamat[3], cache->co);
+ pamat[3][3]= 1.0f;
+
+ }
+ else if(step_nbr) {
+ /* other keys */
state.time = (float)k / (float)step_nbr;
psys_get_particle_on_path(par, psys, a, &state, 0);
+
+ QuatToMat4(state.rot, pamat);
+ VECCOPY(pamat[3], state.co);
+ pamat[3][3]= 1.0f;
}
else {
+ /* first key */
state.time = -1.0;
if(psys_get_particle_state(par, psys, a, &state, 0) == 0)
continue;
- }
- QuatToMat3(state.rot, parotmat);
+ QuatToMat4(state.rot, pamat);
+ VECCOPY(pamat[3], state.co);
+ pamat[3][3]= 1.0f;
+ }
if(part->draw_as==PART_DRAW_GR && psys->part->draw & PART_DRAW_WHOLE_GR) {
- for(go= part->dup_group->gobject.first; go; go= go->next) {
-
- Mat4CpyMat4(tmat, go->ob->obmat);
- Mat4MulMat43(tmat, go->ob->obmat, parotmat);
- Mat4MulFloat3((float *)tmat, size);
-
- VECADD(tmat[3], go->ob->obmat[3], state.co);
+ for(go= part->dup_group->gobject.first, b=0; go; go= go->next, b++) {
+ Mat4MulMat4(tmat, oblist[b]->obmat, pamat);
+ Mat4MulFloat3((float *)tmat, size*scale);
+ if(par_space_mat)
+ Mat4MulMat4(mat, tmat, par_space_mat);
+ else
+ Mat4CpyMat4(mat, tmat);
- new_dupli_object(lb, go->ob, tmat, par->lay, counter);
+ dob= new_dupli_object(lb, go->ob, mat, par->lay, counter, OB_DUPLIPARTS, animated);
+ Mat4CpyMat4(dob->omat, obcopylist[b].obmat);
+ if(G.rendering)
+ psys_get_dupli_texture(par, part, psmd, pa, cpa, dob->uv, dob->orco);
}
}
else {
/* to give ipos in object correct offset */
where_is_object_time(ob, ctime-pa_time);
- q = vectoquat(xvec, ob->trackflag, ob->upflag);
- QuatToMat3(q, obrotmat);
-
- Mat3MulMat3(mat, parotmat, obrotmat);
- Mat4CpyMat4(tmat, ob->obmat);
- Mat4MulMat43(tmat, ob->obmat, mat);
- Mat4MulFloat3((float *)tmat, size);
+ Mat4CpyMat4(mat, pamat);
- VECCOPY(tmat[3], state.co);
+ Mat4MulMat4(tmat, obmat, mat);
+ Mat4MulFloat3((float *)tmat, size*scale);
+ if(par_space_mat)
+ Mat4MulMat4(mat, tmat, par_space_mat);
+ else
+ Mat4CpyMat4(mat, tmat);
- new_dupli_object(lb, ob, tmat, par->lay, counter);
+ dob= new_dupli_object(lb, ob, mat, par->lay, counter, OB_DUPLIPARTS, animated);
+ Mat4CpyMat4(dob->omat, oldobmat);
+ if(G.rendering)
+ psys_get_dupli_texture(par, part, psmd, pa, cpa, dob->uv, dob->orco);
}
}
}
+
+ /* restore objects since they were changed in where_is_object_time */
+ if(part->draw_as==PART_DRAW_GR) {
+ for(a=0; a<totgroup; a++)
+ *(oblist[a])= obcopylist[a];
+ }
+ else
+ *ob= obcopy;
}
+
+ /* clean up */
if(oblist)
MEM_freeN(oblist);
+ if(obcopylist)
+ MEM_freeN(obcopylist);
if(psys->lattice) {
end_latt_deform();
@@ -717,7 +971,7 @@ static Object *find_family_object(Object **obar, char *family, char ch)
}
-static void font_duplilist(ListBase *lb, Object *par)
+static void font_duplilist(ListBase *lb, Object *par, int level, int animated)
{
Object *ob, *obar[256];
Curve *cu;
@@ -725,6 +979,9 @@ static void font_duplilist(ListBase *lb, Object *par)
float vec[3], obmat[4][4], pmat[4][4], fsize, xof, yof;
int slen, a;
+ /* simple preventing of too deep nested groups */
+ if(level>MAX_DUPLI_RECUR) return;
+
Mat4CpyMat4(pmat, par->obmat);
/* in par the family name is stored, use this to find the other objects */
@@ -755,54 +1012,73 @@ static void font_duplilist(ListBase *lb, Object *par)
Mat4CpyMat4(obmat, par->obmat);
VECCOPY(obmat[3], vec);
- new_dupli_object(lb, ob, obmat, par->lay, a);
+ new_dupli_object(lb, ob, obmat, par->lay, a, OB_DUPLIVERTS, animated);
}
-
}
MEM_freeN(chartransdata);
}
/* ***************************** */
+static void object_duplilist_recursive(ID *id, Object *ob, ListBase *duplilist, float par_space_mat[][4], int level, int animated)
+{
+ if((ob->transflag & OB_DUPLI)==0)
+ return;
+
+ /* Should the dupli's be generated for this object? - Respect restrict flags */
+ if (G.rendering) {
+ if (ob->restrictflag & OB_RESTRICT_RENDER) {
+ return;
+ }
+ } else {
+ if (ob->restrictflag & OB_RESTRICT_VIEW) {
+ return;
+ }
+ }
-/* note; group dupli's already set transform matrix. see note in group_duplilist() */
-ListBase *object_duplilist(Scene *sce, Object *ob)
-{
- ListBase *duplilist= MEM_mallocN(sizeof(ListBase), "duplilist");
- duplilist->first= duplilist->last= NULL;
-
- if(ob->transflag & OB_DUPLI) {
- if(ob->transflag & OB_DUPLIPARTS) {
- ParticleSystem *psys = ob->particlesystem.first;
- for(; psys; psys=psys->next)
- new_particle_duplilist(duplilist, sce, ob, psys);
+ if(ob->transflag & OB_DUPLIPARTS) {
+ ParticleSystem *psys = ob->particlesystem.first;
+ for(; psys; psys=psys->next)
+ new_particle_duplilist(duplilist, id, ob, par_space_mat, psys, level+1, animated);
+ }
+ else if(ob->transflag & OB_DUPLIVERTS) {
+ if(ob->type==OB_MESH) {
+ vertex_duplilist(duplilist, id, ob, par_space_mat, level+1, animated);
}
- else if(ob->transflag & OB_DUPLIVERTS) {
- if(ob->type==OB_MESH) {
- vertex_duplilist(duplilist, sce, ob);
- }
- else if(ob->type==OB_FONT) {
- font_duplilist(duplilist, ob);
+ else if(ob->type==OB_FONT) {
+ if (GS(id->name)==ID_SCE) { /* TODO - support dupligroups */
+ font_duplilist(duplilist, ob, level+1, animated);
}
}
- else if(ob->transflag & OB_DUPLIFACES) {
- if(ob->type==OB_MESH)
- face_duplilist(duplilist, sce, ob);
+ }
+ else if(ob->transflag & OB_DUPLIFACES) {
+ if(ob->type==OB_MESH)
+ face_duplilist(duplilist, id, ob, par_space_mat, level+1, animated);
+ }
+ else if(ob->transflag & OB_DUPLIFRAMES) {
+ if (GS(id->name)==ID_SCE) { /* TODO - support dupligroups */
+ frames_duplilist(duplilist, ob, level+1, animated);
}
- else if(ob->transflag & OB_DUPLIFRAMES)
- frames_duplilist(duplilist, ob);
- else if(ob->transflag & OB_DUPLIGROUP) {
- DupliObject *dob;
-
- group_duplilist(duplilist, ob, 0); /* now recursive */
+ } else if(ob->transflag & OB_DUPLIGROUP) {
+ DupliObject *dob;
+
+ group_duplilist(duplilist, ob, level+1, animated); /* now recursive */
- /* make copy already, because in group dupli's deform displists can be made, requiring parent matrices */
+ if (level==0) {
for(dob= duplilist->first; dob; dob= dob->next)
- Mat4CpyMat4(dob->ob->obmat, dob->mat);
+ if(dob->type == OB_DUPLIGROUP)
+ Mat4CpyMat4(dob->ob->obmat, dob->mat);
}
-
}
-
+}
+
+/* Returns a list of DupliObject
+ * note; group dupli's already set transform matrix. see note in group_duplilist() */
+ListBase *object_duplilist(Scene *sce, Object *ob)
+{
+ ListBase *duplilist= MEM_mallocN(sizeof(ListBase), "duplilist");
+ duplilist->first= duplilist->last= NULL;
+ object_duplilist_recursive((ID *)sce, ob, duplilist, NULL, 0, 0);
return duplilist;
}
diff --git a/source/blender/blenkernel/intern/armature.c b/source/blender/blenkernel/intern/armature.c
index 4d50c268397..8bb694f45e8 100644
--- a/source/blender/blenkernel/intern/armature.c
+++ b/source/blender/blenkernel/intern/armature.c
@@ -30,6 +30,8 @@
#include <math.h>
#include <string.h>
#include <stdio.h>
+#include <float.h>
+
#include "MEM_guardedalloc.h"
//XXX #include "nla.h"
@@ -354,6 +356,117 @@ void bone_flip_name (char *name, int strip_number)
sprintf (name, "%s%s%s%s", prefix, replace, suffix, number);
}
+/* Finds the best possible extension to the name on a particular axis. (For renaming, check for unique names afterwards)
+ * This assumes that bone names are at most 32 chars long!
+ * strip_number: removes number extensions (TODO: not used)
+ * axis: the axis to name on
+ * head/tail: the head/tail co-ordinate of the bone on the specified axis
+ */
+void bone_autoside_name (char *name, int strip_number, short axis, float head, float tail)
+{
+ int len;
+ char basename[32]={""};
+ char extension[5]={""};
+
+ len= strlen(name);
+ if (len == 0) return;
+ strcpy(basename, name);
+
+ /* Figure out extension to append:
+ * - The extension to append is based upon the axis that we are working on.
+ * - If head happens to be on 0, then we must consider the tail position as well to decide
+ * which side the bone is on
+ * -> If tail is 0, then it's bone is considered to be on axis, so no extension should be added
+ * -> Otherwise, extension is added from perspective of object based on which side tail goes to
+ * - If head is non-zero, extension is added from perspective of object based on side head is on
+ */
+ if (axis == 2) {
+ /* z-axis - vertical (top/bottom) */
+ if (IS_EQ(head, 0)) {
+ if (tail < 0)
+ strcpy(extension, "Bot");
+ else if (tail > 0)
+ strcpy(extension, "Top");
+ }
+ else {
+ if (head < 0)
+ strcpy(extension, "Bot");
+ else
+ strcpy(extension, "Top");
+ }
+ }
+ else if (axis == 1) {
+ /* y-axis - depth (front/back) */
+ if (IS_EQ(head, 0)) {
+ if (tail < 0)
+ strcpy(extension, "Fr");
+ else if (tail > 0)
+ strcpy(extension, "Bk");
+ }
+ else {
+ if (head < 0)
+ strcpy(extension, "Fr");
+ else
+ strcpy(extension, "Bk");
+ }
+ }
+ else {
+ /* x-axis - horizontal (left/right) */
+ if (IS_EQ(head, 0)) {
+ if (tail < 0)
+ strcpy(extension, "R");
+ else if (tail > 0)
+ strcpy(extension, "L");
+ }
+ else {
+ if (head < 0)
+ strcpy(extension, "R");
+ else if (head > 0)
+ strcpy(extension, "L");
+ }
+ }
+
+ /* Simple name truncation
+ * - truncate if there is an extension and it wouldn't be able to fit
+ * - otherwise, just append to end
+ */
+ if (extension[0]) {
+ int change = 1;
+
+ while (change) { /* remove extensions */
+ change = 0;
+ if (len > 2 && basename[len-2]=='.') {
+ if (basename[len-1]=='L' || basename[len-1] == 'R' ) { /* L R */
+ basename[len-2] = '\0';
+ len-=2;
+ change= 1;
+ }
+ } else if (len > 3 && basename[len-3]=='.') {
+ if ( (basename[len-2]=='F' && basename[len-1] == 'r') || /* Fr */
+ (basename[len-2]=='B' && basename[len-1] == 'k') /* Bk */
+ ) {
+ basename[len-3] = '\0';
+ len-=3;
+ change= 1;
+ }
+ } else if (len > 4 && basename[len-4]=='.') {
+ if ( (basename[len-3]=='T' && basename[len-2]=='o' && basename[len-1] == 'p') || /* Top */
+ (basename[len-3]=='B' && basename[len-2]=='o' && basename[len-1] == 't') /* Bot */
+ ) {
+ basename[len-4] = '\0';
+ len-=4;
+ change= 1;
+ }
+ }
+ }
+
+ if ((32 - len) < strlen(extension) + 1) { /* add 1 for the '.' */
+ strncpy(name, basename, len-strlen(extension));
+ }
+ }
+
+ sprintf(name, "%s.%s", basename, extension);
+}
/* ************* B-Bone support ******************* */
@@ -1305,18 +1418,27 @@ static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected
bPoseChannel *pchan, *pchanp, pchanw;
bConstraint *con;
- if(frompose==NULL) return;
+ if (frompose==NULL) return;
/* exception, armature local layer should be proxied too */
- if(pose->proxy_layer)
+ if (pose->proxy_layer)
((bArmature *)ob->data)->layer= pose->proxy_layer;
/* clear all transformation values from library */
rest_pose(frompose);
- pchan= pose->chanbase.first;
- for(; pchan; pchan= pchan->next) {
- if(pchan->bone->layer & layer_protected) {
+ /* copy over all of the proxy's bone groups */
+ /* TODO for later - implement 'local' bone groups as for constraints
+ * Note: this isn't trivial, as bones reference groups by index not by pointer,
+ * so syncing things correctly needs careful attention
+ */
+ BLI_freelistN(&pose->agroups);
+ BLI_duplicatelist(&pose->agroups, &frompose->agroups);
+ pose->active_group= frompose->active_group;
+
+ for (pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
+ if (pchan->bone->layer & layer_protected) {
+ ListBase proxylocal_constraints = {NULL, NULL};
pchanp= get_pose_channel(frompose, pchan->name);
/* copy posechannel to temp, but restore important pointers */
@@ -1327,9 +1449,16 @@ static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected
pchanw.child= pchan->child;
pchanw.path= NULL;
- /* constraints, set target ob pointer to own object */
+ /* constraints - proxy constraints are flushed... local ones are added after
+ * 1. extract constraints not from proxy (CONSTRAINT_PROXY_LOCAL) from pchan's constraints
+ * 2. copy proxy-pchan's constraints on-to new
+ * 3. add extracted local constraints back on top
+ */
+ extract_proxylocal_constraints(&proxylocal_constraints, &pchan->constraints);
copy_constraints(&pchanw.constraints, &pchanp->constraints);
+ addlisttolist(&pchanw.constraints, &proxylocal_constraints);
+ /* constraints - set target ob pointer to own object */
for (con= pchanw.constraints.first; con; con= con->next) {
bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
ListBase targets = {NULL, NULL};
@@ -1444,21 +1573,16 @@ static void initialize_posetree(struct Object *ob, bPoseChannel *pchan_tip)
/* find IK constraint, and validate it */
for(con= pchan_tip->constraints.first; con; con= con->next) {
- if(con->type==CONSTRAINT_TYPE_KINEMATIC) break;
+ if(con->type==CONSTRAINT_TYPE_KINEMATIC) {
+ data=(bKinematicConstraint*)con->data;
+ if (data->flag & CONSTRAINT_IK_AUTO) break;
+ if (data->tar==NULL) continue;
+ if (data->tar->type==OB_ARMATURE && data->subtarget[0]==0) continue;
+ if ((con->flag & CONSTRAINT_DISABLE)==0 && (con->enforce!=0.0)) break;
+ }
}
if(con==NULL) return;
- data=(bKinematicConstraint*)con->data;
-
- /* two types of targets */
- if(data->flag & CONSTRAINT_IK_AUTO);
- else {
- if(con->flag & CONSTRAINT_DISABLE) return; /* checked in editconstraint.c */
- if(con->enforce == 0.0f) return;
- if(data->tar==NULL) return;
- if(data->tar->type==OB_ARMATURE && data->subtarget[0]==0) return;
- }
-
/* exclude tip from chain? */
if(!(data->flag & CONSTRAINT_IK_TIP))
pchan_tip= pchan_tip->parent;
@@ -1561,7 +1685,7 @@ static void initialize_posetree(struct Object *ob, bPoseChannel *pchan_tip)
were executed & assigned. Now as last we do an IK pass */
static void execute_posetree(Object *ob, PoseTree *tree)
{
- float R_parmat[3][3];
+ float R_parmat[3][3], identity[3][3];
float iR_parmat[3][3];
float R_bonemat[3][3];
float goalrot[3][3], goalpos[3];
@@ -1570,7 +1694,8 @@ static void execute_posetree(Object *ob, PoseTree *tree)
float irest_basis[3][3], full_basis[3][3];
float end_pose[4][4], world_pose[4][4];
float length, basis[3][3], rest_basis[3][3], start[3], *ikstretch=NULL;
- int a, flag, hasstretch=0;
+ float resultinf=0.0f;
+ int a, flag, hasstretch=0, resultblend=0;
bPoseChannel *pchan;
IK_Segment *seg, *parent, **iktree, *iktarget;
IK_Solver *solver;
@@ -1580,13 +1705,13 @@ static void execute_posetree(Object *ob, PoseTree *tree)
if (tree->totchannel == 0)
return;
-
+
iktree= MEM_mallocN(sizeof(void*)*tree->totchannel, "ik tree");
for(a=0; a<tree->totchannel; a++) {
pchan= tree->pchan[a];
bone= pchan->bone;
-
+
/* set DoF flag */
flag= 0;
if(!(pchan->ikflag & BONE_IK_NO_XDOF) && !(pchan->ikflag & BONE_IK_NO_XDOF_TEMP))
@@ -1595,32 +1720,32 @@ static void execute_posetree(Object *ob, PoseTree *tree)
flag |= IK_YDOF;
if(!(pchan->ikflag & BONE_IK_NO_ZDOF) && !(pchan->ikflag & BONE_IK_NO_ZDOF_TEMP))
flag |= IK_ZDOF;
-
+
if(tree->stretch && (pchan->ikstretch > 0.0)) {
flag |= IK_TRANS_YDOF;
hasstretch = 1;
}
-
+
seg= iktree[a]= IK_CreateSegment(flag);
-
+
/* find parent */
if(a == 0)
parent= NULL;
else
parent= iktree[tree->parent[a]];
-
+
IK_SetParent(seg, parent);
-
+
/* get the matrix that transforms from prevbone into this bone */
Mat3CpyMat4(R_bonemat, pchan->pose_mat);
-
+
/* gather transformations for this IK segment */
-
+
if (pchan->parent)
Mat3CpyMat4(R_parmat, pchan->parent->pose_mat);
else
Mat3One(R_parmat);
-
+
/* bone offset */
if (pchan->parent && (a > 0))
VecSubf(start, pchan->pose_head, pchan->parent->pose_tail);
@@ -1630,40 +1755,40 @@ static void execute_posetree(Object *ob, PoseTree *tree)
/* change length based on bone size */
length= bone->length*VecLength(R_bonemat[1]);
-
+
/* compute rest basis and its inverse */
Mat3CpyMat3(rest_basis, bone->bone_mat);
Mat3CpyMat3(irest_basis, bone->bone_mat);
Mat3Transp(irest_basis);
-
+
/* compute basis with rest_basis removed */
Mat3Inv(iR_parmat, R_parmat);
Mat3MulMat3(full_basis, iR_parmat, R_bonemat);
Mat3MulMat3(basis, irest_basis, full_basis);
-
+
/* basis must be pure rotation */
Mat3Ortho(basis);
-
+
/* transform offset into local bone space */
Mat3Ortho(iR_parmat);
Mat3MulVecfl(iR_parmat, start);
-
+
IK_SetTransform(seg, start, rest_basis, basis, length);
-
+
if (pchan->ikflag & BONE_IK_XLIMIT)
IK_SetLimit(seg, IK_X, pchan->limitmin[0], pchan->limitmax[0]);
if (pchan->ikflag & BONE_IK_YLIMIT)
IK_SetLimit(seg, IK_Y, pchan->limitmin[1], pchan->limitmax[1]);
if (pchan->ikflag & BONE_IK_ZLIMIT)
IK_SetLimit(seg, IK_Z, pchan->limitmin[2], pchan->limitmax[2]);
-
+
IK_SetStiffness(seg, IK_X, pchan->stiffness[0]);
IK_SetStiffness(seg, IK_Y, pchan->stiffness[1]);
IK_SetStiffness(seg, IK_Z, pchan->stiffness[2]);
-
+
if(tree->stretch && (pchan->ikstretch > 0.0)) {
float ikstretch = pchan->ikstretch*pchan->ikstretch;
- IK_SetStiffness(seg, IK_TRANS_Y, MIN2(1.0-ikstretch, 0.999));
+ IK_SetStiffness(seg, IK_TRANS_Y, MIN2(1.0-ikstretch, 0.99));
IK_SetLimit(seg, IK_TRANS_Y, 0.001, 1e10);
}
}
@@ -1689,7 +1814,7 @@ static void execute_posetree(Object *ob, PoseTree *tree)
for (target=tree->targets.first; target; target=target->next) {
float polepos[3];
int poleconstrain= 0;
-
+
data= (bKinematicConstraint*)target->con->data;
/* 1.0=ctime, we pass on object for auto-ik (owner-type here is object, even though
@@ -1706,7 +1831,7 @@ static void execute_posetree(Object *ob, PoseTree *tree)
/* same for pole vector target */
if(data->poletar) {
get_constraint_target_matrix(target->con, 1, CONSTRAINT_OBTYPE_OBJECT, ob, rootmat, 1.0);
-
+
if(data->flag & CONSTRAINT_IK_SETANGLE) {
/* don't solve IK when we are setting the pole angle */
break;
@@ -1716,6 +1841,12 @@ static void execute_posetree(Object *ob, PoseTree *tree)
VECCOPY(polepos, goal[3]);
poleconstrain= 1;
+ /* for pole targets, we blend the result of the ik solver
+ * instead of the target position, otherwise we can't get
+ * a smooth transition */
+ resultblend= 1;
+ resultinf= target->con->enforce;
+
if(data->flag & CONSTRAINT_IK_GETANGLE) {
poleangledata= data;
data->flag &= ~CONSTRAINT_IK_GETANGLE;
@@ -1724,7 +1855,7 @@ static void execute_posetree(Object *ob, PoseTree *tree)
}
/* do we need blending? */
- if (target->con->enforce!=1.0) {
+ if (!resultblend && target->con->enforce!=1.0) {
float q1[4], q2[4], q[4];
float fac= target->con->enforce;
float mfac= 1.0-fac;
@@ -1774,36 +1905,41 @@ static void execute_posetree(Object *ob, PoseTree *tree)
tree->basis_change= MEM_mallocN(sizeof(float[3][3])*tree->totchannel, "ik basis change");
if(hasstretch)
ikstretch= MEM_mallocN(sizeof(float)*tree->totchannel, "ik stretch");
-
+
for(a=0; a<tree->totchannel; a++) {
IK_GetBasisChange(iktree[a], tree->basis_change[a]);
-
+
if(hasstretch) {
/* have to compensate for scaling received from parent */
float parentstretch, stretch;
-
+
pchan= tree->pchan[a];
parentstretch= (tree->parent[a] >= 0)? ikstretch[tree->parent[a]]: 1.0;
-
+
if(tree->stretch && (pchan->ikstretch > 0.0)) {
float trans[3], length;
-
+
IK_GetTranslationChange(iktree[a], trans);
length= pchan->bone->length*VecLength(pchan->pose_mat[1]);
-
+
ikstretch[a]= (length == 0.0)? 1.0: (trans[1]+length)/length;
}
else
ikstretch[a] = 1.0;
-
+
stretch= (parentstretch == 0.0)? 1.0: ikstretch[a]/parentstretch;
-
+
VecMulf(tree->basis_change[a][0], stretch);
VecMulf(tree->basis_change[a][1], stretch);
VecMulf(tree->basis_change[a][2], stretch);
-
}
+ if(resultblend && resultinf!=1.0f) {
+ Mat3One(identity);
+ Mat3BlendMat3(tree->basis_change[a], identity,
+ tree->basis_change[a], resultinf);
+ }
+
IK_FreeSegment(iktree[a]);
}
@@ -2072,8 +2208,10 @@ static void where_is_pose_bone(Object *ob, bPoseChannel *pchan, float ctime)
}
else {
Mat4MulMat4(pchan->pose_mat, pchan->chan_mat, bone->arm_mat);
- /* only rootbones get the cyclic offset */
- VecAddf(pchan->pose_mat[3], pchan->pose_mat[3], ob->pose->cyclic_offset);
+
+ /* only rootbones get the cyclic offset (unless user doesn't want that) */
+ if ((bone->flag & BONE_NO_CYCLICOFFSET) == 0)
+ VecAddf(pchan->pose_mat[3], pchan->pose_mat[3], ob->pose->cyclic_offset);
}
/* do NLA strip modifiers - i.e. curve follow */
diff --git a/source/blender/blenkernel/intern/blender.c b/source/blender/blenkernel/intern/blender.c
index 109fe4b2d74..b63d63c925c 100644
--- a/source/blender/blenkernel/intern/blender.c
+++ b/source/blender/blenkernel/intern/blender.c
@@ -30,11 +30,15 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#ifndef WIN32
- #include <unistd.h> // for read close
- #include <sys/param.h> // for MAXPATHLEN
+#ifndef _WIN32
+ #include <unistd.h> // for read close
+ #include <sys/param.h> // for MAXPATHLEN
#else
- #include <io.h> // for open close read
+ #include <io.h> // for open close read
+ #define open _open
+ #define read _read
+ #define close _close
+ #define write _write
#endif
#include <stdlib.h>
@@ -61,6 +65,7 @@
#include "IMB_imbuf_types.h"
#include "IMB_imbuf.h"
+#include "BKE_action.h"
#include "BKE_blender.h"
#include "BKE_curve.h"
#include "BKE_depsgraph.h"
@@ -282,7 +287,6 @@ static void clean_paths(Main *main)
}
BLI_clean(scene->r.backbuf);
BLI_clean(scene->r.pic);
- BLI_clean(scene->r.ftype);
scene= scene->id.next;
}
@@ -313,6 +317,7 @@ static void setup_app_data(bContext *C, BlendFileData *bfd, char *filename)
extern void lib_link_screen_restore(Main *, Scene *);
SWAP(ListBase, G.main->screen, bfd->main->screen);
+ SWAP(ListBase, G.main->script, bfd->main->script);
/* we re-use current screen */
curscreen= C->screen;
@@ -366,7 +371,8 @@ static void setup_app_data(bContext *C, BlendFileData *bfd, char *filename)
/* special cases, override loaded flags: */
if (G.f & G_DEBUG) bfd->globalf |= G_DEBUG;
else bfd->globalf &= ~G_DEBUG;
- if (!(G.f & G_DOSCRIPTLINKS)) bfd->globalf &= ~G_DOSCRIPTLINKS;
+
+ if ((U.flag & USER_DONT_DOSCRIPTLINKS)) bfd->globalf &= ~G_DOSCRIPTLINKS;
G.f= bfd->globalf;
@@ -377,6 +383,9 @@ static void setup_app_data(bContext *C, BlendFileData *bfd, char *filename)
/* baseflags, groups, make depsgraph, etc */
set_scene_bg(C->scene);
+ /* clear BONE_UNKEYED flags, these are not valid anymore for proxies */
+ framechange_poses_clear_unkeyed();
+
/* last stage of do_versions actually, that sets recalc flags for recalc poses */
for(ob= G.main->object.first; ob; ob= ob->id.next) {
if(ob->type==OB_ARMATURE)
@@ -393,7 +402,7 @@ static void setup_app_data(bContext *C, BlendFileData *bfd, char *filename)
if (G.sce != filename) /* these are the same at times, should never copy to the same location */
strcpy(G.sce, filename);
- strcpy(G.main->name, filename); /* is guaranteed current file */
+ BLI_strncpy(G.main->name, filename, FILE_MAX); /* is guaranteed current file */
MEM_freeN(bfd);
}
@@ -445,8 +454,8 @@ int BKE_read_file_from_memory(bContext *C, char* filebuf, int filelength, void *
BlendFileData *bfd;
bfd= BLO_read_from_memory(filebuf, filelength, &bre);
- if (bfd) {
- setup_app_data(C, bfd, "<memory>");
+ if (bfd) {
+ setup_app_data(C, bfd, "<memory2>");
} else {
// XXX error("Loading failed: %s", BLO_bre_as_string(bre));
}
@@ -462,7 +471,7 @@ int BKE_read_file_from_memfile(bContext *C, MemFile *memfile)
bfd= BLO_read_from_memfile(G.sce, memfile, &bre);
if (bfd) {
- setup_app_data(C, bfd, "<memory>");
+ setup_app_data(C, bfd, "<memory1>");
} else {
// XXX error("Loading failed: %s", BLO_bre_as_string(bre));
}
@@ -481,6 +490,7 @@ typedef struct UndoElem {
char str[FILE_MAXDIR+FILE_MAXFILE];
char name[MAXUNDONAME];
MemFile memfile;
+ uintptr_t undosize;
} UndoElem;
static ListBase undobase={NULL, NULL};
@@ -511,6 +521,7 @@ static int read_undosave(bContext *C, UndoElem *uel)
/* name can be a dynamic string */
void BKE_write_undo(bContext *C, char *name)
{
+ uintptr_t maxmem, totmem, memused;
int nr, success;
UndoElem *uel;
@@ -560,7 +571,7 @@ void BKE_write_undo(bContext *C, char *name)
counter= counter % U.undosteps;
sprintf(numstr, "%d.blend", counter);
- BLI_make_file_string("/", tstr, U.tempdir, numstr);
+ BLI_make_file_string("/", tstr, btempdir, numstr);
success= BLO_write_file(C, tstr, G.fileflags, &err);
@@ -572,12 +583,41 @@ void BKE_write_undo(bContext *C, char *name)
if(curundo->prev) prevfile= &(curundo->prev->memfile);
+ memused= MEM_get_memory_in_use();
success= BLO_write_file_mem(C, prevfile, &curundo->memfile, G.fileflags, &err);
-
+ curundo->undosize= MEM_get_memory_in_use() - memused;
+ }
+
+ if(U.undomemory != 0) {
+ /* limit to maximum memory (afterwards, we can't know in advance) */
+ totmem= 0;
+ maxmem= ((uintptr_t)U.undomemory)*1024*1024;
+
+ /* keep at least two (original + other) */
+ uel= undobase.last;
+ while(uel && uel->prev) {
+ totmem+= uel->undosize;
+ if(totmem>maxmem) break;
+ uel= uel->prev;
+ }
+
+ if(uel) {
+ if(uel->prev && uel->prev->prev)
+ uel= uel->prev;
+
+ while(undobase.first!=uel) {
+ UndoElem *first= undobase.first;
+ BLI_remlink(&undobase, first);
+ /* the merge is because of compression */
+ BLO_merge_memfile(&first->memfile, &first->next->memfile);
+ MEM_freeN(first);
+ }
+ }
}
}
-/* 1= an undo, -1 is a redo. we have to make sure 'curundo' remains at current situation */
+/* 1= an undo, -1 is a redo. we have to make sure 'curundo' remains at current situation
+ * Note, ALWAYS call sound_initialize_sounds after BKE_undo_step() */
void BKE_undo_step(bContext *C, int step)
{
@@ -638,14 +678,14 @@ char *BKE_undo_menu_string(void)
UndoElem *uel;
DynStr *ds= BLI_dynstr_new();
char *menu;
-
+
BLI_dynstr_append(ds, "Global Undo History %t");
for(uel= undobase.first; uel; uel= uel->next) {
BLI_dynstr_append(ds, "|");
BLI_dynstr_append(ds, uel->name);
}
-
+
menu= BLI_dynstr_get_cstring(ds);
BLI_dynstr_free(ds);
@@ -671,11 +711,11 @@ void BKE_undo_save_quit(void)
/* no undo state to save */
if(undobase.first==undobase.last) return;
- BLI_make_file_string("/", str, U.tempdir, "quit.blend");
+ BLI_make_file_string("/", str, btempdir, "quit.blend");
file = open(str,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
if(file == -1) {
- printf("Unable to save %s\n", str);
+ //XXX error("Unable to save %s, check you have permissions", str);
return;
}
@@ -687,7 +727,7 @@ void BKE_undo_save_quit(void)
close(file);
- if(chunk) printf("Unable to save %s\n", str);
+ if(chunk) ; //XXX error("Unable to save %s, internal error", str);
else printf("Saved session recovery to %s\n", str);
}
diff --git a/source/blender/blenkernel/intern/bmesh_private.h b/source/blender/blenkernel/intern/bmesh_private.h
new file mode 100644
index 00000000000..f34ef0090f3
--- /dev/null
+++ b/source/blender/blenkernel/intern/bmesh_private.h
@@ -0,0 +1,70 @@
+/**
+ * BME_private.h jan 2007
+ *
+ * low level, 'private' function prototypes for bmesh kernel.
+ *
+ * $Id: BKE_bmesh.h,v 1.00 2007/01/17 17:42:01 Briggs Exp $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2004 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Geoffrey Bantle.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef BMESH_PRIVATE
+#define BMESH_PRIVATE
+
+#include "BKE_bmesh.h"
+
+/*ALLOCATION/DEALLOCATION*/
+struct BME_Vert *BME_addvertlist(struct BME_Mesh *bm, struct BME_Vert *example);
+struct BME_Edge *BME_addedgelist(struct BME_Mesh *bm, struct BME_Vert *v1, struct BME_Vert *v2, struct BME_Edge *example);
+struct BME_Poly *BME_addpolylist(struct BME_Mesh *bm, struct BME_Poly *example);
+struct BME_Loop *BME_create_loop(struct BME_Mesh *bm, struct BME_Vert *v, struct BME_Edge *e, struct BME_Poly *f, struct BME_Loop *example);
+
+void BME_free_vert(struct BME_Mesh *bm, struct BME_Vert *v);
+void BME_free_edge(struct BME_Mesh *bm, struct BME_Edge *e);
+void BME_free_poly(struct BME_Mesh *bm, struct BME_Poly *f);
+void BME_free_loop(struct BME_Mesh *bm, struct BME_Loop *l);
+
+/*DOUBLE CIRCULAR LINKED LIST FUNCTIONS*/
+void BME_cycle_append(void *h, void *nt);
+int BME_cycle_remove(void *h, void *remn);
+int BME_cycle_validate(int len, void *h);
+/*DISK CYCLE MANAGMENT*/
+int BME_disk_append_edge(struct BME_Edge *e, struct BME_Vert *v);
+void BME_disk_remove_edge(struct BME_Edge *e, struct BME_Vert *v);
+/*RADIAL CYCLE MANAGMENT*/
+void BME_radial_append(struct BME_Edge *e, struct BME_Loop *l);
+void BME_radial_remove_loop(struct BME_Loop *l, struct BME_Edge *e);
+
+/*MISC FUNCTIONS*/
+int BME_edge_swapverts(struct BME_Edge *e, struct BME_Vert *orig, struct BME_Vert *new); /*relink edge*/
+int BME_disk_hasedge(struct BME_Vert *v, struct BME_Edge *e);
+
+/*Error reporting. Shouldnt be called by tools ever.*/
+void BME_error(void);
+#endif
diff --git a/source/blender/blenkernel/intern/brush.c b/source/blender/blenkernel/intern/brush.c
index f1b12869c0f..1c53af97dbb 100644
--- a/source/blender/blenkernel/intern/brush.c
+++ b/source/blender/blenkernel/intern/brush.c
@@ -70,7 +70,8 @@ Brush *add_brush(char *name)
brush->clone.alpha= 0.5;
/* enable fake user by default */
- brush_toggle_fake_user(brush);
+ brush->id.flag |= LIB_FAKEUSER;
+ brush_toggled_fake_user(brush);
return brush;
}
@@ -92,8 +93,10 @@ Brush *copy_brush(Brush *brush)
}
/* enable fake user by default */
- if (!(brushn->id.flag & LIB_FAKEUSER))
- brush_toggle_fake_user(brushn);
+ if (!(brushn->id.flag & LIB_FAKEUSER)) {
+ brushn->id.flag |= LIB_FAKEUSER;
+ brush_toggled_fake_user(brushn);
+ }
return brushn;
}
@@ -145,8 +148,10 @@ void make_local_brush(Brush *brush)
new_id(0, (ID *)brush, 0);
/* enable fake user by default */
- if (!(brush->id.flag & LIB_FAKEUSER))
- brush_toggle_fake_user(brush);
+ if (!(brush->id.flag & LIB_FAKEUSER)) {
+ brush->id.flag |= LIB_FAKEUSER;
+ brush_toggled_fake_user(brush);
+ }
}
else if(local && lib) {
brushn= copy_brush(brush);
@@ -200,16 +205,14 @@ int brush_delete(Brush **current_brush)
return 0;
}
-void brush_toggle_fake_user(Brush *brush)
+void brush_toggled_fake_user(Brush *brush)
{
ID *id= (ID*)brush;
if(id) {
if(id->flag & LIB_FAKEUSER) {
- id->flag -= LIB_FAKEUSER;
- id->us--;
- } else {
- id->flag |= LIB_FAKEUSER;
id_us_plus(id);
+ } else {
+ id->us--;
}
}
}
@@ -356,7 +359,6 @@ void brush_sample_tex(Brush *brush, float *xy, float *rgba)
rgba[0]= rgba[1]= rgba[2]= rgba[3]= 1.0f;
}
-#define FTOCHAR(val) val<=0.0f?0: (val>=1.0f?255: (char)(255.0f*val))
void brush_imbuf_new(Brush *brush, short flt, short texfall, int size, ImBuf **outbuf)
{
diff --git a/source/blender/blenkernel/intern/bullet.c b/source/blender/blenkernel/intern/bullet.c
new file mode 100644
index 00000000000..b389f8c0536
--- /dev/null
+++ b/source/blender/blenkernel/intern/bullet.c
@@ -0,0 +1,96 @@
+/*
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "MEM_guardedalloc.h"
+
+/* types */
+#include "DNA_object_force.h" /* here is the softbody struct */
+
+#include "BKE_bullet.h"
+
+
+/* ************ Object level, exported functions *************** */
+
+/* allocates and initializes general main data */
+BulletSoftBody *bsbNew(void)
+{
+ BulletSoftBody *bsb;
+
+ bsb= MEM_callocN(sizeof(BulletSoftBody), "bulletsoftbody");
+
+ bsb->flag = OB_BSB_BENDING_CONSTRAINTS | OB_BSB_SHAPE_MATCHING | OB_BSB_AERO_VPOINT;
+ bsb->linStiff = 0.5f;
+ bsb->angStiff = 1.0f;
+ bsb->volume = 1.0f;
+
+
+ bsb->viterations = 0;
+ bsb->piterations = 2;
+ bsb->diterations = 0;
+ bsb->citerations = 4;
+
+ bsb->kSRHR_CL = 0.1f;
+ bsb->kSKHR_CL = 1.f;
+ bsb->kSSHR_CL = 0.5f;
+ bsb->kSR_SPLT_CL = 0.5f;
+
+ bsb->kSK_SPLT_CL = 0.5f;
+ bsb->kSS_SPLT_CL = 0.5f;
+ bsb->kVCF = 1;
+ bsb->kDP = 0;
+
+ bsb->kDG = 0;
+ bsb->kLF = 0;
+ bsb->kPR = 0;
+ bsb->kVC = 0;
+
+ bsb->kDF = 0.2f;
+ bsb->kMT = 0.05;
+ bsb->kCHR = 1.0f;
+ bsb->kKHR = 0.1f;
+
+ bsb->kSHR = 1.0f;
+ bsb->kAHR = 0.7f;
+
+ bsb->collisionflags = 0;
+ //bsb->collisionflags = OB_BSB_COL_CL_RS + OB_BSB_COL_CL_SS;
+ bsb->numclusteriterations = 64;
+
+ return bsb;
+}
+
+/* frees all */
+void bsbFree(BulletSoftBody *bsb)
+{
+ /* no internal data yet */
+ MEM_freeN(bsb);
+}
+
+
diff --git a/source/blender/blenkernel/intern/bvhutils.c b/source/blender/blenkernel/intern/bvhutils.c
new file mode 100644
index 00000000000..ae449843d2a
--- /dev/null
+++ b/source/blender/blenkernel/intern/bvhutils.c
@@ -0,0 +1,577 @@
+/**
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): André Pinto.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+
+#include "BKE_bvhutils.h"
+
+#include "DNA_object_types.h"
+#include "DNA_modifier_types.h"
+#include "DNA_meshdata_types.h"
+
+#include "BKE_DerivedMesh.h"
+#include "BKE_utildefines.h"
+#include "BKE_deform.h"
+#include "BKE_cdderivedmesh.h"
+#include "BKE_displist.h"
+#include "BKE_global.h"
+
+#include "BLI_arithb.h"
+
+/* Math stuff for ray casting on mesh faces and for nearest surface */
+
+static float ray_tri_intersection(const BVHTreeRay *ray, const float m_dist, const float *v0, const float *v1, const float *v2)
+{
+ float dist;
+
+ if(RayIntersectsTriangle((float*)ray->origin, (float*)ray->direction, (float*)v0, (float*)v1, (float*)v2, &dist, NULL))
+ return dist;
+
+ return FLT_MAX;
+}
+
+static float sphereray_tri_intersection(const BVHTreeRay *ray, float radius, const float m_dist, const float *v0, const float *v1, const float *v2)
+{
+
+ float idist;
+ float p1[3];
+ float plane_normal[3], hit_point[3];
+
+ CalcNormFloat((float*)v0, (float*)v1, (float*)v2, plane_normal);
+
+ VECADDFAC( p1, ray->origin, ray->direction, m_dist);
+ if(SweepingSphereIntersectsTriangleUV((float*)ray->origin, p1, radius, (float*)v0, (float*)v1, (float*)v2, &idist, hit_point))
+ {
+ return idist * m_dist;
+ }
+
+ return FLT_MAX;
+}
+
+
+/*
+ * Function adapted from David Eberly's distance tools (LGPL)
+ * http://www.geometrictools.com/LibFoundation/Distance/Distance.html
+ */
+static float nearest_point_in_tri_surface(const float *v0,const float *v1,const float *v2,const float *p, int *v, int *e, float *nearest )
+{
+ float diff[3];
+ float e0[3];
+ float e1[3];
+ float A00;
+ float A01;
+ float A11;
+ float B0;
+ float B1;
+ float C;
+ float Det;
+ float S;
+ float T;
+ float sqrDist;
+ int lv = -1, le = -1;
+
+ VECSUB(diff, v0, p);
+ VECSUB(e0, v1, v0);
+ VECSUB(e1, v2, v0);
+
+ A00 = INPR ( e0, e0 );
+ A01 = INPR( e0, e1 );
+ A11 = INPR ( e1, e1 );
+ B0 = INPR( diff, e0 );
+ B1 = INPR( diff, e1 );
+ C = INPR( diff, diff );
+ Det = fabs( A00 * A11 - A01 * A01 );
+ S = A01 * B1 - A11 * B0;
+ T = A01 * B0 - A00 * B1;
+
+ if ( S + T <= Det )
+ {
+ if ( S < 0.0f )
+ {
+ if ( T < 0.0f ) // Region 4
+ {
+ if ( B0 < 0.0f )
+ {
+ T = 0.0f;
+ if ( -B0 >= A00 )
+ {
+ S = (float)1.0;
+ sqrDist = A00 + 2.0f * B0 + C;
+ lv = 1;
+ }
+ else
+ {
+ if(fabs(A00) > FLT_EPSILON)
+ S = -B0/A00;
+ else
+ S = 0.0f;
+ sqrDist = B0 * S + C;
+ le = 0;
+ }
+ }
+ else
+ {
+ S = 0.0f;
+ if ( B1 >= 0.0f )
+ {
+ T = 0.0f;
+ sqrDist = C;
+ lv = 0;
+ }
+ else if ( -B1 >= A11 )
+ {
+ T = 1.0f;
+ sqrDist = A11 + 2.0f * B1 + C;
+ lv = 2;
+ }
+ else
+ {
+ if(fabs(A11) > FLT_EPSILON)
+ T = -B1 / A11;
+ else
+ T = 0.0f;
+ sqrDist = B1 * T + C;
+ le = 1;
+ }
+ }
+ }
+ else // Region 3
+ {
+ S = 0.0f;
+ if ( B1 >= 0.0f )
+ {
+ T = 0.0f;
+ sqrDist = C;
+ lv = 0;
+ }
+ else if ( -B1 >= A11 )
+ {
+ T = 1.0f;
+ sqrDist = A11 + 2.0f * B1 + C;
+ lv = 2;
+ }
+ else
+ {
+ if(fabs(A11) > FLT_EPSILON)
+ T = -B1 / A11;
+ else
+ T = 0.0;
+ sqrDist = B1 * T + C;
+ le = 1;
+ }
+ }
+ }
+ else if ( T < 0.0f ) // Region 5
+ {
+ T = 0.0f;
+ if ( B0 >= 0.0f )
+ {
+ S = 0.0f;
+ sqrDist = C;
+ lv = 0;
+ }
+ else if ( -B0 >= A00 )
+ {
+ S = 1.0f;
+ sqrDist = A00 + 2.0f * B0 + C;
+ lv = 1;
+ }
+ else
+ {
+ if(fabs(A00) > FLT_EPSILON)
+ S = -B0 / A00;
+ else
+ S = 0.0f;
+ sqrDist = B0 * S + C;
+ le = 0;
+ }
+ }
+ else // Region 0
+ {
+ // Minimum at interior lv
+ float invDet;
+ if(fabs(Det) > FLT_EPSILON)
+ invDet = 1.0f / Det;
+ else
+ invDet = 0.0f;
+ S *= invDet;
+ T *= invDet;
+ sqrDist = S * ( A00 * S + A01 * T + 2.0f * B0) +
+ T * ( A01 * S + A11 * T + 2.0f * B1 ) + C;
+ }
+ }
+ else
+ {
+ float tmp0, tmp1, numer, denom;
+
+ if ( S < 0.0f ) // Region 2
+ {
+ tmp0 = A01 + B0;
+ tmp1 = A11 + B1;
+ if ( tmp1 > tmp0 )
+ {
+ numer = tmp1 - tmp0;
+ denom = A00 - 2.0f * A01 + A11;
+ if ( numer >= denom )
+ {
+ S = 1.0f;
+ T = 0.0f;
+ sqrDist = A00 + 2.0f * B0 + C;
+ lv = 1;
+ }
+ else
+ {
+ if(fabs(denom) > FLT_EPSILON)
+ S = numer / denom;
+ else
+ S = 0.0f;
+ T = 1.0f - S;
+ sqrDist = S * ( A00 * S + A01 * T + 2.0f * B0 ) +
+ T * ( A01 * S + A11 * T + 2.0f * B1 ) + C;
+ le = 2;
+ }
+ }
+ else
+ {
+ S = 0.0f;
+ if ( tmp1 <= 0.0f )
+ {
+ T = 1.0f;
+ sqrDist = A11 + 2.0f * B1 + C;
+ lv = 2;
+ }
+ else if ( B1 >= 0.0f )
+ {
+ T = 0.0f;
+ sqrDist = C;
+ lv = 0;
+ }
+ else
+ {
+ if(fabs(A11) > FLT_EPSILON)
+ T = -B1 / A11;
+ else
+ T = 0.0f;
+ sqrDist = B1 * T + C;
+ le = 1;
+ }
+ }
+ }
+ else if ( T < 0.0f ) // Region 6
+ {
+ tmp0 = A01 + B1;
+ tmp1 = A00 + B0;
+ if ( tmp1 > tmp0 )
+ {
+ numer = tmp1 - tmp0;
+ denom = A00 - 2.0f * A01 + A11;
+ if ( numer >= denom )
+ {
+ T = 1.0f;
+ S = 0.0f;
+ sqrDist = A11 + 2.0f * B1 + C;
+ lv = 2;
+ }
+ else
+ {
+ if(fabs(denom) > FLT_EPSILON)
+ T = numer / denom;
+ else
+ T = 0.0f;
+ S = 1.0f - T;
+ sqrDist = S * ( A00 * S + A01 * T + 2.0f * B0 ) +
+ T * ( A01 * S + A11 * T + 2.0f * B1 ) + C;
+ le = 2;
+ }
+ }
+ else
+ {
+ T = 0.0f;
+ if ( tmp1 <= 0.0f )
+ {
+ S = 1.0f;
+ sqrDist = A00 + 2.0f * B0 + C;
+ lv = 1;
+ }
+ else if ( B0 >= 0.0f )
+ {
+ S = 0.0f;
+ sqrDist = C;
+ lv = 0;
+ }
+ else
+ {
+ if(fabs(A00) > FLT_EPSILON)
+ S = -B0 / A00;
+ else
+ S = 0.0f;
+ sqrDist = B0 * S + C;
+ le = 0;
+ }
+ }
+ }
+ else // Region 1
+ {
+ numer = A11 + B1 - A01 - B0;
+ if ( numer <= 0.0f )
+ {
+ S = 0.0f;
+ T = 1.0f;
+ sqrDist = A11 + 2.0f * B1 + C;
+ lv = 2;
+ }
+ else
+ {
+ denom = A00 - 2.0f * A01 + A11;
+ if ( numer >= denom )
+ {
+ S = 1.0f;
+ T = 0.0f;
+ sqrDist = A00 + 2.0f * B0 + C;
+ lv = 1;
+ }
+ else
+ {
+ if(fabs(denom) > FLT_EPSILON)
+ S = numer / denom;
+ else
+ S = 0.0f;
+ T = 1.0f - S;
+ sqrDist = S * ( A00 * S + A01 * T + 2.0f * B0 ) +
+ T * ( A01 * S + A11 * T + 2.0f * B1 ) + C;
+ le = 2;
+ }
+ }
+ }
+ }
+
+ // Account for numerical round-off error
+ if ( sqrDist < FLT_EPSILON )
+ sqrDist = 0.0f;
+
+ {
+ float w[3], x[3], y[3], z[3];
+ VECCOPY(w, v0);
+ VECCOPY(x, e0);
+ VecMulf(x, S);
+ VECCOPY(y, e1);
+ VecMulf(y, T);
+ VECADD(z, w, x);
+ VECADD(z, z, y);
+ //VECSUB(d, p, z);
+ VECCOPY(nearest, z);
+ // d = p - ( v0 + S * e0 + T * e1 );
+ }
+ *v = lv;
+ *e = le;
+
+ return sqrDist;
+}
+
+
+/*
+ * BVH from meshs callbacks
+ */
+
+// Callback to bvh tree nearest point. The tree must bust have been built using bvhtree_from_mesh_faces.
+// userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree.
+static void mesh_faces_nearest_point(void *userdata, int index, const float *co, BVHTreeNearest *nearest)
+{
+ const BVHTreeFromMesh *data = (BVHTreeFromMesh*) userdata;
+ MVert *vert = data->vert;
+ MFace *face = data->face + index;
+
+ float *t0, *t1, *t2, *t3;
+ t0 = vert[ face->v1 ].co;
+ t1 = vert[ face->v2 ].co;
+ t2 = vert[ face->v3 ].co;
+ t3 = face->v4 ? vert[ face->v4].co : NULL;
+
+
+ do
+ {
+ float nearest_tmp[3], dist;
+ int vertex, edge;
+
+ dist = nearest_point_in_tri_surface(t0, t1, t2, co, &vertex, &edge, nearest_tmp);
+ if(dist < nearest->dist)
+ {
+ nearest->index = index;
+ nearest->dist = dist;
+ VECCOPY(nearest->co, nearest_tmp);
+ CalcNormFloat(t0, t1, t2, nearest->no);
+ }
+
+ t1 = t2;
+ t2 = t3;
+ t3 = NULL;
+
+ } while(t2);
+}
+
+// Callback to bvh tree raycast. The tree must bust have been built using bvhtree_from_mesh_faces.
+// userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree.
+static void mesh_faces_spherecast(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
+{
+ const BVHTreeFromMesh *data = (BVHTreeFromMesh*) userdata;
+ MVert *vert = data->vert;
+ MFace *face = data->face + index;
+
+ float *t0, *t1, *t2, *t3;
+ t0 = vert[ face->v1 ].co;
+ t1 = vert[ face->v2 ].co;
+ t2 = vert[ face->v3 ].co;
+ t3 = face->v4 ? vert[ face->v4].co : NULL;
+
+
+ do
+ {
+ float dist;
+ if(data->sphere_radius == 0.0f)
+ dist = ray_tri_intersection(ray, hit->dist, t0, t1, t2);
+ else
+ dist = sphereray_tri_intersection(ray, data->sphere_radius, hit->dist, t0, t1, t2);
+
+ if(dist >= 0 && dist < hit->dist)
+ {
+ hit->index = index;
+ hit->dist = dist;
+ VECADDFAC(hit->co, ray->origin, ray->direction, dist);
+
+ CalcNormFloat(t0, t1, t2, hit->no);
+ }
+
+ t1 = t2;
+ t2 = t3;
+ t3 = NULL;
+
+ } while(t2);
+}
+
+/*
+ * BVH builders
+ */
+// Builds a bvh tree.. where nodes are the vertexs of the given mesh
+void bvhtree_from_mesh_verts(BVHTreeFromMesh *data, DerivedMesh *mesh, float epsilon, int tree_type, int axis)
+{
+ int i;
+ int numVerts= mesh->getNumVerts(mesh);
+ MVert *vert = mesh->getVertDataArray(mesh, CD_MVERT);
+ BVHTree *tree = NULL;
+
+ memset(data, 0, sizeof(*data));
+
+ if(vert == NULL)
+ {
+ printf("bvhtree cant be build: cant get a vertex array");
+ return;
+ }
+
+ tree = BLI_bvhtree_new(numVerts, epsilon, tree_type, axis);
+ if(tree != NULL)
+ {
+ for(i = 0; i < numVerts; i++)
+ BLI_bvhtree_insert(tree, i, vert[i].co, 1);
+
+ BLI_bvhtree_balance(tree);
+
+ data->tree = tree;
+
+ //a NULL nearest callback works fine
+ //remeber the min distance to point is the same as the min distance to BV of point
+ data->nearest_callback = NULL;
+ data->raycast_callback = NULL;
+
+ data->mesh = mesh;
+ data->vert = mesh->getVertDataArray(mesh, CD_MVERT);
+ data->face = mesh->getFaceDataArray(mesh, CD_MFACE);
+
+ data->sphere_radius = epsilon;
+ }
+}
+
+// Builds a bvh tree.. where nodes are the faces of the given mesh.
+void bvhtree_from_mesh_faces(BVHTreeFromMesh *data, DerivedMesh *mesh, float epsilon, int tree_type, int axis)
+{
+ int i;
+ int numFaces= mesh->getNumFaces(mesh);
+ MVert *vert = mesh->getVertDataArray(mesh, CD_MVERT);
+ MFace *face = mesh->getFaceDataArray(mesh, CD_MFACE);
+ BVHTree *tree = NULL;
+
+ memset(data, 0, sizeof(*data));
+
+ if(vert == NULL && face == NULL)
+ {
+ printf("bvhtree cant be build: cant get a vertex/face array");
+ return;
+ }
+
+ /* Create a bvh-tree of the given target */
+ tree = BLI_bvhtree_new(numFaces, epsilon, tree_type, axis);
+ if(tree != NULL)
+ {
+ for(i = 0; i < numFaces; i++)
+ {
+ float co[4][3];
+ VECCOPY(co[0], vert[ face[i].v1 ].co);
+ VECCOPY(co[1], vert[ face[i].v2 ].co);
+ VECCOPY(co[2], vert[ face[i].v3 ].co);
+ if(face[i].v4)
+ VECCOPY(co[3], vert[ face[i].v4 ].co);
+
+ BLI_bvhtree_insert(tree, i, co[0], face[i].v4 ? 4 : 3);
+ }
+ BLI_bvhtree_balance(tree);
+
+ data->tree = tree;
+ data->nearest_callback = mesh_faces_nearest_point;
+ data->raycast_callback = mesh_faces_spherecast;
+
+ data->mesh = mesh;
+ data->vert = mesh->getVertDataArray(mesh, CD_MVERT);
+ data->face = mesh->getFaceDataArray(mesh, CD_MFACE);
+
+ data->sphere_radius = epsilon;
+ }
+}
+
+// Frees data allocated by a call to bvhtree_from_mesh_*.
+void free_bvhtree_from_mesh(struct BVHTreeFromMesh *data)
+{
+ if(data->tree)
+ {
+ BLI_bvhtree_free(data->tree);
+ memset( data, 0, sizeof(data) );
+ }
+}
+
+
diff --git a/source/blender/blenkernel/intern/cdderivedmesh.c b/source/blender/blenkernel/intern/cdderivedmesh.c
index 6a856307916..2c1b5ced614 100644
--- a/source/blender/blenkernel/intern/cdderivedmesh.c
+++ b/source/blender/blenkernel/intern/cdderivedmesh.c
@@ -52,11 +52,16 @@
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
+#include "DNA_object_fluidsim.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
#include "MEM_guardedalloc.h"
+#include "GPU_draw.h"
+#include "GPU_extensions.h"
+#include "GPU_material.h"
+
#include <string.h>
#include <limits.h>
@@ -116,7 +121,7 @@ static void cdDM_copyEdgeArray(DerivedMesh *dm, MEdge *edge_r)
memcpy(edge_r, cddm->medge, sizeof(*edge_r) * dm->numEdgeData);
}
-void cdDM_copyFaceArray(DerivedMesh *dm, MFace *face_r)
+static void cdDM_copyFaceArray(DerivedMesh *dm, MFace *face_r)
{
CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
memcpy(face_r, cddm->mface, sizeof(*face_r) * dm->numFaceData);
@@ -242,7 +247,7 @@ static void cdDM_drawLooseEdges(DerivedMesh *dm)
glEnd();
}
-static void cdDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int))
+static void cdDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int, void *attribs))
{
CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
MVert *mvert = cddm->mvert;
@@ -270,7 +275,7 @@ static void cdDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int))
|| new_shademodel != shademodel) {
glEnd();
- drawCurrentMat = setMaterial(matnr = new_matnr);
+ drawCurrentMat = setMaterial(matnr = new_matnr, NULL);
glShadeModel(shademodel = new_shademodel);
glBegin(glmode = new_glmode);
@@ -555,6 +560,134 @@ static void cdDM_drawMappedFacesTex(DerivedMesh *dm, int (*setDrawOptions)(void
cdDM_drawFacesTex_common(dm, NULL, setDrawOptions, userData);
}
+static void cdDM_drawMappedFacesGLSL(DerivedMesh *dm, int (*setMaterial)(int, void *attribs), int (*setDrawOptions)(void *userData, int index), void *userData)
+{
+ CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
+ GPUVertexAttribs gattribs;
+ DMVertexAttribs attribs;
+ MVert *mvert = cddm->mvert;
+ MFace *mface = cddm->mface;
+ MTFace *tf = dm->getFaceDataArray(dm, CD_MTFACE);
+ float (*nors)[3] = dm->getFaceDataArray(dm, CD_NORMAL);
+ int a, b, dodraw, smoothnormal, matnr, new_matnr;
+ int transp, new_transp, orig_transp;
+ int orig, *index = dm->getFaceDataArray(dm, CD_ORIGINDEX);
+
+ matnr = -1;
+ smoothnormal = 0;
+ dodraw = 0;
+ transp = GPU_get_material_blend_mode();
+ orig_transp = transp;
+
+ memset(&attribs, 0, sizeof(attribs));
+
+ glShadeModel(GL_SMOOTH);
+ glBegin(GL_QUADS);
+
+ for(a = 0; a < dm->numFaceData; a++, mface++) {
+ new_matnr = mface->mat_nr + 1;
+
+ if(new_matnr != matnr) {
+ glEnd();
+
+ dodraw = setMaterial(matnr = new_matnr, &gattribs);
+ if(dodraw)
+ DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
+
+ glBegin(GL_QUADS);
+ }
+
+ if(!dodraw) {
+ continue;
+ }
+ else if(setDrawOptions) {
+ orig = index[a];
+
+ if(orig == ORIGINDEX_NONE)
+ continue;
+ else if(!setDrawOptions(userData, orig))
+ continue;
+ }
+
+ if(tf) {
+ new_transp = tf[a].transp;
+
+ if(new_transp != transp) {
+ glEnd();
+
+ if(new_transp == GPU_BLEND_SOLID && orig_transp != GPU_BLEND_SOLID)
+ GPU_set_material_blend_mode(orig_transp);
+ else
+ GPU_set_material_blend_mode(new_transp);
+ transp = new_transp;
+
+ glBegin(GL_QUADS);
+ }
+ }
+
+ smoothnormal = (mface->flag & ME_SMOOTH);
+
+ if(!smoothnormal) {
+ if(nors) {
+ glNormal3fv(nors[a]);
+ }
+ else {
+ /* TODO ideally a normal layer should always be available */
+ float nor[3];
+ if(mface->v4) {
+ CalcNormFloat4(mvert[mface->v1].co, mvert[mface->v2].co,
+ mvert[mface->v3].co, mvert[mface->v4].co,
+ nor);
+ } else {
+ CalcNormFloat(mvert[mface->v1].co, mvert[mface->v2].co,
+ mvert[mface->v3].co, nor);
+ }
+ glNormal3fv(nor);
+ }
+ }
+
+#define PASSVERT(index, vert) { \
+ if(attribs.totorco) \
+ glVertexAttrib3fvARB(attribs.orco.glIndex, attribs.orco.array[index]); \
+ for(b = 0; b < attribs.tottface; b++) { \
+ MTFace *tf = &attribs.tface[b].array[a]; \
+ glVertexAttrib2fvARB(attribs.tface[b].glIndex, tf->uv[vert]); \
+ } \
+ for(b = 0; b < attribs.totmcol; b++) { \
+ MCol *cp = &attribs.mcol[b].array[a*4 + vert]; \
+ GLubyte col[4]; \
+ col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a; \
+ glVertexAttrib4ubvARB(attribs.mcol[b].glIndex, col); \
+ } \
+ if(attribs.tottang) { \
+ float *tang = attribs.tang.array[a*4 + vert]; \
+ glVertexAttrib3fvARB(attribs.tang.glIndex, tang); \
+ } \
+ if(smoothnormal) \
+ glNormal3sv(mvert[index].no); \
+ glVertex3fv(mvert[index].co); \
+}
+
+ PASSVERT(mface->v1, 0);
+ PASSVERT(mface->v2, 1);
+ PASSVERT(mface->v3, 2);
+ if(mface->v4)
+ PASSVERT(mface->v4, 3)
+ else
+ PASSVERT(mface->v3, 2)
+
+#undef PASSVERT
+ }
+ glEnd();
+
+ glShadeModel(GL_FLAT);
+}
+
+static void cdDM_drawFacesGLSL(DerivedMesh *dm, int (*setMaterial)(int, void *attribs))
+{
+ dm->drawMappedFacesGLSL(dm, setMaterial, NULL, NULL);
+}
+
static void cdDM_drawMappedEdges(DerivedMesh *dm, int (*setDrawOptions)(void *userData, int index), void *userData)
{
CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
@@ -712,8 +845,10 @@ static CDDerivedMesh *cdDM_create(const char *desc)
dm->drawFacesSolid = cdDM_drawFacesSolid;
dm->drawFacesColored = cdDM_drawFacesColored;
dm->drawFacesTex = cdDM_drawFacesTex;
+ dm->drawFacesGLSL = cdDM_drawFacesGLSL;
dm->drawMappedFaces = cdDM_drawMappedFaces;
dm->drawMappedFacesTex = cdDM_drawMappedFacesTex;
+ dm->drawMappedFacesGLSL = cdDM_drawMappedFacesGLSL;
dm->foreachMappedVert = cdDM_foreachMappedVert;
dm->foreachMappedEdge = cdDM_foreachMappedEdge;
@@ -731,6 +866,10 @@ DerivedMesh *CDDM_new(int numVerts, int numEdges, int numFaces)
DM_init(dm, numVerts, numEdges, numFaces);
+ CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, numVerts);
+ CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
+ CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numFaces);
+
CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL, numVerts);
CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numFaces);
@@ -746,18 +885,26 @@ DerivedMesh *CDDM_from_mesh(Mesh *mesh, Object *ob)
{
CDDerivedMesh *cddm = cdDM_create("CDDM_from_mesh dm");
DerivedMesh *dm = &cddm->dm;
- int i, *index;
+ int i, *index, alloctype;
- /* this does a referenced copy, the only new layers being ORIGINDEX */
+ /* this does a referenced copy, the only new layers being ORIGINDEX,
+ * with an exception for fluidsim */
DM_init(dm, mesh->totvert, mesh->totedge, mesh->totface);
+
+ CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, mesh->totvert);
+ CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, mesh->totedge);
+ CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, mesh->totface);
+
dm->deformedOnly = 1;
- CustomData_merge(&mesh->vdata, &dm->vertData, CD_MASK_MESH, CD_REFERENCE,
+ alloctype= CD_REFERENCE;
+
+ CustomData_merge(&mesh->vdata, &dm->vertData, CD_MASK_MESH, alloctype,
mesh->totvert);
- CustomData_merge(&mesh->edata, &dm->edgeData, CD_MASK_MESH, CD_REFERENCE,
+ CustomData_merge(&mesh->edata, &dm->edgeData, CD_MASK_MESH, alloctype,
mesh->totedge);
- CustomData_merge(&mesh->fdata, &dm->faceData, CD_MASK_MESH, CD_REFERENCE,
+ CustomData_merge(&mesh->fdata, &dm->faceData, CD_MASK_MESH, alloctype,
mesh->totface);
cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
@@ -833,6 +980,7 @@ DerivedMesh *CDDM_from_editmesh(EditMesh *em, Mesh *me)
mv->no[0] = eve->no[0] * 32767.0;
mv->no[1] = eve->no[1] * 32767.0;
mv->no[2] = eve->no[2] * 32767.0;
+ mv->bweight = (unsigned char) (eve->bweight * 255.0f);
mv->mat_nr = 0;
mv->flag = 0;
@@ -850,6 +998,7 @@ DerivedMesh *CDDM_from_editmesh(EditMesh *em, Mesh *me)
med->v1 = eed->v1->tmp.l;
med->v2 = eed->v2->tmp.l;
med->crease = (unsigned char) (eed->crease * 255.0f);
+ med->bweight = (unsigned char) (eed->bweight * 255.0f);
med->flag = ME_EDGEDRAW|ME_EDGERENDER;
if(eed->seam) med->flag |= ME_SEAM;
diff --git a/source/blender/blenkernel/intern/cloth.c b/source/blender/blenkernel/intern/cloth.c
new file mode 100644
index 00000000000..dbc94571cad
--- /dev/null
+++ b/source/blender/blenkernel/intern/cloth.c
@@ -0,0 +1,1290 @@
+/* cloth.c
+*
+*
+* ***** BEGIN GPL LICENSE BLOCK *****
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 2
+* of the License, or (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software Foundation,
+* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*
+* The Original Code is Copyright (C) Blender Foundation
+* All rights reserved.
+*
+* Contributor(s): Daniel Genrich
+*
+* ***** END GPL LICENSE BLOCK *****
+*/
+
+#include "MEM_guardedalloc.h"
+
+#include "BKE_cloth.h"
+
+#include "DNA_cloth_types.h"
+#include "DNA_mesh_types.h"
+#include "DNA_object_force.h"
+#include "DNA_scene_types.h"
+
+#include "BKE_deform.h"
+#include "BKE_DerivedMesh.h"
+#include "BKE_cdderivedmesh.h"
+#include "BKE_effect.h"
+#include "BKE_global.h"
+#include "BKE_object.h"
+#include "BKE_modifier.h"
+#include "BKE_utildefines.h"
+
+#include "BKE_pointcache.h"
+
+#include "BLI_kdopbvh.h"
+
+#ifdef _WIN32
+void tstart ( void )
+{}
+void tend ( void )
+{
+}
+double tval()
+{
+ return 0;
+}
+#else
+#include <sys/time.h>
+ static struct timeval _tstart, _tend;
+ static struct timezone tz;
+ void tstart ( void )
+{
+ gettimeofday ( &_tstart, &tz );
+}
+void tend ( void )
+{
+ gettimeofday ( &_tend,&tz );
+}
+double tval()
+{
+ double t1, t2;
+ t1 = ( double ) _tstart.tv_sec + ( double ) _tstart.tv_usec/ ( 1000*1000 );
+ t2 = ( double ) _tend.tv_sec + ( double ) _tend.tv_usec/ ( 1000*1000 );
+ return t2-t1;
+}
+#endif
+
+/* Our available solvers. */
+// 255 is the magic reserved number, so NEVER try to put 255 solvers in here!
+// 254 = MAX!
+static CM_SOLVER_DEF solvers [] =
+{
+ { "Implicit", CM_IMPLICIT, implicit_init, implicit_solver, implicit_free },
+ // { "Implicit C++", CM_IMPLICITCPP, implicitcpp_init, implicitcpp_solver, implicitcpp_free },
+};
+
+/* ********** cloth engine ******* */
+/* Prototypes for internal functions.
+*/
+static void cloth_to_object (Object *ob, ClothModifierData *clmd, DerivedMesh *dm);
+static void cloth_from_mesh ( Object *ob, ClothModifierData *clmd, DerivedMesh *dm );
+static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *dm, float framenr, int first);
+int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm );
+static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm );
+
+
+/******************************************************************************
+*
+* External interface called by modifier.c clothModifier functions.
+*
+******************************************************************************/
+/**
+ * cloth_init - creates a new cloth simulation.
+ *
+ * 1. create object
+ * 2. fill object with standard values or with the GUI settings if given
+ */
+void cloth_init ( ClothModifierData *clmd )
+{
+ /* Initialize our new data structure to reasonable values. */
+ clmd->sim_parms->gravity [0] = 0.0;
+ clmd->sim_parms->gravity [1] = 0.0;
+ clmd->sim_parms->gravity [2] = -9.81;
+ clmd->sim_parms->structural = 15.0;
+ clmd->sim_parms->shear = 15.0;
+ clmd->sim_parms->bending = 0.5;
+ clmd->sim_parms->Cdis = 5.0;
+ clmd->sim_parms->Cvi = 1.0;
+ clmd->sim_parms->mass = 0.3f;
+ clmd->sim_parms->stepsPerFrame = 5;
+ clmd->sim_parms->flags = 0;
+ clmd->sim_parms->solver_type = 0;
+ clmd->sim_parms->preroll = 0;
+ clmd->sim_parms->maxspringlen = 10;
+ clmd->sim_parms->vgroup_mass = 0;
+ clmd->sim_parms->avg_spring_len = 0.0;
+ clmd->sim_parms->presets = 2; /* cotton as start setting */
+ clmd->sim_parms->timescale = 1.0f; /* speed factor, describes how fast cloth moves */
+
+ clmd->coll_parms->self_friction = 5.0;
+ clmd->coll_parms->friction = 5.0;
+ clmd->coll_parms->loop_count = 2;
+ clmd->coll_parms->epsilon = 0.015f;
+ clmd->coll_parms->flags = CLOTH_COLLSETTINGS_FLAG_ENABLED;
+ clmd->coll_parms->collision_list = NULL;
+ clmd->coll_parms->self_loop_count = 1.0;
+ clmd->coll_parms->selfepsilon = 0.75;
+
+ /* These defaults are copied from softbody.c's
+ * softbody_calc_forces() function.
+ */
+ clmd->sim_parms->eff_force_scale = 1000.0;
+ clmd->sim_parms->eff_wind_scale = 250.0;
+
+ // also from softbodies
+ clmd->sim_parms->maxgoal = 1.0f;
+ clmd->sim_parms->mingoal = 0.0f;
+ clmd->sim_parms->defgoal = 0.0f;
+ clmd->sim_parms->goalspring = 1.0f;
+ clmd->sim_parms->goalfrict = 0.0f;
+}
+
+BVHTree *bvhselftree_build_from_cloth (ClothModifierData *clmd, float epsilon)
+{
+ unsigned int i;
+ BVHTree *bvhtree;
+ Cloth *cloth = clmd->clothObject;
+ ClothVertex *verts;
+ MFace *mfaces;
+ float co[12];
+
+ if(!clmd)
+ return NULL;
+
+ cloth = clmd->clothObject;
+
+ if(!cloth)
+ return NULL;
+
+ verts = cloth->verts;
+ mfaces = cloth->mfaces;
+
+ // in the moment, return zero if no faces there
+ if(!cloth->numverts)
+ return NULL;
+
+ // create quadtree with k=26
+ bvhtree = BLI_bvhtree_new(cloth->numverts, epsilon, 4, 6);
+
+ // fill tree
+ for(i = 0; i < cloth->numverts; i++, verts++)
+ {
+ VECCOPY(&co[0*3], verts->xold);
+
+ BLI_bvhtree_insert(bvhtree, i, co, 1);
+ }
+
+ // balance tree
+ BLI_bvhtree_balance(bvhtree);
+
+ return bvhtree;
+}
+
+BVHTree *bvhtree_build_from_cloth (ClothModifierData *clmd, float epsilon)
+{
+ unsigned int i;
+ BVHTree *bvhtree;
+ Cloth *cloth = clmd->clothObject;
+ ClothVertex *verts;
+ MFace *mfaces;
+ float co[12];
+
+ if(!clmd)
+ return NULL;
+
+ cloth = clmd->clothObject;
+
+ if(!cloth)
+ return NULL;
+
+ verts = cloth->verts;
+ mfaces = cloth->mfaces;
+
+ // in the moment, return zero if no faces there
+ if(!cloth->numfaces)
+ return NULL;
+
+ // create quadtree with k=26
+ bvhtree = BLI_bvhtree_new(cloth->numfaces, epsilon, 4, 26);
+
+ // fill tree
+ for(i = 0; i < cloth->numfaces; i++, mfaces++)
+ {
+ VECCOPY(&co[0*3], verts[mfaces->v1].xold);
+ VECCOPY(&co[1*3], verts[mfaces->v2].xold);
+ VECCOPY(&co[2*3], verts[mfaces->v3].xold);
+
+ if(mfaces->v4)
+ VECCOPY(&co[3*3], verts[mfaces->v4].xold);
+
+ BLI_bvhtree_insert(bvhtree, i, co, (mfaces->v4 ? 4 : 3));
+ }
+
+ // balance tree
+ BLI_bvhtree_balance(bvhtree);
+
+ return bvhtree;
+}
+
+void bvhtree_update_from_cloth(ClothModifierData *clmd, int moving)
+{
+ unsigned int i = 0;
+ Cloth *cloth = clmd->clothObject;
+ BVHTree *bvhtree = cloth->bvhtree;
+ ClothVertex *verts = cloth->verts;
+ MFace *mfaces;
+ float co[12], co_moving[12];
+ int ret = 0;
+
+ if(!bvhtree)
+ return;
+
+ mfaces = cloth->mfaces;
+
+ // update vertex position in bvh tree
+ if(verts && mfaces)
+ {
+ for(i = 0; i < cloth->numfaces; i++, mfaces++)
+ {
+ VECCOPY(&co[0*3], verts[mfaces->v1].txold);
+ VECCOPY(&co[1*3], verts[mfaces->v2].txold);
+ VECCOPY(&co[2*3], verts[mfaces->v3].txold);
+
+ if(mfaces->v4)
+ VECCOPY(&co[3*3], verts[mfaces->v4].txold);
+
+ // copy new locations into array
+ if(moving)
+ {
+ // update moving positions
+ VECCOPY(&co_moving[0*3], verts[mfaces->v1].tx);
+ VECCOPY(&co_moving[1*3], verts[mfaces->v2].tx);
+ VECCOPY(&co_moving[2*3], verts[mfaces->v3].tx);
+
+ if(mfaces->v4)
+ VECCOPY(&co_moving[3*3], verts[mfaces->v4].tx);
+
+ ret = BLI_bvhtree_update_node(bvhtree, i, co, co_moving, (mfaces->v4 ? 4 : 3));
+ }
+ else
+ {
+ ret = BLI_bvhtree_update_node(bvhtree, i, co, NULL, (mfaces->v4 ? 4 : 3));
+ }
+
+ // check if tree is already full
+ if(!ret)
+ break;
+ }
+
+ BLI_bvhtree_update_tree(bvhtree);
+ }
+}
+
+void bvhselftree_update_from_cloth(ClothModifierData *clmd, int moving)
+{
+ unsigned int i = 0;
+ Cloth *cloth = clmd->clothObject;
+ BVHTree *bvhtree = cloth->bvhselftree;
+ ClothVertex *verts = cloth->verts;
+ MFace *mfaces;
+ float co[12], co_moving[12];
+ int ret = 0;
+
+ if(!bvhtree)
+ return;
+
+ mfaces = cloth->mfaces;
+
+ // update vertex position in bvh tree
+ if(verts && mfaces)
+ {
+ for(i = 0; i < cloth->numverts; i++, verts++)
+ {
+ VECCOPY(&co[0*3], verts->txold);
+
+ // copy new locations into array
+ if(moving)
+ {
+ // update moving positions
+ VECCOPY(&co_moving[0*3], verts->tx);
+
+ ret = BLI_bvhtree_update_node(bvhtree, i, co, co_moving, 1);
+ }
+ else
+ {
+ ret = BLI_bvhtree_update_node(bvhtree, i, co, NULL, 1);
+ }
+
+ // check if tree is already full
+ if(!ret)
+ break;
+ }
+
+ BLI_bvhtree_update_tree(bvhtree);
+ }
+}
+
+int modifiers_indexInObject(Object *ob, ModifierData *md_seek);
+
+int cloth_read_cache(Object *ob, ClothModifierData *clmd, float framenr)
+{
+ PTCacheID pid;
+ PTCacheFile *pf;
+ Cloth *cloth = clmd->clothObject;
+ unsigned int a, ret = 1;
+
+ if(!cloth)
+ return 0;
+
+ BKE_ptcache_id_from_cloth(&pid, ob, clmd);
+ pf = BKE_ptcache_file_open(&pid, PTCACHE_FILE_READ, framenr);
+ if(pf) {
+ for(a = 0; a < cloth->numverts; a++) {
+ if(!BKE_ptcache_file_read_floats(pf, cloth->verts[a].x, 3)) {
+ ret = 0;
+ break;
+ }
+ if(!BKE_ptcache_file_read_floats(pf, cloth->verts[a].xconst, 3)) {
+ ret = 0;
+ break;
+ }
+ if(!BKE_ptcache_file_read_floats(pf, cloth->verts[a].v, 3)) {
+ ret = 0;
+ break;
+ }
+ }
+
+ BKE_ptcache_file_close(pf);
+ }
+ else
+ ret = 0;
+
+ return ret;
+}
+
+void cloth_clear_cache(Object *ob, ClothModifierData *clmd, float framenr)
+{
+ PTCacheID pid;
+
+ BKE_ptcache_id_from_cloth(&pid, ob, clmd);
+
+ // don't do anything as long as we're in editmode!
+ if(pid.cache->flag & PTCACHE_BAKE_EDIT_ACTIVE)
+ return;
+
+ BKE_ptcache_id_clear(&pid, PTCACHE_CLEAR_AFTER, framenr);
+}
+
+void cloth_write_cache(Object *ob, ClothModifierData *clmd, float framenr)
+{
+ Cloth *cloth = clmd->clothObject;
+ PTCacheID pid;
+ PTCacheFile *pf;
+ unsigned int a;
+
+ if(!cloth)
+ return;
+
+ BKE_ptcache_id_from_cloth(&pid, ob, clmd);
+ pf = BKE_ptcache_file_open(&pid, PTCACHE_FILE_WRITE, framenr);
+ if(!pf)
+ return;
+
+ for(a = 0; a < cloth->numverts; a++) {
+ BKE_ptcache_file_write_floats(pf, cloth->verts[a].x, 3);
+ BKE_ptcache_file_write_floats(pf, cloth->verts[a].xconst, 3);
+ BKE_ptcache_file_write_floats(pf, cloth->verts[a].v, 3);
+ }
+
+ BKE_ptcache_file_close(pf);
+}
+
+static int do_init_cloth(Object *ob, ClothModifierData *clmd, DerivedMesh *result, int framenr)
+{
+ PointCache *cache;
+
+ cache= clmd->point_cache;
+
+ /* initialize simulation data if it didn't exist already */
+ if(clmd->clothObject == NULL) {
+ if(!cloth_from_object(ob, clmd, result, framenr, 1)) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ return 0;
+ }
+
+ if(clmd->clothObject == NULL) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ return 0;
+ }
+
+ implicit_set_positions(clmd);
+ }
+
+ return 1;
+}
+
+static int do_step_cloth(Object *ob, ClothModifierData *clmd, DerivedMesh *result, int framenr)
+{
+ ClothVertex *verts = NULL;
+ Cloth *cloth;
+ ListBase *effectors = NULL;
+ MVert *mvert;
+ int i, ret = 0;
+
+ /* simulate 1 frame forward */
+ cloth = clmd->clothObject;
+ verts = cloth->verts;
+ mvert = result->getVertArray(result);
+
+ /* force any pinned verts to their constrained location. */
+ for(i = 0; i < clmd->clothObject->numverts; i++, verts++) {
+ /* save the previous position. */
+ VECCOPY(verts->xold, verts->xconst);
+ VECCOPY(verts->txold, verts->x);
+
+ /* Get the current position. */
+ VECCOPY(verts->xconst, mvert[i].co);
+ Mat4MulVecfl(ob->obmat, verts->xconst);
+ }
+
+ tstart();
+
+ /* call the solver. */
+ if(solvers [clmd->sim_parms->solver_type].solver)
+ ret = solvers[clmd->sim_parms->solver_type].solver(ob, framenr, clmd, effectors);
+
+ tend();
+
+ // printf ( "%f\n", ( float ) tval() );
+
+ return ret;
+}
+
+/************************************************
+ * clothModifier_do - main simulation function
+************************************************/
+DerivedMesh *clothModifier_do(ClothModifierData *clmd, Object *ob, DerivedMesh *dm, int useRenderParams, int isFinalCalc)
+{
+ DerivedMesh *result;
+ PointCache *cache;
+ PTCacheID pid;
+ float timescale;
+ int framedelta, framenr, startframe, endframe;
+
+ framenr= (int)G.scene->r.cfra;
+ cache= clmd->point_cache;
+ result = CDDM_copy(dm);
+
+ BKE_ptcache_id_from_cloth(&pid, ob, clmd);
+ BKE_ptcache_id_time(&pid, framenr, &startframe, &endframe, &timescale);
+ clmd->sim_parms->timescale= timescale;
+
+ if(!result) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ return dm;
+ }
+
+ /* verify we still have the same number of vertices, if not do nothing.
+ * note that this should only happen if the number of vertices changes
+ * during an animation due to a preceding modifier, this should not
+ * happen because of object changes! */
+ if(clmd->clothObject) {
+ if(result->getNumVerts(result) != clmd->clothObject->numverts) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ return result;
+ }
+ }
+
+ // unused in the moment, calculated seperately in implicit.c
+ clmd->sim_parms->dt = clmd->sim_parms->timescale / clmd->sim_parms->stepsPerFrame;
+
+ /* handle continuous simulation with the play button */
+ if(BKE_ptcache_get_continue_physics()) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+
+ /* do simulation */
+ if(!do_init_cloth(ob, clmd, result, framenr))
+ return result;
+
+ do_step_cloth(ob, clmd, result, framenr);
+ cloth_to_object(ob, clmd, result);
+
+ return result;
+ }
+
+ /* simulation is only active during a specific period */
+ if(framenr < startframe) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ return result;
+ }
+ else if(framenr > endframe) {
+ framenr= endframe;
+ }
+
+ if(cache->flag & PTCACHE_SIMULATION_VALID)
+ framedelta= framenr - cache->simframe;
+ else
+ framedelta= -1;
+
+ /* initialize simulation data if it didn't exist already */
+ if(!do_init_cloth(ob, clmd, result, framenr))
+ return result;
+
+ /* try to read from cache */
+ if(cloth_read_cache(ob, clmd, framenr)) {
+ cache->flag |= PTCACHE_SIMULATION_VALID;
+ cache->simframe= framenr;
+
+ implicit_set_positions(clmd);
+ cloth_to_object (ob, clmd, result);
+
+ return result;
+ }
+ else if(ob->id.lib || (cache->flag & PTCACHE_BAKED)) {
+ /* if baked and nothing in cache, do nothing */
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ return result;
+ }
+
+ if(framenr == startframe) {
+ cache->flag |= PTCACHE_SIMULATION_VALID;
+ cache->simframe= framenr;
+
+ /* don't write cache on first frame, but on second frame write
+ * cache for frame 1 and 2 */
+ }
+ else if(framedelta == 1) {
+ /* if on second frame, write cache for first frame */
+ if(framenr == startframe+1)
+ cloth_write_cache(ob, clmd, startframe);
+
+ /* do simulation */
+ cache->flag |= PTCACHE_SIMULATION_VALID;
+ cache->simframe= framenr;
+
+ if(!do_step_cloth(ob, clmd, result, framenr)) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ }
+ else
+ cloth_write_cache(ob, clmd, framenr);
+
+ cloth_to_object (ob, clmd, result);
+ }
+ else {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ }
+
+ return result;
+}
+
+/* frees all */
+void cloth_free_modifier ( Object *ob, ClothModifierData *clmd )
+{
+ Cloth *cloth = NULL;
+
+ if ( !clmd )
+ return;
+
+ cloth = clmd->clothObject;
+
+
+ if ( cloth )
+ {
+ // If our solver provides a free function, call it
+ if ( solvers [clmd->sim_parms->solver_type].free )
+ {
+ solvers [clmd->sim_parms->solver_type].free ( clmd );
+ }
+
+ // Free the verts.
+ if ( cloth->verts != NULL )
+ MEM_freeN ( cloth->verts );
+
+ cloth->verts = NULL;
+ cloth->numverts = 0;
+
+ // Free the springs.
+ if ( cloth->springs != NULL )
+ {
+ LinkNode *search = cloth->springs;
+ while(search)
+ {
+ ClothSpring *spring = search->link;
+
+ MEM_freeN ( spring );
+ search = search->next;
+ }
+ BLI_linklist_free(cloth->springs, NULL);
+
+ cloth->springs = NULL;
+ }
+
+ cloth->springs = NULL;
+ cloth->numsprings = 0;
+
+ // free BVH collision tree
+ if ( cloth->bvhtree )
+ BLI_bvhtree_free ( cloth->bvhtree );
+
+ if ( cloth->bvhselftree )
+ BLI_bvhtree_free ( cloth->bvhselftree );
+
+ // we save our faces for collision objects
+ if ( cloth->mfaces )
+ MEM_freeN ( cloth->mfaces );
+
+ if(cloth->edgehash)
+ BLI_edgehash_free ( cloth->edgehash, NULL );
+
+
+ /*
+ if(clmd->clothObject->facemarks)
+ MEM_freeN(clmd->clothObject->facemarks);
+ */
+ MEM_freeN ( cloth );
+ clmd->clothObject = NULL;
+ }
+}
+
+/* frees all */
+void cloth_free_modifier_extern ( ClothModifierData *clmd )
+{
+ Cloth *cloth = NULL;
+ if(G.rt > 0)
+ printf("cloth_free_modifier_extern\n");
+
+ if ( !clmd )
+ return;
+
+ cloth = clmd->clothObject;
+
+ if ( cloth )
+ {
+ if(G.rt > 0)
+ printf("cloth_free_modifier_extern in\n");
+
+ // If our solver provides a free function, call it
+ if ( solvers [clmd->sim_parms->solver_type].free )
+ {
+ solvers [clmd->sim_parms->solver_type].free ( clmd );
+ }
+
+ // Free the verts.
+ if ( cloth->verts != NULL )
+ MEM_freeN ( cloth->verts );
+
+ cloth->verts = NULL;
+ cloth->numverts = 0;
+
+ // Free the springs.
+ if ( cloth->springs != NULL )
+ {
+ LinkNode *search = cloth->springs;
+ while(search)
+ {
+ ClothSpring *spring = search->link;
+
+ MEM_freeN ( spring );
+ search = search->next;
+ }
+ BLI_linklist_free(cloth->springs, NULL);
+
+ cloth->springs = NULL;
+ }
+
+ cloth->springs = NULL;
+ cloth->numsprings = 0;
+
+ // free BVH collision tree
+ if ( cloth->bvhtree )
+ BLI_bvhtree_free ( cloth->bvhtree );
+
+ if ( cloth->bvhselftree )
+ BLI_bvhtree_free ( cloth->bvhselftree );
+
+ // we save our faces for collision objects
+ if ( cloth->mfaces )
+ MEM_freeN ( cloth->mfaces );
+
+ if(cloth->edgehash)
+ BLI_edgehash_free ( cloth->edgehash, NULL );
+
+
+ /*
+ if(clmd->clothObject->facemarks)
+ MEM_freeN(clmd->clothObject->facemarks);
+ */
+ MEM_freeN ( cloth );
+ clmd->clothObject = NULL;
+ }
+}
+
+/******************************************************************************
+*
+* Internal functions.
+*
+******************************************************************************/
+
+/**
+ * cloth_to_object - copies the deformed vertices to the object.
+ *
+ **/
+static void cloth_to_object (Object *ob, ClothModifierData *clmd, DerivedMesh *dm)
+{
+ unsigned int i = 0;
+ MVert *mvert = NULL;
+ unsigned int numverts;
+ Cloth *cloth = clmd->clothObject;
+
+ if (clmd->clothObject) {
+ /* inverse matrix is not uptodate... */
+ Mat4Invert (ob->imat, ob->obmat);
+
+ mvert = CDDM_get_verts(dm);
+ numverts = dm->getNumVerts(dm);
+
+ for (i = 0; i < numverts; i++)
+ {
+ VECCOPY (mvert[i].co, cloth->verts[i].x);
+ Mat4MulVecfl (ob->imat, mvert[i].co); /* cloth is in global coords */
+ }
+ }
+}
+
+
+/**
+ * cloth_apply_vgroup - applies a vertex group as specified by type
+ *
+ **/
+/* can be optimized to do all groups in one loop */
+static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm )
+{
+ int i = 0;
+ int j = 0;
+ MDeformVert *dvert = NULL;
+ Cloth *clothObj = NULL;
+ int numverts = dm->getNumVerts ( dm );
+ float goalfac = 0;
+ ClothVertex *verts = NULL;
+
+ clothObj = clmd->clothObject;
+
+ if ( !dm )
+ return;
+
+ numverts = dm->getNumVerts ( dm );
+
+ verts = clothObj->verts;
+
+ if (((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SCALING ) ||
+ (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )) &&
+ ((clmd->sim_parms->vgroup_mass>0) ||
+ (clmd->sim_parms->vgroup_struct>0)||
+ (clmd->sim_parms->vgroup_bend>0)))
+ {
+ for ( i = 0; i < numverts; i++, verts++ )
+ {
+ dvert = dm->getVertData ( dm, i, CD_MDEFORMVERT );
+ if ( dvert )
+ {
+ for ( j = 0; j < dvert->totweight; j++ )
+ {
+ if (( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_mass-1)) && (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL ))
+ {
+ verts->goal = dvert->dw [j].weight;
+ goalfac= 1.0f;
+
+ /*
+ // Kicking goal factor to simplify things...who uses that anyway?
+ // ABS ( clmd->sim_parms->maxgoal - clmd->sim_parms->mingoal );
+ */
+
+ verts->goal = ( float ) pow ( verts->goal , 4.0f );
+ if ( verts->goal >=SOFTGOALSNAP )
+ {
+ verts->flags |= CLOTH_VERT_FLAG_PINNED;
+ }
+ }
+
+ if (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SCALING )
+ {
+ if( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_struct-1))
+ {
+ verts->struct_stiff = dvert->dw [j].weight;
+ verts->shear_stiff = dvert->dw [j].weight;
+ }
+
+ if( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_bend-1))
+ {
+ verts->bend_stiff = dvert->dw [j].weight;
+ }
+ }
+ /*
+ // for later
+ if( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_weight-1))
+ {
+ verts->mass = dvert->dw [j].weight;
+ }
+ */
+ }
+ }
+ }
+ }
+}
+
+static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *dm, float framenr, int first)
+{
+ int i = 0;
+ MVert *mvert = NULL;
+ ClothVertex *verts = NULL;
+ float tnull[3] = {0,0,0};
+ Cloth *cloth = NULL;
+ float maxdist = 0;
+
+ // If we have a clothObject, free it.
+ if ( clmd->clothObject != NULL )
+ {
+ cloth_free_modifier ( ob, clmd );
+ if(G.rt > 0)
+ printf("cloth_free_modifier cloth_from_object\n");
+ }
+
+ // Allocate a new cloth object.
+ clmd->clothObject = MEM_callocN ( sizeof ( Cloth ), "cloth" );
+ if ( clmd->clothObject )
+ {
+ clmd->clothObject->old_solver_type = 255;
+ // clmd->clothObject->old_collision_type = 255;
+ cloth = clmd->clothObject;
+ clmd->clothObject->edgehash = NULL;
+ }
+ else if ( !clmd->clothObject )
+ {
+ modifier_setError ( & ( clmd->modifier ), "Out of memory on allocating clmd->clothObject." );
+ return 0;
+ }
+
+ // mesh input objects need DerivedMesh
+ if ( !dm )
+ return 0;
+
+ cloth_from_mesh ( ob, clmd, dm );
+
+ // create springs
+ clmd->clothObject->springs = NULL;
+ clmd->clothObject->numsprings = -1;
+
+ mvert = dm->getVertArray ( dm );
+ verts = clmd->clothObject->verts;
+
+ // set initial values
+ for ( i = 0; i < dm->getNumVerts(dm); i++, verts++ )
+ {
+ if(first)
+ {
+ VECCOPY ( verts->x, mvert[i].co );
+ Mat4MulVecfl ( ob->obmat, verts->x );
+ }
+
+ /* no GUI interface yet */
+ verts->mass = clmd->sim_parms->mass;
+ verts->impulse_count = 0;
+
+ if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )
+ verts->goal= clmd->sim_parms->defgoal;
+ else
+ verts->goal= 0.0f;
+
+ verts->flags = 0;
+ VECCOPY ( verts->xold, verts->x );
+ VECCOPY ( verts->xconst, verts->x );
+ VECCOPY ( verts->txold, verts->x );
+ VECCOPY ( verts->tx, verts->x );
+ VecMulf ( verts->v, 0.0f );
+
+ verts->impulse_count = 0;
+ VECCOPY ( verts->impulse, tnull );
+ }
+
+ // apply / set vertex groups
+ // has to be happen before springs are build!
+ cloth_apply_vgroup (clmd, dm);
+
+ if ( !cloth_build_springs ( clmd, dm ) )
+ {
+ cloth_free_modifier ( ob, clmd );
+ modifier_setError ( & ( clmd->modifier ), "Can't build springs." );
+ printf("cloth_free_modifier cloth_build_springs\n");
+ return 0;
+ }
+
+ for ( i = 0; i < dm->getNumVerts(dm); i++)
+ {
+ if((!(cloth->verts[i].flags & CLOTH_VERT_FLAG_PINNED)) && (cloth->verts[i].goal > ALMOST_ZERO))
+ {
+ cloth_add_spring (clmd, i, i, 0.0, CLOTH_SPRING_TYPE_GOAL);
+ }
+ }
+
+ // init our solver
+ if ( solvers [clmd->sim_parms->solver_type].init ) {
+ solvers [clmd->sim_parms->solver_type].init ( ob, clmd );
+ }
+
+ if(!first)
+ implicit_set_positions(clmd);
+
+ clmd->clothObject->bvhtree = bvhtree_build_from_cloth ( clmd, clmd->coll_parms->epsilon );
+
+ for(i = 0; i < dm->getNumVerts(dm); i++)
+ {
+ maxdist = MAX2(maxdist, clmd->coll_parms->selfepsilon* ( cloth->verts[i].avg_spring_len*2.0));
+ }
+
+ clmd->clothObject->bvhselftree = bvhselftree_build_from_cloth ( clmd, maxdist );
+
+ return 1;
+}
+
+static void cloth_from_mesh ( Object *ob, ClothModifierData *clmd, DerivedMesh *dm )
+{
+ unsigned int numverts = dm->getNumVerts ( dm );
+ unsigned int numfaces = dm->getNumFaces ( dm );
+ MFace *mface = CDDM_get_faces(dm);
+ unsigned int i = 0;
+
+ /* Allocate our vertices. */
+ clmd->clothObject->numverts = numverts;
+ clmd->clothObject->verts = MEM_callocN ( sizeof ( ClothVertex ) * clmd->clothObject->numverts, "clothVertex" );
+ if ( clmd->clothObject->verts == NULL )
+ {
+ cloth_free_modifier ( ob, clmd );
+ modifier_setError ( & ( clmd->modifier ), "Out of memory on allocating clmd->clothObject->verts." );
+ printf("cloth_free_modifier clmd->clothObject->verts\n");
+ return;
+ }
+
+ // save face information
+ clmd->clothObject->numfaces = numfaces;
+ clmd->clothObject->mfaces = MEM_callocN ( sizeof ( MFace ) * clmd->clothObject->numfaces, "clothMFaces" );
+ if ( clmd->clothObject->mfaces == NULL )
+ {
+ cloth_free_modifier ( ob, clmd );
+ modifier_setError ( & ( clmd->modifier ), "Out of memory on allocating clmd->clothObject->mfaces." );
+ printf("cloth_free_modifier clmd->clothObject->mfaces\n");
+ return;
+ }
+ for ( i = 0; i < numfaces; i++ )
+ memcpy ( &clmd->clothObject->mfaces[i], &mface[i], sizeof ( MFace ) );
+
+ /* Free the springs since they can't be correct if the vertices
+ * changed.
+ */
+ if ( clmd->clothObject->springs != NULL )
+ MEM_freeN ( clmd->clothObject->springs );
+
+}
+
+/***************************************************************************************
+* SPRING NETWORK BUILDING IMPLEMENTATION BEGIN
+***************************************************************************************/
+
+// be carefull: implicit solver has to be resettet when using this one!
+// --> only for implicit handling of this spring!
+int cloth_add_spring ( ClothModifierData *clmd, unsigned int indexA, unsigned int indexB, float restlength, int spring_type)
+{
+ Cloth *cloth = clmd->clothObject;
+ ClothSpring *spring = NULL;
+
+ if(cloth)
+ {
+ // TODO: look if this spring is already there
+
+ spring = ( ClothSpring * ) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
+
+ if(!spring)
+ return 0;
+
+ spring->ij = indexA;
+ spring->kl = indexB;
+ spring->restlen = restlength;
+ spring->type = spring_type;
+ spring->flags = 0;
+ spring->stiffness = 0;
+
+ cloth->numsprings++;
+
+ BLI_linklist_prepend ( &cloth->springs, spring );
+
+ return 1;
+ }
+ return 0;
+}
+
+void cloth_free_errorsprings(Cloth *cloth, EdgeHash *edgehash, LinkNode **edgelist)
+{
+ unsigned int i = 0;
+
+ if ( cloth->springs != NULL )
+ {
+ LinkNode *search = cloth->springs;
+ while(search)
+ {
+ ClothSpring *spring = search->link;
+
+ MEM_freeN ( spring );
+ search = search->next;
+ }
+ BLI_linklist_free(cloth->springs, NULL);
+
+ cloth->springs = NULL;
+ }
+
+ if(edgelist)
+ {
+ for ( i = 0; i < cloth->numverts; i++ )
+ {
+ BLI_linklist_free ( edgelist[i],NULL );
+ }
+
+ MEM_freeN ( edgelist );
+ }
+
+ if(cloth->edgehash)
+ BLI_edgehash_free ( cloth->edgehash, NULL );
+}
+
+int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm )
+{
+ Cloth *cloth = clmd->clothObject;
+ ClothSpring *spring = NULL, *tspring = NULL, *tspring2 = NULL;
+ unsigned int struct_springs = 0, shear_springs=0, bend_springs = 0;
+ int i = 0;
+ int numverts = dm->getNumVerts ( dm );
+ int numedges = dm->getNumEdges ( dm );
+ int numfaces = dm->getNumFaces ( dm );
+ MEdge *medge = CDDM_get_edges ( dm );
+ MFace *mface = CDDM_get_faces ( dm );
+ int index2 = 0; // our second vertex index
+ LinkNode **edgelist = NULL;
+ EdgeHash *edgehash = NULL;
+ LinkNode *search = NULL, *search2 = NULL;
+ float temp[3];
+
+ // error handling
+ if ( numedges==0 )
+ return 0;
+
+ cloth->springs = NULL;
+
+ edgelist = MEM_callocN ( sizeof ( LinkNode * ) * numverts, "cloth_edgelist_alloc" );
+
+ if(!edgelist)
+ return 0;
+
+ for ( i = 0; i < numverts; i++ )
+ {
+ edgelist[i] = NULL;
+ }
+
+ if ( cloth->springs )
+ MEM_freeN ( cloth->springs );
+
+ // create spring network hash
+ edgehash = BLI_edgehash_new();
+
+ // structural springs
+ for ( i = 0; i < numedges; i++ )
+ {
+ spring = ( ClothSpring * ) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
+
+ if ( spring )
+ {
+ spring->ij = MIN2(medge[i].v1, medge[i].v2);
+ spring->kl = MAX2(medge[i].v2, medge[i].v1);
+ VECSUB ( temp, cloth->verts[spring->kl].x, cloth->verts[spring->ij].x );
+ spring->restlen = sqrt ( INPR ( temp, temp ) );
+ clmd->sim_parms->avg_spring_len += spring->restlen;
+ cloth->verts[spring->ij].avg_spring_len += spring->restlen;
+ cloth->verts[spring->kl].avg_spring_len += spring->restlen;
+ cloth->verts[spring->ij].spring_count++;
+ cloth->verts[spring->kl].spring_count++;
+ spring->type = CLOTH_SPRING_TYPE_STRUCTURAL;
+ spring->flags = 0;
+ spring->stiffness = (cloth->verts[spring->kl].struct_stiff + cloth->verts[spring->ij].struct_stiff) / 2.0;
+ struct_springs++;
+
+ BLI_linklist_prepend ( &cloth->springs, spring );
+ }
+ else
+ {
+ cloth_free_errorsprings(cloth, edgehash, edgelist);
+ return 0;
+ }
+ }
+
+ if(struct_springs > 0)
+ clmd->sim_parms->avg_spring_len /= struct_springs;
+
+ for(i = 0; i < numverts; i++)
+ {
+ cloth->verts[i].avg_spring_len = cloth->verts[i].avg_spring_len * 0.49 / ((float)cloth->verts[i].spring_count);
+ }
+
+ // shear springs
+ for ( i = 0; i < numfaces; i++ )
+ {
+ // triangle faces already have shear springs due to structural geometry
+ if ( !mface[i].v4 )
+ continue;
+
+ spring = ( ClothSpring *) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
+
+ if(!spring)
+ {
+ cloth_free_errorsprings(cloth, edgehash, edgelist);
+ return 0;
+ }
+
+ spring->ij = MIN2(mface[i].v1, mface[i].v3);
+ spring->kl = MAX2(mface[i].v3, mface[i].v1);
+ VECSUB ( temp, cloth->verts[spring->kl].x, cloth->verts[spring->ij].x );
+ spring->restlen = sqrt ( INPR ( temp, temp ) );
+ spring->type = CLOTH_SPRING_TYPE_SHEAR;
+ spring->stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0;
+
+ BLI_linklist_append ( &edgelist[spring->ij], spring );
+ BLI_linklist_append ( &edgelist[spring->kl], spring );
+ shear_springs++;
+
+ BLI_linklist_prepend ( &cloth->springs, spring );
+
+
+ // if ( mface[i].v4 ) --> Quad face
+ spring = ( ClothSpring * ) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
+
+ if(!spring)
+ {
+ cloth_free_errorsprings(cloth, edgehash, edgelist);
+ return 0;
+ }
+
+ spring->ij = MIN2(mface[i].v2, mface[i].v4);
+ spring->kl = MAX2(mface[i].v4, mface[i].v2);
+ VECSUB ( temp, cloth->verts[spring->kl].x, cloth->verts[spring->ij].x );
+ spring->restlen = sqrt ( INPR ( temp, temp ) );
+ spring->type = CLOTH_SPRING_TYPE_SHEAR;
+ spring->stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0;
+
+ BLI_linklist_append ( &edgelist[spring->ij], spring );
+ BLI_linklist_append ( &edgelist[spring->kl], spring );
+ shear_springs++;
+
+ BLI_linklist_prepend ( &cloth->springs, spring );
+ }
+
+ // bending springs
+ search2 = cloth->springs;
+ for ( i = struct_springs; i < struct_springs+shear_springs; i++ )
+ {
+ if ( !search2 )
+ break;
+
+ tspring2 = search2->link;
+ search = edgelist[tspring2->kl];
+ while ( search )
+ {
+ tspring = search->link;
+ index2 = ( ( tspring->ij==tspring2->kl ) ? ( tspring->kl ) : ( tspring->ij ) );
+
+ // check for existing spring
+ // check also if startpoint is equal to endpoint
+ if ( !BLI_edgehash_haskey ( edgehash, MIN2(tspring2->ij, index2), MAX2(tspring2->ij, index2) )
+ && ( index2!=tspring2->ij ) )
+ {
+ spring = ( ClothSpring * ) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
+
+ if(!spring)
+ {
+ cloth_free_errorsprings(cloth, edgehash, edgelist);
+ return 0;
+ }
+
+ spring->ij = MIN2(tspring2->ij, index2);
+ spring->kl = MAX2(tspring2->ij, index2);
+ VECSUB ( temp, cloth->verts[spring->kl].x, cloth->verts[spring->ij].x );
+ spring->restlen = sqrt ( INPR ( temp, temp ) );
+ spring->type = CLOTH_SPRING_TYPE_BENDING;
+ spring->stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0;
+ BLI_edgehash_insert ( edgehash, spring->ij, spring->kl, NULL );
+ bend_springs++;
+
+ BLI_linklist_prepend ( &cloth->springs, spring );
+ }
+ search = search->next;
+ }
+ search2 = search2->next;
+ }
+
+ /* insert other near springs in edgehash AFTER bending springs are calculated (for selfcolls) */
+ for ( i = 0; i < numedges; i++ ) // struct springs
+ BLI_edgehash_insert ( edgehash, MIN2(medge[i].v1, medge[i].v2), MAX2(medge[i].v2, medge[i].v1), NULL );
+
+ for ( i = 0; i < numfaces; i++ ) // edge springs
+ {
+ if(mface[i].v4)
+ {
+ BLI_edgehash_insert ( edgehash, MIN2(mface[i].v1, mface[i].v3), MAX2(mface[i].v3, mface[i].v1), NULL );
+
+ BLI_edgehash_insert ( edgehash, MIN2(mface[i].v2, mface[i].v4), MAX2(mface[i].v2, mface[i].v4), NULL );
+ }
+ }
+
+
+ cloth->numsprings = struct_springs + shear_springs + bend_springs;
+
+ if ( edgelist )
+ {
+ for ( i = 0; i < numverts; i++ )
+ {
+ BLI_linklist_free ( edgelist[i],NULL );
+ }
+
+ MEM_freeN ( edgelist );
+ }
+
+ cloth->edgehash = edgehash;
+
+ if(G.rt>0)
+ printf("avg_len: %f\n",clmd->sim_parms->avg_spring_len);
+
+ return 1;
+
+} /* cloth_build_springs */
+/***************************************************************************************
+* SPRING NETWORK BUILDING IMPLEMENTATION END
+***************************************************************************************/
+
diff --git a/source/blender/blenkernel/intern/collision.c b/source/blender/blenkernel/intern/collision.c
new file mode 100644
index 00000000000..9db3dda94eb
--- /dev/null
+++ b/source/blender/blenkernel/intern/collision.c
@@ -0,0 +1,1677 @@
+/* collision.c
+*
+*
+* ***** BEGIN GPL LICENSE BLOCK *****
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 2
+* of the License, or (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software Foundation,
+* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*
+* The Original Code is Copyright (C) Blender Foundation
+* All rights reserved.
+*
+* The Original Code is: all of this file.
+*
+* Contributor(s): none yet.
+*
+* ***** END GPL LICENSE BLOCK *****
+*/
+
+#include "MEM_guardedalloc.h"
+
+#include "BKE_cloth.h"
+
+#include "DNA_cloth_types.h"
+#include "DNA_group_types.h"
+#include "DNA_mesh_types.h"
+#include "DNA_object_types.h"
+#include "DNA_object_force.h"
+#include "DNA_scene_types.h"
+
+#include "BKE_DerivedMesh.h"
+#include "BKE_global.h"
+#include "BKE_mesh.h"
+#include "BKE_object.h"
+#include "BKE_modifier.h"
+#include "BKE_utildefines.h"
+#include "BKE_DerivedMesh.h"
+
+#include "Bullet-C-Api.h"
+
+#include "BLI_kdopbvh.h"
+#include "BKE_collision.h"
+
+
+/***********************************
+Collision modifier code start
+***********************************/
+
+/* step is limited from 0 (frame start position) to 1 (frame end position) */
+void collision_move_object ( CollisionModifierData *collmd, float step, float prevstep )
+{
+ float tv[3] = {0,0,0};
+ unsigned int i = 0;
+
+ for ( i = 0; i < collmd->numverts; i++ )
+ {
+ VECSUB ( tv, collmd->xnew[i].co, collmd->x[i].co );
+ VECADDS ( collmd->current_x[i].co, collmd->x[i].co, tv, prevstep );
+ VECADDS ( collmd->current_xnew[i].co, collmd->x[i].co, tv, step );
+ VECSUB ( collmd->current_v[i].co, collmd->current_xnew[i].co, collmd->current_x[i].co );
+ }
+ bvhtree_update_from_mvert ( collmd->bvhtree, collmd->mfaces, collmd->numfaces, collmd->current_x, collmd->current_xnew, collmd->numverts, 1 );
+}
+
+BVHTree *bvhtree_build_from_mvert ( MFace *mfaces, unsigned int numfaces, MVert *x, unsigned int numverts, float epsilon )
+{
+ BVHTree *tree;
+ float co[12];
+ int i;
+ MFace *tface = mfaces;
+
+ tree = BLI_bvhtree_new ( numfaces*2, epsilon, 4, 26 );
+
+ // fill tree
+ for ( i = 0; i < numfaces; i++, tface++ )
+ {
+ VECCOPY ( &co[0*3], x[tface->v1].co );
+ VECCOPY ( &co[1*3], x[tface->v2].co );
+ VECCOPY ( &co[2*3], x[tface->v3].co );
+ if ( tface->v4 )
+ VECCOPY ( &co[3*3], x[tface->v4].co );
+
+ BLI_bvhtree_insert ( tree, i, co, ( mfaces->v4 ? 4 : 3 ) );
+ }
+
+ // balance tree
+ BLI_bvhtree_balance ( tree );
+
+ return tree;
+}
+
+void bvhtree_update_from_mvert ( BVHTree * bvhtree, MFace *faces, int numfaces, MVert *x, MVert *xnew, int numverts, int moving )
+{
+ int i;
+ MFace *mfaces = faces;
+ float co[12], co_moving[12];
+ int ret = 0;
+
+ if ( !bvhtree )
+ return;
+
+ if ( x )
+ {
+ for ( i = 0; i < numfaces; i++, mfaces++ )
+ {
+ VECCOPY ( &co[0*3], x[mfaces->v1].co );
+ VECCOPY ( &co[1*3], x[mfaces->v2].co );
+ VECCOPY ( &co[2*3], x[mfaces->v3].co );
+ if ( mfaces->v4 )
+ VECCOPY ( &co[3*3], x[mfaces->v4].co );
+
+ // copy new locations into array
+ if ( moving && xnew )
+ {
+ // update moving positions
+ VECCOPY ( &co_moving[0*3], xnew[mfaces->v1].co );
+ VECCOPY ( &co_moving[1*3], xnew[mfaces->v2].co );
+ VECCOPY ( &co_moving[2*3], xnew[mfaces->v3].co );
+ if ( mfaces->v4 )
+ VECCOPY ( &co_moving[3*3], xnew[mfaces->v4].co );
+
+ ret = BLI_bvhtree_update_node ( bvhtree, i, co, co_moving, ( mfaces->v4 ? 4 : 3 ) );
+ }
+ else
+ {
+ ret = BLI_bvhtree_update_node ( bvhtree, i, co, NULL, ( mfaces->v4 ? 4 : 3 ) );
+ }
+
+ // check if tree is already full
+ if ( !ret )
+ break;
+ }
+
+ BLI_bvhtree_update_tree ( bvhtree );
+ }
+}
+
+/***********************************
+Collision modifier code end
+***********************************/
+
+/**
+* gsl_poly_solve_cubic -
+*
+* copied from SOLVE_CUBIC.C --> GSL
+*/
+
+#define mySWAP(a,b) do { double tmp = b ; b = a ; a = tmp ; } while(0)
+
+int
+gsl_poly_solve_cubic (double a, double b, double c,
+ double *x0, double *x1, double *x2)
+{
+ double q = (a * a - 3 * b);
+ double r = (2 * a * a * a - 9 * a * b + 27 * c);
+
+ double Q = q / 9;
+ double R = r / 54;
+
+ double Q3 = Q * Q * Q;
+ double R2 = R * R;
+
+ double CR2 = 729 * r * r;
+ double CQ3 = 2916 * q * q * q;
+
+ if (R == 0 && Q == 0)
+ {
+ *x0 = - a / 3 ;
+ *x1 = - a / 3 ;
+ *x2 = - a / 3 ;
+ return 3 ;
+ }
+ else if (CR2 == CQ3)
+ {
+ /* this test is actually R2 == Q3, written in a form suitable
+ for exact computation with integers */
+
+ /* Due to finite precision some double roots may be missed, and
+ considered to be a pair of complex roots z = x +/- epsilon i
+ close to the real axis. */
+
+ double sqrtQ = sqrt (Q);
+
+ if (R > 0)
+ {
+ *x0 = -2 * sqrtQ - a / 3;
+ *x1 = sqrtQ - a / 3;
+ *x2 = sqrtQ - a / 3;
+ }
+ else
+ {
+ *x0 = - sqrtQ - a / 3;
+ *x1 = - sqrtQ - a / 3;
+ *x2 = 2 * sqrtQ - a / 3;
+ }
+ return 3 ;
+ }
+ else if (CR2 < CQ3) /* equivalent to R2 < Q3 */
+ {
+ double sqrtQ = sqrt (Q);
+ double sqrtQ3 = sqrtQ * sqrtQ * sqrtQ;
+ double theta = acos (R / sqrtQ3);
+ double norm = -2 * sqrtQ;
+ *x0 = norm * cos (theta / 3) - a / 3;
+ *x1 = norm * cos ((theta + 2.0 * M_PI) / 3) - a / 3;
+ *x2 = norm * cos ((theta - 2.0 * M_PI) / 3) - a / 3;
+
+ /* Sort *x0, *x1, *x2 into increasing order */
+
+ if (*x0 > *x1)
+ mySWAP(*x0, *x1) ;
+
+ if (*x1 > *x2)
+ {
+ mySWAP(*x1, *x2) ;
+
+ if (*x0 > *x1)
+ mySWAP(*x0, *x1) ;
+ }
+
+ return 3;
+ }
+ else
+ {
+ double sgnR = (R >= 0 ? 1 : -1);
+ double A = -sgnR * pow (fabs (R) + sqrt (R2 - Q3), 1.0/3.0);
+ double B = Q / A ;
+ *x0 = A + B - a / 3;
+ return 1;
+ }
+}
+
+
+
+/**
+* gsl_poly_solve_quadratic
+*
+* copied from GSL
+*/
+int
+gsl_poly_solve_quadratic (double a, double b, double c,
+ double *x0, double *x1)
+{
+ double disc = b * b - 4 * a * c;
+
+ if (a == 0) /* Handle linear case */
+ {
+ if (b == 0)
+ {
+ return 0;
+ }
+ else
+ {
+ *x0 = -c / b;
+ return 1;
+ };
+ }
+
+ if (disc > 0)
+ {
+ if (b == 0)
+ {
+ double r = fabs (0.5 * sqrt (disc) / a);
+ *x0 = -r;
+ *x1 = r;
+ }
+ else
+ {
+ double sgnb = (b > 0 ? 1 : -1);
+ double temp = -0.5 * (b + sgnb * sqrt (disc));
+ double r1 = temp / a ;
+ double r2 = c / temp ;
+
+ if (r1 < r2)
+ {
+ *x0 = r1 ;
+ *x1 = r2 ;
+ }
+ else
+ {
+ *x0 = r2 ;
+ *x1 = r1 ;
+ }
+ }
+ return 2;
+ }
+ else if (disc == 0)
+ {
+ *x0 = -0.5 * b / a ;
+ *x1 = -0.5 * b / a ;
+ return 2 ;
+ }
+ else
+ {
+ return 0;
+ }
+}
+
+
+
+
+/*
+* See Bridson et al. "Robust Treatment of Collision, Contact and Friction for Cloth Animation"
+* page 4, left column
+*/
+int cloth_get_collision_time ( double a[3], double b[3], double c[3], double d[3], double e[3], double f[3], double solution[3] )
+{
+ int num_sols = 0;
+
+ // x^0 - checked
+ double g = a[0] * c[1] * e[2] - a[0] * c[2] * e[1] +
+ a[1] * c[2] * e[0] - a[1] * c[0] * e[2] +
+ a[2] * c[0] * e[1] - a[2] * c[1] * e[0];
+
+ // x^1
+ double h = -b[2] * c[1] * e[0] + b[1] * c[2] * e[0] - a[2] * d[1] * e[0] +
+ a[1] * d[2] * e[0] + b[2] * c[0] * e[1] - b[0] * c[2] * e[1] +
+ a[2] * d[0] * e[1] - a[0] * d[2] * e[1] - b[1] * c[0] * e[2] +
+ b[0] * c[1] * e[2] - a[1] * d[0] * e[2] + a[0] * d[1] * e[2] -
+ a[2] * c[1] * f[0] + a[1] * c[2] * f[0] + a[2] * c[0] * f[1] -
+ a[0] * c[2] * f[1] - a[1] * c[0] * f[2] + a[0] * c[1] * f[2];
+
+ // x^2
+ double i = -b[2] * d[1] * e[0] + b[1] * d[2] * e[0] +
+ b[2] * d[0] * e[1] - b[0] * d[2] * e[1] -
+ b[1] * d[0] * e[2] + b[0] * d[1] * e[2] -
+ b[2] * c[1] * f[0] + b[1] * c[2] * f[0] -
+ a[2] * d[1] * f[0] + a[1] * d[2] * f[0] +
+ b[2] * c[0] * f[1] - b[0] * c[2] * f[1] +
+ a[2] * d[0] * f[1] - a[0] * d[2] * f[1] -
+ b[1] * c[0] * f[2] + b[0] * c[1] * f[2] -
+ a[1] * d[0] * f[2] + a[0] * d[1] * f[2];
+
+ // x^3 - checked
+ double j = -b[2] * d[1] * f[0] + b[1] * d[2] * f[0] +
+ b[2] * d[0] * f[1] - b[0] * d[2] * f[1] -
+ b[1] * d[0] * f[2] + b[0] * d[1] * f[2];
+
+ /*
+ printf("r1: %lf\n", a[0] * c[1] * e[2] - a[0] * c[2] * e[1]);
+ printf("r2: %lf\n", a[1] * c[2] * e[0] - a[1] * c[0] * e[2]);
+ printf("r3: %lf\n", a[2] * c[0] * e[1] - a[2] * c[1] * e[0]);
+
+ printf("x1 x: %f, y: %f, z: %f\n", a[0], a[1], a[2]);
+ printf("x2 x: %f, y: %f, z: %f\n", c[0], c[1], c[2]);
+ printf("x3 x: %f, y: %f, z: %f\n", e[0], e[1], e[2]);
+
+ printf("v1 x: %f, y: %f, z: %f\n", b[0], b[1], b[2]);
+ printf("v2 x: %f, y: %f, z: %f\n", d[0], d[1], d[2]);
+ printf("v3 x: %f, y: %f, z: %f\n", f[0], f[1], f[2]);
+
+ printf("t^3: %lf, t^2: %lf, t^1: %lf, t^0: %lf\n", j, i, h, g);
+
+*/
+ // Solve cubic equation to determine times t1, t2, t3, when the collision will occur.
+ if ( ABS ( j ) > DBL_EPSILON )
+ {
+ i /= j;
+ h /= j;
+ g /= j;
+ num_sols = gsl_poly_solve_cubic ( i, h, g, &solution[0], &solution[1], &solution[2] );
+ }
+ else
+ {
+ num_sols = gsl_poly_solve_quadratic ( i, h, g, &solution[0], &solution[1] );
+ solution[2] = -1.0;
+ }
+
+ // printf("num_sols: %d, sol1: %lf, sol2: %lf, sol3: %lf\n", num_sols, solution[0], solution[1], solution[2]);
+
+ // Discard negative solutions
+ if ( ( num_sols >= 1 ) && ( solution[0] < DBL_EPSILON ) )
+ {
+ --num_sols;
+ solution[0] = solution[num_sols];
+ }
+ if ( ( num_sols >= 2 ) && ( solution[1] < DBL_EPSILON ) )
+ {
+ --num_sols;
+ solution[1] = solution[num_sols];
+ }
+ if ( ( num_sols == 3 ) && ( solution[2] < DBL_EPSILON ) )
+ {
+ --num_sols;
+ }
+
+ // Sort
+ if ( num_sols == 2 )
+ {
+ if ( solution[0] > solution[1] )
+ {
+ double tmp = solution[0];
+ solution[0] = solution[1];
+ solution[1] = tmp;
+ }
+ }
+ else if ( num_sols == 3 )
+ {
+
+ // Bubblesort
+ if ( solution[0] > solution[1] )
+ {
+ double tmp = solution[0]; solution[0] = solution[1]; solution[1] = tmp;
+ }
+ if ( solution[1] > solution[2] )
+ {
+ double tmp = solution[1]; solution[1] = solution[2]; solution[2] = tmp;
+ }
+ if ( solution[0] > solution[1] )
+ {
+ double tmp = solution[0]; solution[0] = solution[1]; solution[1] = tmp;
+ }
+ }
+
+ return num_sols;
+}
+
+
+// w3 is not perfect
+void collision_compute_barycentric ( float pv[3], float p1[3], float p2[3], float p3[3], float *w1, float *w2, float *w3 )
+{
+ double tempV1[3], tempV2[3], tempV4[3];
+ double a,b,c,d,e,f;
+
+ VECSUB ( tempV1, p1, p3 );
+ VECSUB ( tempV2, p2, p3 );
+ VECSUB ( tempV4, pv, p3 );
+
+ a = INPR ( tempV1, tempV1 );
+ b = INPR ( tempV1, tempV2 );
+ c = INPR ( tempV2, tempV2 );
+ e = INPR ( tempV1, tempV4 );
+ f = INPR ( tempV2, tempV4 );
+
+ d = ( a * c - b * b );
+
+ if ( ABS ( d ) < ALMOST_ZERO )
+ {
+ *w1 = *w2 = *w3 = 1.0 / 3.0;
+ return;
+ }
+
+ w1[0] = ( float ) ( ( e * c - b * f ) / d );
+
+ if ( w1[0] < 0 )
+ w1[0] = 0;
+
+ w2[0] = ( float ) ( ( f - b * ( double ) w1[0] ) / c );
+
+ if ( w2[0] < 0 )
+ w2[0] = 0;
+
+ w3[0] = 1.0f - w1[0] - w2[0];
+}
+
+DO_INLINE void collision_interpolateOnTriangle ( float to[3], float v1[3], float v2[3], float v3[3], double w1, double w2, double w3 )
+{
+ to[0] = to[1] = to[2] = 0;
+ VECADDMUL ( to, v1, w1 );
+ VECADDMUL ( to, v2, w2 );
+ VECADDMUL ( to, v3, w3 );
+}
+
+
+int cloth_collision_response_static ( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair, CollPair *collision_end )
+{
+ int result = 0;
+ Cloth *cloth1;
+ float w1, w2, w3, u1, u2, u3;
+ float v1[3], v2[3], relativeVelocity[3];
+ float magrelVel;
+ float epsilon2 = BLI_bvhtree_getepsilon ( collmd->bvhtree );
+
+ cloth1 = clmd->clothObject;
+
+ for ( ; collpair != collision_end; collpair++ )
+ {
+ // only handle static collisions here
+ if ( collpair->flag & COLLISION_IN_FUTURE )
+ continue;
+
+ // compute barycentric coordinates for both collision points
+ collision_compute_barycentric ( collpair->pa,
+ cloth1->verts[collpair->ap1].txold,
+ cloth1->verts[collpair->ap2].txold,
+ cloth1->verts[collpair->ap3].txold,
+ &w1, &w2, &w3 );
+
+ // was: txold
+ collision_compute_barycentric ( collpair->pb,
+ collmd->current_x[collpair->bp1].co,
+ collmd->current_x[collpair->bp2].co,
+ collmd->current_x[collpair->bp3].co,
+ &u1, &u2, &u3 );
+
+ // Calculate relative "velocity".
+ collision_interpolateOnTriangle ( v1, cloth1->verts[collpair->ap1].tv, cloth1->verts[collpair->ap2].tv, cloth1->verts[collpair->ap3].tv, w1, w2, w3 );
+
+ collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 );
+
+ VECSUB ( relativeVelocity, v2, v1 );
+
+ // Calculate the normal component of the relative velocity (actually only the magnitude - the direction is stored in 'normal').
+ magrelVel = INPR ( relativeVelocity, collpair->normal );
+
+ // printf("magrelVel: %f\n", magrelVel);
+
+ // Calculate masses of points.
+ // TODO
+
+ // If v_n_mag < 0 the edges are approaching each other.
+ if ( magrelVel > ALMOST_ZERO )
+ {
+ // Calculate Impulse magnitude to stop all motion in normal direction.
+ float magtangent = 0, repulse = 0, d = 0;
+ double impulse = 0.0;
+ float vrel_t_pre[3];
+ float temp[3];
+
+ // calculate tangential velocity
+ VECCOPY ( temp, collpair->normal );
+ VecMulf ( temp, magrelVel );
+ VECSUB ( vrel_t_pre, relativeVelocity, temp );
+
+ // Decrease in magnitude of relative tangential velocity due to coulomb friction
+ // in original formula "magrelVel" should be the "change of relative velocity in normal direction"
+ magtangent = MIN2 ( clmd->coll_parms->friction * 0.01 * magrelVel,sqrt ( INPR ( vrel_t_pre,vrel_t_pre ) ) );
+
+ // Apply friction impulse.
+ if ( magtangent > ALMOST_ZERO )
+ {
+ Normalize ( vrel_t_pre );
+
+ impulse = magtangent / ( 1.0 + w1*w1 + w2*w2 + w3*w3 ); // 2.0 *
+ VECADDMUL ( cloth1->verts[collpair->ap1].impulse, vrel_t_pre, w1 * impulse );
+ VECADDMUL ( cloth1->verts[collpair->ap2].impulse, vrel_t_pre, w2 * impulse );
+ VECADDMUL ( cloth1->verts[collpair->ap3].impulse, vrel_t_pre, w3 * impulse );
+ }
+
+ // Apply velocity stopping impulse
+ // I_c = m * v_N / 2.0
+ // no 2.0 * magrelVel normally, but looks nicer DG
+ impulse = magrelVel / ( 1.0 + w1*w1 + w2*w2 + w3*w3 );
+
+ VECADDMUL ( cloth1->verts[collpair->ap1].impulse, collpair->normal, w1 * impulse );
+ cloth1->verts[collpair->ap1].impulse_count++;
+
+ VECADDMUL ( cloth1->verts[collpair->ap2].impulse, collpair->normal, w2 * impulse );
+ cloth1->verts[collpair->ap2].impulse_count++;
+
+ VECADDMUL ( cloth1->verts[collpair->ap3].impulse, collpair->normal, w3 * impulse );
+ cloth1->verts[collpair->ap3].impulse_count++;
+
+ // Apply repulse impulse if distance too short
+ // I_r = -min(dt*kd, m(0,1d/dt - v_n))
+ d = clmd->coll_parms->epsilon*8.0/9.0 + epsilon2*8.0/9.0 - collpair->distance;
+ if ( ( magrelVel < 0.1*d*clmd->sim_parms->stepsPerFrame ) && ( d > ALMOST_ZERO ) )
+ {
+ repulse = MIN2 ( d*1.0/clmd->sim_parms->stepsPerFrame, 0.1*d*clmd->sim_parms->stepsPerFrame - magrelVel );
+
+ // stay on the safe side and clamp repulse
+ if ( impulse > ALMOST_ZERO )
+ repulse = MIN2 ( repulse, 5.0*impulse );
+ repulse = MAX2 ( impulse, repulse );
+
+ impulse = repulse / ( 1.0 + w1*w1 + w2*w2 + w3*w3 ); // original 2.0 / 0.25
+ VECADDMUL ( cloth1->verts[collpair->ap1].impulse, collpair->normal, impulse );
+ VECADDMUL ( cloth1->verts[collpair->ap2].impulse, collpair->normal, impulse );
+ VECADDMUL ( cloth1->verts[collpair->ap3].impulse, collpair->normal, impulse );
+ }
+
+ result = 1;
+ }
+ }
+ return result;
+}
+
+//Determines collisions on overlap, collisions are writen to collpair[i] and collision+number_collision_found is returned
+CollPair* cloth_collision ( ModifierData *md1, ModifierData *md2, BVHTreeOverlap *overlap, CollPair *collpair )
+{
+ ClothModifierData *clmd = ( ClothModifierData * ) md1;
+ CollisionModifierData *collmd = ( CollisionModifierData * ) md2;
+ MFace *face1=NULL, *face2 = NULL;
+ ClothVertex *verts1 = clmd->clothObject->verts;
+ double distance = 0;
+ float epsilon1 = clmd->coll_parms->epsilon;
+ float epsilon2 = BLI_bvhtree_getepsilon ( collmd->bvhtree );
+ int i;
+
+ face1 = & ( clmd->clothObject->mfaces[overlap->indexA] );
+ face2 = & ( collmd->mfaces[overlap->indexB] );
+
+ // check all 4 possible collisions
+ for ( i = 0; i < 4; i++ )
+ {
+ if ( i == 0 )
+ {
+ // fill faceA
+ collpair->ap1 = face1->v1;
+ collpair->ap2 = face1->v2;
+ collpair->ap3 = face1->v3;
+
+ // fill faceB
+ collpair->bp1 = face2->v1;
+ collpair->bp2 = face2->v2;
+ collpair->bp3 = face2->v3;
+ }
+ else if ( i == 1 )
+ {
+ if ( face1->v4 )
+ {
+ // fill faceA
+ collpair->ap1 = face1->v1;
+ collpair->ap2 = face1->v4;
+ collpair->ap3 = face1->v3;
+
+ // fill faceB
+ collpair->bp1 = face2->v1;
+ collpair->bp2 = face2->v2;
+ collpair->bp3 = face2->v3;
+ }
+ else
+ i++;
+ }
+ if ( i == 2 )
+ {
+ if ( face2->v4 )
+ {
+ // fill faceA
+ collpair->ap1 = face1->v1;
+ collpair->ap2 = face1->v2;
+ collpair->ap3 = face1->v3;
+
+ // fill faceB
+ collpair->bp1 = face2->v1;
+ collpair->bp2 = face2->v4;
+ collpair->bp3 = face2->v3;
+ }
+ else
+ break;
+ }
+ else if ( i == 3 )
+ {
+ if ( face1->v4 && face2->v4 )
+ {
+ // fill faceA
+ collpair->ap1 = face1->v1;
+ collpair->ap2 = face1->v4;
+ collpair->ap3 = face1->v3;
+
+ // fill faceB
+ collpair->bp1 = face2->v1;
+ collpair->bp2 = face2->v4;
+ collpair->bp3 = face2->v3;
+ }
+ else
+ break;
+ }
+
+#ifdef WITH_BULLET
+ // calc distance + normal
+ distance = plNearestPoints (
+ verts1[collpair->ap1].txold, verts1[collpair->ap2].txold, verts1[collpair->ap3].txold, collmd->current_x[collpair->bp1].co, collmd->current_x[collpair->bp2].co, collmd->current_x[collpair->bp3].co, collpair->pa,collpair->pb,collpair->vector );
+#else
+ // just be sure that we don't add anything
+ distance = 2.0 * ( epsilon1 + epsilon2 + ALMOST_ZERO );
+#endif
+
+ if ( distance <= ( epsilon1 + epsilon2 + ALMOST_ZERO ) )
+ {
+ VECCOPY ( collpair->normal, collpair->vector );
+ Normalize ( collpair->normal );
+
+ collpair->distance = distance;
+ collpair->flag = 0;
+ collpair++;
+ }/*
+ else
+ {
+ float w1, w2, w3, u1, u2, u3;
+ float v1[3], v2[3], relativeVelocity[3];
+
+ // calc relative velocity
+
+ // compute barycentric coordinates for both collision points
+ collision_compute_barycentric ( collpair->pa,
+ verts1[collpair->ap1].txold,
+ verts1[collpair->ap2].txold,
+ verts1[collpair->ap3].txold,
+ &w1, &w2, &w3 );
+
+ // was: txold
+ collision_compute_barycentric ( collpair->pb,
+ collmd->current_x[collpair->bp1].co,
+ collmd->current_x[collpair->bp2].co,
+ collmd->current_x[collpair->bp3].co,
+ &u1, &u2, &u3 );
+
+ // Calculate relative "velocity".
+ collision_interpolateOnTriangle ( v1, verts1[collpair->ap1].tv, verts1[collpair->ap2].tv, verts1[collpair->ap3].tv, w1, w2, w3 );
+
+ collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 );
+
+ VECSUB ( relativeVelocity, v2, v1 );
+
+ if(sqrt(INPR(relativeVelocity, relativeVelocity)) >= distance)
+ {
+ // check for collision in the future
+ collpair->flag |= COLLISION_IN_FUTURE;
+ collpair++;
+ }
+ }*/
+ }
+ return collpair;
+}
+
+int cloth_collision_response_moving( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair, CollPair *collision_end )
+{
+ int result = 0;
+ Cloth *cloth1;
+ float w1, w2, w3, u1, u2, u3;
+ float v1[3], v2[3], relativeVelocity[3];
+ float magrelVel;
+
+ cloth1 = clmd->clothObject;
+
+ for ( ; collpair != collision_end; collpair++ )
+ {
+ // compute barycentric coordinates for both collision points
+ collision_compute_barycentric ( collpair->pa,
+ cloth1->verts[collpair->ap1].txold,
+ cloth1->verts[collpair->ap2].txold,
+ cloth1->verts[collpair->ap3].txold,
+ &w1, &w2, &w3 );
+
+ // was: txold
+ collision_compute_barycentric ( collpair->pb,
+ collmd->current_x[collpair->bp1].co,
+ collmd->current_x[collpair->bp2].co,
+ collmd->current_x[collpair->bp3].co,
+ &u1, &u2, &u3 );
+
+ // Calculate relative "velocity".
+ collision_interpolateOnTriangle ( v1, cloth1->verts[collpair->ap1].tv, cloth1->verts[collpair->ap2].tv, cloth1->verts[collpair->ap3].tv, w1, w2, w3 );
+
+ collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 );
+
+ VECSUB ( relativeVelocity, v2, v1 );
+
+ // Calculate the normal component of the relative velocity (actually only the magnitude - the direction is stored in 'normal').
+ magrelVel = INPR ( relativeVelocity, collpair->normal );
+
+ // printf("magrelVel: %f\n", magrelVel);
+
+ // Calculate masses of points.
+ // TODO
+
+ // If v_n_mag < 0 the edges are approaching each other.
+ if ( magrelVel > ALMOST_ZERO )
+ {
+ // Calculate Impulse magnitude to stop all motion in normal direction.
+ float magtangent = 0;
+ double impulse = 0.0;
+ float vrel_t_pre[3];
+ float temp[3];
+
+ // calculate tangential velocity
+ VECCOPY ( temp, collpair->normal );
+ VecMulf ( temp, magrelVel );
+ VECSUB ( vrel_t_pre, relativeVelocity, temp );
+
+ // Decrease in magnitude of relative tangential velocity due to coulomb friction
+ // in original formula "magrelVel" should be the "change of relative velocity in normal direction"
+ magtangent = MIN2 ( clmd->coll_parms->friction * 0.01 * magrelVel,sqrt ( INPR ( vrel_t_pre,vrel_t_pre ) ) );
+
+ // Apply friction impulse.
+ if ( magtangent > ALMOST_ZERO )
+ {
+ Normalize ( vrel_t_pre );
+
+ impulse = 2.0 * magtangent / ( 1.0 + w1*w1 + w2*w2 + w3*w3 );
+ VECADDMUL ( cloth1->verts[collpair->ap1].impulse, vrel_t_pre, w1 * impulse );
+ VECADDMUL ( cloth1->verts[collpair->ap2].impulse, vrel_t_pre, w2 * impulse );
+ VECADDMUL ( cloth1->verts[collpair->ap3].impulse, vrel_t_pre, w3 * impulse );
+ }
+
+ // Apply velocity stopping impulse
+ // I_c = m * v_N / 2.0
+ // no 2.0 * magrelVel normally, but looks nicer DG
+ impulse = magrelVel / ( 1.0 + w1*w1 + w2*w2 + w3*w3 );
+
+ VECADDMUL ( cloth1->verts[collpair->ap1].impulse, collpair->normal, w1 * impulse );
+ cloth1->verts[collpair->ap1].impulse_count++;
+
+ VECADDMUL ( cloth1->verts[collpair->ap2].impulse, collpair->normal, w2 * impulse );
+ cloth1->verts[collpair->ap2].impulse_count++;
+
+ VECADDMUL ( cloth1->verts[collpair->ap3].impulse, collpair->normal, w3 * impulse );
+ cloth1->verts[collpair->ap3].impulse_count++;
+
+ // Apply repulse impulse if distance too short
+ // I_r = -min(dt*kd, m(0,1d/dt - v_n))
+ /*
+ d = clmd->coll_parms->epsilon*8.0/9.0 + epsilon2*8.0/9.0 - collpair->distance;
+ if ( ( magrelVel < 0.1*d*clmd->sim_parms->stepsPerFrame ) && ( d > ALMOST_ZERO ) )
+ {
+ repulse = MIN2 ( d*1.0/clmd->sim_parms->stepsPerFrame, 0.1*d*clmd->sim_parms->stepsPerFrame - magrelVel );
+
+ // stay on the safe side and clamp repulse
+ if ( impulse > ALMOST_ZERO )
+ repulse = MIN2 ( repulse, 5.0*impulse );
+ repulse = MAX2 ( impulse, repulse );
+
+ impulse = repulse / ( 1.0 + w1*w1 + w2*w2 + w3*w3 ); // original 2.0 / 0.25
+ VECADDMUL ( cloth1->verts[collpair->ap1].impulse, collpair->normal, impulse );
+ VECADDMUL ( cloth1->verts[collpair->ap2].impulse, collpair->normal, impulse );
+ VECADDMUL ( cloth1->verts[collpair->ap3].impulse, collpair->normal, impulse );
+ }
+ */
+ result = 1;
+ }
+ }
+ return result;
+}
+
+static float projectPointOntoLine(float *p, float *a, float *b)
+{
+ float ba[3], pa[3];
+ VECSUB(ba, b, a);
+ VECSUB(pa, p, a);
+ return INPR(pa, ba) / INPR(ba, ba);
+}
+
+static void calculateEENormal(float *np1, float *np2, float *np3, float *np4,float *out_normal)
+{
+ float line1[3], line2[3];
+ float length;
+
+ VECSUB(line1, np2, np1);
+ VECSUB(line2, np3, np1);
+
+ // printf("l1: %f, l1: %f, l2: %f, l2: %f\n", line1[0], line1[1], line2[0], line2[1]);
+
+ Crossf(out_normal, line1, line2);
+
+
+
+ length = Normalize(out_normal);
+ if (length <= FLT_EPSILON)
+ { // lines are collinear
+ VECSUB(out_normal, np2, np1);
+ Normalize(out_normal);
+ }
+}
+
+static void findClosestPointsEE(float *x1, float *x2, float *x3, float *x4, float *w1, float *w2)
+{
+ float temp[3], temp2[3];
+
+ double a, b, c, e, f;
+
+ VECSUB(temp, x2, x1);
+ a = INPR(temp, temp);
+
+ VECSUB(temp2, x4, x3);
+ b = -INPR(temp, temp2);
+
+ c = INPR(temp2, temp2);
+
+ VECSUB(temp2, x3, x1);
+ e = INPR(temp, temp2);
+
+ VECSUB(temp, x4, x3);
+ f = -INPR(temp, temp2);
+
+ *w1 = (e * c - b * f) / (a * c - b * b);
+ *w2 = (f - b * *w1) / c;
+
+}
+
+// calculates the distance of 2 edges
+float edgedge_distance(float np11[3], float np12[3], float np21[3], float np22[3], float *out_a1, float *out_a2, float *out_normal)
+{
+ float line1[3], line2[3], cross[3];
+ float length;
+ float temp[3], temp2[3];
+ float dist_a1, dist_a2;
+
+ VECSUB(line1, np12, np11);
+ VECSUB(line2, np22, np21);
+
+ Crossf(cross, line1, line2);
+ length = INPR(cross, cross);
+
+ if (length < FLT_EPSILON)
+ {
+ *out_a2 = projectPointOntoLine(np11, np21, np22);
+ if ((*out_a2 >= -FLT_EPSILON) && (*out_a2 <= 1.0 + FLT_EPSILON))
+ {
+ *out_a1 = 0;
+ calculateEENormal(np11, np12, np21, np22, out_normal);
+ VECSUB(temp, np22, np21);
+ VecMulf(temp, *out_a2);
+ VECADD(temp2, temp, np21);
+ VECADD(temp2, temp2, np11);
+ return INPR(temp2, temp2);
+ }
+
+ CLAMP(*out_a2, 0.0, 1.0);
+ if (*out_a2 > .5)
+ { // == 1.0
+ *out_a1 = projectPointOntoLine(np22, np11, np12);
+ if ((*out_a1 >= -FLT_EPSILON) && (*out_a1 <= 1.0 + FLT_EPSILON))
+ {
+ calculateEENormal(np11, np12, np21, np22, out_normal);
+
+ // return (np22 - (np11 + (np12 - np11) * out_a1)).lengthSquared();
+ VECSUB(temp, np12, np11);
+ VecMulf(temp, *out_a1);
+ VECADD(temp2, temp, np11);
+ VECSUB(temp2, np22, temp2);
+ return INPR(temp2, temp2);
+ }
+ }
+ else
+ { // == 0.0
+ *out_a1 = projectPointOntoLine(np21, np11, np12);
+ if ((*out_a1 >= -FLT_EPSILON) && (*out_a1 <= 1.0 + FLT_EPSILON))
+ {
+ calculateEENormal(np11, np11, np21, np22, out_normal);
+
+ // return (np21 - (np11 + (np12 - np11) * out_a1)).lengthSquared();
+ VECSUB(temp, np12, np11);
+ VecMulf(temp, *out_a1);
+ VECADD(temp2, temp, np11);
+ VECSUB(temp2, np21, temp2);
+ return INPR(temp2, temp2);
+ }
+ }
+
+ CLAMP(*out_a1, 0.0, 1.0);
+ calculateEENormal(np11, np12, np21, np22, out_normal);
+ if(*out_a1 > .5)
+ {
+ if(*out_a2 > .5)
+ {
+ VECSUB(temp, np12, np22);
+ }
+ else
+ {
+ VECSUB(temp, np12, np21);
+ }
+ }
+ else
+ {
+ if(*out_a2 > .5)
+ {
+ VECSUB(temp, np11, np22);
+ }
+ else
+ {
+ VECSUB(temp, np11, np21);
+ }
+ }
+
+ return INPR(temp, temp);
+ }
+ else
+ {
+
+ // If the lines aren't parallel (but coplanar) they have to intersect
+
+ findClosestPointsEE(np11, np12, np21, np22, out_a1, out_a2);
+
+ // If both points are on the finite edges, we're done.
+ if (*out_a1 >= 0.0 && *out_a1 <= 1.0 && *out_a2 >= 0.0 && *out_a2 <= 1.0)
+ {
+ float p1[3], p2[3];
+
+ // p1= np11 + (np12 - np11) * out_a1;
+ VECSUB(temp, np12, np11);
+ VecMulf(temp, *out_a1);
+ VECADD(p1, np11, temp);
+
+ // p2 = np21 + (np22 - np21) * out_a2;
+ VECSUB(temp, np22, np21);
+ VecMulf(temp, *out_a2);
+ VECADD(p2, np21, temp);
+
+ calculateEENormal(np11, np12, np21, np22, out_normal);
+ VECSUB(temp, p1, p2);
+ return INPR(temp, temp);
+ }
+
+
+ /*
+ * Clamp both points to the finite edges.
+ * The one that moves most during clamping is one part of the solution.
+ */
+ dist_a1 = *out_a1;
+ CLAMP(dist_a1, 0.0, 1.0);
+ dist_a2 = *out_a2;
+ CLAMP(dist_a2, 0.0, 1.0);
+
+ // Now project the "most clamped" point on the other line.
+ if (dist_a1 > dist_a2)
+ {
+ /* keep out_a1 */
+ float p1[3];
+
+ // p1 = np11 + (np12 - np11) * out_a1;
+ VECSUB(temp, np12, np11);
+ VecMulf(temp, *out_a1);
+ VECADD(p1, np11, temp);
+
+ *out_a2 = projectPointOntoLine(p1, np21, np22);
+ CLAMP(*out_a2, 0.0, 1.0);
+
+ calculateEENormal(np11, np12, np21, np22, out_normal);
+
+ // return (p1 - (np21 + (np22 - np21) * out_a2)).lengthSquared();
+ VECSUB(temp, np22, np21);
+ VecMulf(temp, *out_a2);
+ VECADD(temp, temp, np21);
+ VECSUB(temp, p1, temp);
+ return INPR(temp, temp);
+ }
+ else
+ {
+ /* keep out_a2 */
+ float p2[3];
+
+ // p2 = np21 + (np22 - np21) * out_a2;
+ VECSUB(temp, np22, np21);
+ VecMulf(temp, *out_a2);
+ VECADD(p2, np21, temp);
+
+ *out_a1 = projectPointOntoLine(p2, np11, np12);
+ CLAMP(*out_a1, 0.0, 1.0);
+
+ calculateEENormal(np11, np12, np21, np22, out_normal);
+
+ // return ((np11 + (np12 - np11) * out_a1) - p2).lengthSquared();
+ VECSUB(temp, np12, np11);
+ VecMulf(temp, *out_a1);
+ VECADD(temp, temp, np11);
+ VECSUB(temp, temp, p2);
+ return INPR(temp, temp);
+ }
+ }
+
+ printf("Error in edgedge_distance: end of function\n");
+ return 0;
+}
+
+int cloth_collision_moving_edges ( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair )
+{
+ EdgeCollPair edgecollpair;
+ Cloth *cloth1=NULL;
+ ClothVertex *verts1=NULL;
+ unsigned int i = 0, k = 0;
+ int numsolutions = 0;
+ double x1[3], v1[3], x2[3], v2[3], x3[3], v3[3];
+ double solution[3], solution2[3];
+ MVert *verts2 = collmd->current_x; // old x
+ MVert *velocity2 = collmd->current_v; // velocity
+ float distance = 0;
+ float triA[3][3], triB[3][3];
+ int result = 0;
+
+ cloth1 = clmd->clothObject;
+ verts1 = cloth1->verts;
+
+ for(i = 0; i < 9; i++)
+ {
+ // 9 edge - edge possibilities
+
+ if(i == 0) // cloth edge: 1-2; coll edge: 1-2
+ {
+ edgecollpair.p11 = collpair->ap1;
+ edgecollpair.p12 = collpair->ap2;
+
+ edgecollpair.p21 = collpair->bp1;
+ edgecollpair.p22 = collpair->bp2;
+ }
+ else if(i == 1) // cloth edge: 1-2; coll edge: 2-3
+ {
+ edgecollpair.p11 = collpair->ap1;
+ edgecollpair.p12 = collpair->ap2;
+
+ edgecollpair.p21 = collpair->bp2;
+ edgecollpair.p22 = collpair->bp3;
+ }
+ else if(i == 2) // cloth edge: 1-2; coll edge: 1-3
+ {
+ edgecollpair.p11 = collpair->ap1;
+ edgecollpair.p12 = collpair->ap2;
+
+ edgecollpair.p21 = collpair->bp1;
+ edgecollpair.p22 = collpair->bp3;
+ }
+ else if(i == 3) // cloth edge: 2-3; coll edge: 1-2
+ {
+ edgecollpair.p11 = collpair->ap2;
+ edgecollpair.p12 = collpair->ap3;
+
+ edgecollpair.p21 = collpair->bp1;
+ edgecollpair.p22 = collpair->bp2;
+ }
+ else if(i == 4) // cloth edge: 2-3; coll edge: 2-3
+ {
+ edgecollpair.p11 = collpair->ap2;
+ edgecollpair.p12 = collpair->ap3;
+
+ edgecollpair.p21 = collpair->bp2;
+ edgecollpair.p22 = collpair->bp3;
+ }
+ else if(i == 5) // cloth edge: 2-3; coll edge: 1-3
+ {
+ edgecollpair.p11 = collpair->ap2;
+ edgecollpair.p12 = collpair->ap3;
+
+ edgecollpair.p21 = collpair->bp1;
+ edgecollpair.p22 = collpair->bp3;
+ }
+ else if(i ==6) // cloth edge: 1-3; coll edge: 1-2
+ {
+ edgecollpair.p11 = collpair->ap1;
+ edgecollpair.p12 = collpair->ap3;
+
+ edgecollpair.p21 = collpair->bp1;
+ edgecollpair.p22 = collpair->bp2;
+ }
+ else if(i ==7) // cloth edge: 1-3; coll edge: 2-3
+ {
+ edgecollpair.p11 = collpair->ap1;
+ edgecollpair.p12 = collpair->ap3;
+
+ edgecollpair.p21 = collpair->bp2;
+ edgecollpair.p22 = collpair->bp3;
+ }
+ else if(i == 8) // cloth edge: 1-3; coll edge: 1-3
+ {
+ edgecollpair.p11 = collpair->ap1;
+ edgecollpair.p12 = collpair->ap3;
+
+ edgecollpair.p21 = collpair->bp1;
+ edgecollpair.p22 = collpair->bp3;
+ }
+ /*
+ if((edgecollpair.p11 == 3) && (edgecollpair.p12 == 16))
+ printf("Ahier!\n");
+ if((edgecollpair.p11 == 16) && (edgecollpair.p12 == 3))
+ printf("Ahier!\n");
+ */
+
+ // if ( !cloth_are_edges_adjacent ( clmd, collmd, &edgecollpair ) )
+ {
+ // always put coll points in p21/p22
+ VECSUB ( x1, verts1[edgecollpair.p12].txold, verts1[edgecollpair.p11].txold );
+ VECSUB ( v1, verts1[edgecollpair.p12].tv, verts1[edgecollpair.p11].tv );
+
+ VECSUB ( x2, verts2[edgecollpair.p21].co, verts1[edgecollpair.p11].txold );
+ VECSUB ( v2, velocity2[edgecollpair.p21].co, verts1[edgecollpair.p11].tv );
+
+ VECSUB ( x3, verts2[edgecollpair.p22].co, verts1[edgecollpair.p11].txold );
+ VECSUB ( v3, velocity2[edgecollpair.p22].co, verts1[edgecollpair.p11].tv );
+
+ numsolutions = cloth_get_collision_time ( x1, v1, x2, v2, x3, v3, solution );
+
+ if((edgecollpair.p11 == 3 && edgecollpair.p12==16)|| (edgecollpair.p11==16 && edgecollpair.p12==3))
+ {
+ if(edgecollpair.p21==6 || edgecollpair.p22 == 6)
+ {
+ printf("dist: %f, sol[k]: %lf, sol2[k]: %lf\n", distance, solution[k], solution2[k]);
+ printf("a1: %f, a2: %f, b1: %f, b2: %f\n", x1[0], x2[0], x3[0], v1[0]);
+ printf("b21: %d, b22: %d\n", edgecollpair.p21, edgecollpair.p22);
+ }
+ }
+
+ for ( k = 0; k < numsolutions; k++ )
+ {
+ // printf("sol %d: %lf\n", k, solution[k]);
+ if ( ( solution[k] >= ALMOST_ZERO ) && ( solution[k] <= 1.0 ) && ( solution[k] > ALMOST_ZERO))
+ {
+ float a,b;
+ float out_normal[3];
+ float distance;
+ float impulse = 0;
+ float I_mag;
+
+ // move verts
+ VECADDS(triA[0], verts1[edgecollpair.p11].txold, verts1[edgecollpair.p11].tv, solution[k]);
+ VECADDS(triA[1], verts1[edgecollpair.p12].txold, verts1[edgecollpair.p12].tv, solution[k]);
+
+ VECADDS(triB[0], collmd->current_x[edgecollpair.p21].co, collmd->current_v[edgecollpair.p21].co, solution[k]);
+ VECADDS(triB[1], collmd->current_x[edgecollpair.p22].co, collmd->current_v[edgecollpair.p22].co, solution[k]);
+
+ // TODO: check for collisions
+ distance = edgedge_distance(triA[0], triA[1], triB[0], triB[1], &a, &b, out_normal);
+
+ if ((distance <= clmd->coll_parms->epsilon + BLI_bvhtree_getepsilon ( collmd->bvhtree ) + ALMOST_ZERO) && (INPR(out_normal, out_normal) > 0))
+ {
+ float vrel_1_to_2[3], temp[3], temp2[3], out_normalVelocity;
+ float desiredVn;
+
+ VECCOPY(vrel_1_to_2, verts1[edgecollpair.p11].tv);
+ VecMulf(vrel_1_to_2, 1.0 - a);
+ VECCOPY(temp, verts1[edgecollpair.p12].tv);
+ VecMulf(temp, a);
+
+ VECADD(vrel_1_to_2, vrel_1_to_2, temp);
+
+ VECCOPY(temp, verts1[edgecollpair.p21].tv);
+ VecMulf(temp, 1.0 - b);
+ VECCOPY(temp2, verts1[edgecollpair.p22].tv);
+ VecMulf(temp2, b);
+ VECADD(temp, temp, temp2);
+
+ VECSUB(vrel_1_to_2, vrel_1_to_2, temp);
+
+ out_normalVelocity = INPR(vrel_1_to_2, out_normal);
+/*
+ // this correction results in wrong normals sometimes?
+ if(out_normalVelocity < 0.0)
+ {
+ out_normalVelocity*= -1.0;
+ VecMulf(out_normal, -1.0);
+ }
+*/
+ /* Inelastic repulsion impulse. */
+
+ // Calculate which normal velocity we need.
+ desiredVn = (out_normalVelocity * (float)solution[k] - (.1 * (clmd->coll_parms->epsilon + BLI_bvhtree_getepsilon ( collmd->bvhtree )) - sqrt(distance)) - ALMOST_ZERO);
+
+ // Now calculate what impulse we need to reach that velocity.
+ I_mag = (out_normalVelocity - desiredVn) / 2.0; // / (1/m1 + 1/m2);
+
+ // Finally apply that impulse.
+ impulse = (2.0 * -I_mag) / (a*a + (1.0-a)*(1.0-a) + b*b + (1.0-b)*(1.0-b));
+
+ VECADDMUL ( verts1[edgecollpair.p11].impulse, out_normal, (1.0-a) * impulse );
+ verts1[edgecollpair.p11].impulse_count++;
+
+ VECADDMUL ( verts1[edgecollpair.p12].impulse, out_normal, a * impulse );
+ verts1[edgecollpair.p12].impulse_count++;
+
+ // return true;
+ result = 1;
+ break;
+ }
+ else
+ {
+ // missing from collision.hpp
+ }
+ // mintime = MIN2(mintime, (float)solution[k]);
+
+ break;
+ }
+ }
+ }
+ }
+ return result;
+}
+
+int cloth_collision_moving ( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair, CollPair *collision_end )
+{
+ Cloth *cloth1;
+ cloth1 = clmd->clothObject;
+
+ for ( ; collpair != collision_end; collpair++ )
+ {
+ // only handle moving collisions here
+ if (!( collpair->flag & COLLISION_IN_FUTURE ))
+ continue;
+
+ cloth_collision_moving_edges ( clmd, collmd, collpair);
+ // cloth_collision_moving_tris ( clmd, collmd, collpair);
+ }
+
+ return 1;
+}
+
+
+// return all collision objects in scene
+// collision object will exclude self
+CollisionModifierData **get_collisionobjects(Object *self, int *numcollobj)
+{
+ Base *base=NULL;
+ CollisionModifierData **objs = NULL;
+ Object *coll_ob = NULL;
+ CollisionModifierData *collmd = NULL;
+ int numobj = 0, maxobj = 100;
+
+ objs = MEM_callocN(sizeof(CollisionModifierData *)*maxobj, "CollisionObjectsArray");
+ // check all collision objects
+ for ( base = G.scene->base.first; base; base = base->next )
+ {
+ /*Only proceed for mesh object in same layer */
+ if(!(base->object->type==OB_MESH && (base->lay & self->lay)))
+ continue;
+
+ coll_ob = base->object;
+
+ if(coll_ob == self)
+ continue;
+
+ if(coll_ob->pd && coll_ob->pd->deflect)
+ {
+ collmd = ( CollisionModifierData * ) modifiers_findByType ( coll_ob, eModifierType_Collision );
+ }
+ else
+ collmd = NULL;
+
+ if ( collmd )
+ {
+ if(numobj >= maxobj)
+ {
+ // realloc
+ int oldmax = maxobj;
+ CollisionModifierData **tmp;
+ maxobj *= 2;
+ tmp = MEM_callocN(sizeof(CollisionModifierData *)*maxobj, "CollisionObjectsArray");
+ memcpy(tmp, objs, sizeof(CollisionModifierData *)*oldmax);
+ MEM_freeN(objs);
+ objs = tmp;
+
+ }
+
+ objs[numobj] = collmd;
+ numobj++;
+ }
+ else
+ {
+ if ( coll_ob->dup_group )
+ {
+ GroupObject *go;
+ Group *group = coll_ob->dup_group;
+
+ for ( go= group->gobject.first; go; go= go->next )
+ {
+ coll_ob = go->ob;
+ collmd = NULL;
+
+ if(coll_ob == self)
+ continue;
+
+ if(coll_ob->pd && coll_ob->pd->deflect)
+ {
+ collmd = ( CollisionModifierData * ) modifiers_findByType ( coll_ob, eModifierType_Collision );
+ }
+ else
+ collmd = NULL;
+
+ if ( !collmd )
+ continue;
+
+ if( !collmd->bvhtree)
+ continue;
+
+ if(numobj >= maxobj)
+ {
+ // realloc
+ int oldmax = maxobj;
+ CollisionModifierData **tmp;
+ maxobj *= 2;
+ tmp = MEM_callocN(sizeof(CollisionModifierData *)*maxobj, "CollisionObjectsArray");
+ memcpy(tmp, objs, sizeof(CollisionModifierData *)*oldmax);
+ MEM_freeN(objs);
+ objs = tmp;
+ }
+
+ objs[numobj] = collmd;
+ numobj++;
+ }
+ }
+ }
+ }
+ *numcollobj = numobj;
+ return objs;
+}
+
+void cloth_bvh_objcollisions_nearcheck ( ClothModifierData * clmd, CollisionModifierData *collmd, CollPair **collisions, CollPair **collisions_index, int numresult, BVHTreeOverlap *overlap)
+{
+ int i;
+
+ *collisions = ( CollPair* ) MEM_mallocN ( sizeof ( CollPair ) * numresult * 4, "collision array" ); //*4 since cloth_collision_static can return more than 1 collision
+ *collisions_index = *collisions;
+
+ for ( i = 0; i < numresult; i++ )
+ {
+ *collisions_index = cloth_collision ( ( ModifierData * ) clmd, ( ModifierData * ) collmd, overlap+i, *collisions_index );
+ }
+}
+
+int cloth_bvh_objcollisions_resolve ( ClothModifierData * clmd, CollisionModifierData *collmd, CollPair *collisions, CollPair *collisions_index)
+{
+ Cloth *cloth = clmd->clothObject;
+ int i=0, j = 0, numfaces = 0, numverts = 0;
+ ClothVertex *verts = NULL;
+ int ret = 0;
+ int result = 0;
+ float tnull[3] = {0,0,0};
+
+ numfaces = clmd->clothObject->numfaces;
+ numverts = clmd->clothObject->numverts;
+
+ verts = cloth->verts;
+
+ // process all collisions (calculate impulses, TODO: also repulses if distance too short)
+ result = 1;
+ for ( j = 0; j < 5; j++ ) // 5 is just a value that ensures convergence
+ {
+ result = 0;
+
+ if ( collmd->bvhtree )
+ {
+ result += cloth_collision_response_static ( clmd, collmd, collisions, collisions_index );
+
+ // apply impulses in parallel
+ if ( result )
+ {
+ for ( i = 0; i < numverts; i++ )
+ {
+ // calculate "velocities" (just xnew = xold + v; no dt in v)
+ if ( verts[i].impulse_count )
+ {
+ VECADDMUL ( verts[i].tv, verts[i].impulse, 1.0f / verts[i].impulse_count );
+ VECCOPY ( verts[i].impulse, tnull );
+ verts[i].impulse_count = 0;
+
+ ret++;
+ }
+ }
+ }
+ }
+ }
+ return ret;
+}
+
+// cloth - object collisions
+int cloth_bvh_objcollision ( Object *ob, ClothModifierData * clmd, float step, float dt )
+{
+ Cloth *cloth=NULL;
+ BVHTree *cloth_bvh=NULL;
+ int i=0, numfaces = 0, numverts = 0, k, l, j;
+ int rounds = 0; // result counts applied collisions; ic is for debug output;
+ ClothVertex *verts = NULL;
+ int ret = 0, ret2 = 0;
+ CollisionModifierData **collobjs = NULL;
+ int numcollobj = 0;
+
+ if ( ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_COLLOBJ ) || ! ( ( ( Cloth * ) clmd->clothObject )->bvhtree ) )
+ {
+ return 0;
+ }
+
+ cloth = clmd->clothObject;
+ verts = cloth->verts;
+ cloth_bvh = ( BVHTree * ) cloth->bvhtree;
+ numfaces = clmd->clothObject->numfaces;
+ numverts = clmd->clothObject->numverts;
+
+ ////////////////////////////////////////////////////////////
+ // static collisions
+ ////////////////////////////////////////////////////////////
+
+ // update cloth bvh
+ bvhtree_update_from_cloth ( clmd, 1 ); // 0 means STATIC, 1 means MOVING (see later in this function)
+ bvhselftree_update_from_cloth ( clmd, 0 ); // 0 means STATIC, 1 means MOVING (see later in this function)
+
+ collobjs = get_collisionobjects(ob, &numcollobj);
+
+ if(!collobjs)
+ return 0;
+
+ do
+ {
+ CollPair **collisions, **collisions_index;
+
+ ret2 = 0;
+
+ collisions = MEM_callocN(sizeof(CollPair *) *numcollobj , "CollPair");
+ collisions_index = MEM_callocN(sizeof(CollPair *) *numcollobj , "CollPair");
+
+ // check all collision objects
+ for(i = 0; i < numcollobj; i++)
+ {
+ CollisionModifierData *collmd = collobjs[i];
+ BVHTreeOverlap *overlap = NULL;
+ int result = 0;
+
+ if(!collmd->bvhtree)
+ continue;
+
+ /* move object to position (step) in time */
+ collision_move_object ( collmd, step + dt, step );
+
+ /* search for overlapping collision pairs */
+ overlap = BLI_bvhtree_overlap ( cloth_bvh, collmd->bvhtree, &result );
+
+ // go to next object if no overlap is there
+ if(!result || !overlap)
+ {
+ if ( overlap )
+ MEM_freeN ( overlap );
+ continue;
+ }
+
+ /* check if collisions really happen (costly near check) */
+ cloth_bvh_objcollisions_nearcheck ( clmd, collmd, &collisions[i], &collisions_index[i], result, overlap);
+
+ // resolve nearby collisions
+ ret += cloth_bvh_objcollisions_resolve ( clmd, collmd, collisions[i], collisions_index[i]);
+ ret2 += ret;
+
+ if ( overlap )
+ MEM_freeN ( overlap );
+ }
+ rounds++;
+
+ for(i = 0; i < numcollobj; i++)
+ {
+ if ( collisions[i] ) MEM_freeN ( collisions[i] );
+ }
+
+ MEM_freeN(collisions);
+ MEM_freeN(collisions_index);
+
+ ////////////////////////////////////////////////////////////
+ // update positions
+ // this is needed for bvh_calc_DOP_hull_moving() [kdop.c]
+ ////////////////////////////////////////////////////////////
+
+ // verts come from clmd
+ for ( i = 0; i < numverts; i++ )
+ {
+ if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )
+ {
+ if ( verts [i].flags & CLOTH_VERT_FLAG_PINNED )
+ {
+ continue;
+ }
+ }
+
+ VECADD ( verts[i].tx, verts[i].txold, verts[i].tv );
+ }
+ ////////////////////////////////////////////////////////////
+
+
+ ////////////////////////////////////////////////////////////
+ // Test on *simple* selfcollisions
+ ////////////////////////////////////////////////////////////
+ if ( clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF )
+ {
+ for(l = 0; l < clmd->coll_parms->self_loop_count; l++)
+ {
+ // TODO: add coll quality rounds again
+ BVHTreeOverlap *overlap = NULL;
+ int result = 0;
+
+ // collisions = 1;
+ verts = cloth->verts; // needed for openMP
+
+ numfaces = clmd->clothObject->numfaces;
+ numverts = clmd->clothObject->numverts;
+
+ verts = cloth->verts;
+
+ if ( cloth->bvhselftree )
+ {
+ // search for overlapping collision pairs
+ overlap = BLI_bvhtree_overlap ( cloth->bvhselftree, cloth->bvhselftree, &result );
+
+ // #pragma omp parallel for private(k, i, j) schedule(static)
+ for ( k = 0; k < result; k++ )
+ {
+ float temp[3];
+ float length = 0;
+ float mindistance;
+
+ i = overlap[k].indexA;
+ j = overlap[k].indexB;
+
+ mindistance = clmd->coll_parms->selfepsilon* ( cloth->verts[i].avg_spring_len + cloth->verts[j].avg_spring_len );
+
+ if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )
+ {
+ if ( ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED )
+ && ( cloth->verts [j].flags & CLOTH_VERT_FLAG_PINNED ) )
+ {
+ continue;
+ }
+ }
+
+ VECSUB ( temp, verts[i].tx, verts[j].tx );
+
+ if ( ( ABS ( temp[0] ) > mindistance ) || ( ABS ( temp[1] ) > mindistance ) || ( ABS ( temp[2] ) > mindistance ) ) continue;
+
+ // check for adjacent points (i must be smaller j)
+ if ( BLI_edgehash_haskey ( cloth->edgehash, MIN2(i, j), MAX2(i, j) ) )
+ {
+ continue;
+ }
+
+ length = Normalize ( temp );
+
+ if ( length < mindistance )
+ {
+ float correction = mindistance - length;
+
+ if ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED )
+ {
+ VecMulf ( temp, -correction );
+ VECADD ( verts[j].tx, verts[j].tx, temp );
+ }
+ else if ( cloth->verts [j].flags & CLOTH_VERT_FLAG_PINNED )
+ {
+ VecMulf ( temp, correction );
+ VECADD ( verts[i].tx, verts[i].tx, temp );
+ }
+ else
+ {
+ VecMulf ( temp, -correction*0.5 );
+ VECADD ( verts[j].tx, verts[j].tx, temp );
+
+ VECSUB ( verts[i].tx, verts[i].tx, temp );
+ }
+ ret = 1;
+ ret2 += ret;
+ }
+ else
+ {
+ // check for approximated time collisions
+ }
+ }
+
+ if ( overlap )
+ MEM_freeN ( overlap );
+
+ }
+ }
+ ////////////////////////////////////////////////////////////
+
+ ////////////////////////////////////////////////////////////
+ // SELFCOLLISIONS: update velocities
+ ////////////////////////////////////////////////////////////
+ if ( ret2 )
+ {
+ for ( i = 0; i < cloth->numverts; i++ )
+ {
+ if ( ! ( verts [i].flags & CLOTH_VERT_FLAG_PINNED ) )
+ {
+ VECSUB ( verts[i].tv, verts[i].tx, verts[i].txold );
+ }
+ }
+ }
+ ////////////////////////////////////////////////////////////
+ }
+ }
+ while ( ret2 && ( clmd->coll_parms->loop_count>rounds ) );
+
+ if(collobjs)
+ MEM_freeN(collobjs);
+
+ return MIN2 ( ret, 1 );
+}
diff --git a/source/blender/blenkernel/intern/colortools.c b/source/blender/blenkernel/intern/colortools.c
index 83b014cdd63..1bc34aea9a1 100644
--- a/source/blender/blenkernel/intern/colortools.c
+++ b/source/blender/blenkernel/intern/colortools.c
@@ -167,18 +167,30 @@ void curvemap_remove(CurveMap *cuma, int flag)
void curvemap_insert(CurveMap *cuma, float x, float y)
{
CurveMapPoint *cmp= MEM_callocN((cuma->totpoint+1)*sizeof(CurveMapPoint), "curve points");
- int a;
-
- memcpy(cmp, cuma->curve, (cuma->totpoint)*sizeof(CurveMapPoint));
+ int a, b, foundloc= 0;
+
+ /* insert fragments of the old one and the new point to the new curve */
+ cuma->totpoint++;
+ for(a=0, b=0; a<cuma->totpoint; a++) {
+ if((x < cuma->curve[a].x) && !foundloc) {
+ cmp[a].x= x;
+ cmp[a].y= y;
+ cmp[a].flag= CUMA_SELECT;
+ foundloc= 1;
+ }
+ else {
+ cmp[a].x= cuma->curve[b].x;
+ cmp[a].y= cuma->curve[b].y;
+ cmp[a].flag= cuma->curve[b].flag;
+ cmp[a].flag &= ~CUMA_SELECT; /* make sure old points don't remain selected */
+ cmp[a].shorty= cuma->curve[b].shorty;
+ b++;
+ }
+ }
+
+ /* free old curve and replace it with new one */
MEM_freeN(cuma->curve);
cuma->curve= cmp;
-
- cuma->curve[cuma->totpoint].x= x;
- cuma->curve[cuma->totpoint].y= y;
- cuma->curve[cuma->totpoint].flag = CUMA_SELECT;
- for(a=0; a<cuma->totpoint; a++, cmp++)
- cmp->flag= 0;
- cuma->totpoint++;
}
void curvemap_reset(CurveMap *cuma, rctf *clipr)
@@ -580,7 +592,8 @@ float curvemap_evaluateF(CurveMap *cuma, float value)
fi= (value-cuma->mintable)*cuma->range;
i= (int)fi;
- if(fi<0.0f || fi>cuma->range)
+ /* fi is table float index and should check against table range i.e. [0.0 CM_TABLE] */
+ if(fi<0.0f || fi>CM_TABLE)
return curvemap_calc_extend(cuma, value, &cuma->table[0].x, &cuma->table[CM_TABLE].x);
else {
if(i<0) return cuma->table[0].y;
@@ -637,7 +650,6 @@ void curvemapping_evaluate_premulRGBF(CurveMapping *cumap, float *vecout, const
vecout[2]= curvemap_evaluateF(cumap->cm+2, fac);
}
-#define FTOCHAR(val) val<=0.0f?0: (val>=1.0f?255: (char)(255.0f*val))
void curvemapping_do_ibuf(CurveMapping *cumap, ImBuf *ibuf)
{
@@ -717,3 +729,24 @@ void curvemapping_initialize(CurveMapping *cumap)
curvemap_make_table(cumap->cm+a, &cumap->clipr);
}
}
+
+void curvemapping_table_RGBA(CurveMapping *cumap, float **array, int *size)
+{
+ int a;
+
+ *size = CM_TABLE+1;
+ *array = MEM_callocN(sizeof(float)*(*size)*4, "CurveMapping");
+ curvemapping_initialize(cumap);
+
+ for(a=0; a<*size; a++) {
+ if(cumap->cm[0].table)
+ (*array)[a*4+0]= cumap->cm[0].table[a].y;
+ if(cumap->cm[1].table)
+ (*array)[a*4+1]= cumap->cm[1].table[a].y;
+ if(cumap->cm[2].table)
+ (*array)[a*4+2]= cumap->cm[2].table[a].y;
+ if(cumap->cm[3].table)
+ (*array)[a*4+3]= cumap->cm[3].table[a].y;
+ }
+}
+
diff --git a/source/blender/blenkernel/intern/constraint.c b/source/blender/blenkernel/intern/constraint.c
index 3ed4d134145..b8bfb002075 100644
--- a/source/blender/blenkernel/intern/constraint.c
+++ b/source/blender/blenkernel/intern/constraint.c
@@ -28,8 +28,10 @@
*/
#include <stdio.h>
+#include <stddef.h>
#include <string.h>
#include <math.h>
+#include <float.h>
#include "MEM_guardedalloc.h"
//XXX #include "nla.h"
@@ -63,8 +65,9 @@
#include "BKE_library.h"
#include "BKE_idprop.h"
-
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h"
+#endif
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -78,10 +81,10 @@
/* ******************* Constraint Channels ********************** */
/* Constraint Channels exist in one of two places:
* - Under Action Channels in an Action (act->chanbase->achan->constraintChannels)
- * - Under Object without object-level action yet (ob->constraintChannels)
+ * - Under Object without Object-level Action yet (ob->constraintChannels)
*
- * The main purpose that constraint channels serve is to act as a link
- * between an IPO-block which
+ * The main purpose that Constraint Channels serve is to act as a link
+ * between an IPO-block (which provides values to interpolate between for some settings)
*/
/* ------------ Data Management ----------- */
@@ -137,7 +140,7 @@ bConstraintChannel *get_constraint_channel (ListBase *list, const char name[])
{
bConstraintChannel *chan;
- if(list) {
+ if (list) {
for (chan = list->first; chan; chan=chan->next) {
if (!strcmp(name, chan->name)) {
return chan;
@@ -177,11 +180,11 @@ void do_constraint_channels (ListBase *conbase, ListBase *chanbase, float ctime,
for (con=conbase->first; con; con=con->next) {
Ipo *ipo= NULL;
- if(con->flag & CONSTRAINT_OWN_IPO)
+ if (con->flag & CONSTRAINT_OWN_IPO)
ipo= con->ipo;
else {
bConstraintChannel *chan = get_constraint_channel(chanbase, con->name);
- if(chan) ipo= chan->ipo;
+ if (chan) ipo= chan->ipo;
}
if (ipo) {
@@ -200,7 +203,24 @@ void do_constraint_channels (ListBase *conbase, ListBase *chanbase, float ctime,
break;
case CO_HEADTAIL:
{
- con->headtail = icu->curval;
+ /* we need to check types of constraints that can get this here, as user
+ * may have created an IPO-curve for this from IPO-editor but for a constraint
+ * that cannot support this
+ */
+ switch (con->type) {
+ /* supported constraints go here... */
+ case CONSTRAINT_TYPE_LOCLIKE:
+ case CONSTRAINT_TYPE_TRACKTO:
+ case CONSTRAINT_TYPE_MINMAX:
+ case CONSTRAINT_TYPE_STRETCHTO:
+ case CONSTRAINT_TYPE_DISTLIMIT:
+ con->headtail = icu->curval;
+ break;
+
+ default:
+ /* not supported */
+ break;
+ }
}
break;
}
@@ -221,55 +241,7 @@ void do_constraint_channels (ListBase *conbase, ListBase *chanbase, float ctime,
/* Find the first available, non-duplicate name for a given constraint */
void unique_constraint_name (bConstraint *con, ListBase *list)
{
- bConstraint *curcon;
- char tempname[64];
- int number = 1, exists = 0;
- char *dot;
-
- /* See if we are given an empty string */
- if (con->name[0] == '\0') {
- /* give it default name first */
- strcpy(con->name, "Const");
- }
-
- /* See if we even need to do this */
- if (list == NULL)
- return;
-
- for (curcon = list->first; curcon; curcon=curcon->next) {
- if (curcon != con) {
- if (!strcmp(curcon->name, con->name)) {
- exists = 1;
- break;
- }
- }
- }
-
- if (exists == 0)
- return;
-
- /* Strip off the suffix */
- dot = strchr(con->name, '.');
- if (dot)
- *dot=0;
-
- for (number = 1; number <= 999; number++) {
- sprintf(tempname, "%s.%03d", con->name, number);
-
- exists = 0;
- for (curcon=list->first; curcon; curcon=curcon->next) {
- if (con != curcon) {
- if (strcmp(curcon->name, tempname)==0) {
- exists = 1;
- break;
- }
- }
- }
- if (exists == 0) {
- strcpy(con->name, tempname);
- return;
- }
- }
+ BLI_uniquename(list, con, "Const", offsetof(bConstraint, name), 32);
}
/* ----------------- Evaluation Loop Preparation --------------- */
@@ -337,7 +309,7 @@ void constraints_clear_evalob (bConstraintOb *cob)
/* calculate delta of constraints evaluation */
Mat4Invert(imat, cob->startmat);
- Mat4MulMat4(delta, cob->matrix, imat);
+ Mat4MulMat4(delta, imat, cob->matrix);
/* copy matrices back to source */
switch (cob->type) {
@@ -395,19 +367,12 @@ void constraint_mat_convertspace (Object *ob, bPoseChannel *pchan, float mat[][4
case CONSTRAINT_SPACE_WORLD: /* ---------- FROM WORLDSPACE ---------- */
{
/* world to pose */
- if (to==CONSTRAINT_SPACE_POSE || to==CONSTRAINT_SPACE_LOCAL || to==CONSTRAINT_SPACE_PARLOCAL) {
- Mat4Invert(imat, ob->obmat);
- Mat4CpyMat4(tempmat, mat);
- Mat4MulMat4(mat, tempmat, imat);
- }
+ Mat4Invert(imat, ob->obmat);
+ Mat4CpyMat4(tempmat, mat);
+ Mat4MulMat4(mat, tempmat, imat);
- /* pose to local */
- if (to == CONSTRAINT_SPACE_LOCAL) {
- /* call self with slightly different values */
- constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to);
- }
- /* pose to local + parent */
- else if (to == CONSTRAINT_SPACE_PARLOCAL) {
+ /* use pose-space as stepping stone for other spaces... */
+ if (ELEM(to, CONSTRAINT_SPACE_LOCAL, CONSTRAINT_SPACE_PARLOCAL)) {
/* call self with slightly different values */
constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to);
}
@@ -473,69 +438,66 @@ void constraint_mat_convertspace (Object *ob, bPoseChannel *pchan, float mat[][4
break;
case CONSTRAINT_SPACE_LOCAL: /* ------------ FROM LOCALSPACE --------- */
{
- /* local to pose */
- if (to==CONSTRAINT_SPACE_POSE || to==CONSTRAINT_SPACE_WORLD) {
- /* do inverse procedure that was done for pose to local */
- if (pchan->bone) {
- /* we need the posespace_matrix = local_matrix + (parent_posespace_matrix + restpos) */
- if (pchan->parent) {
- float offs_bone[4][4];
-
- /* construct offs_bone the same way it is done in armature.c */
- Mat4CpyMat3(offs_bone, pchan->bone->bone_mat);
- VECCOPY(offs_bone[3], pchan->bone->head);
- offs_bone[3][1]+= pchan->bone->parent->length;
+ /* local to pose - do inverse procedure that was done for pose to local */
+ if (pchan->bone) {
+ /* we need the posespace_matrix = local_matrix + (parent_posespace_matrix + restpos) */
+ if (pchan->parent) {
+ float offs_bone[4][4];
+
+ /* construct offs_bone the same way it is done in armature.c */
+ Mat4CpyMat3(offs_bone, pchan->bone->bone_mat);
+ VECCOPY(offs_bone[3], pchan->bone->head);
+ offs_bone[3][1]+= pchan->bone->parent->length;
+
+ if (pchan->bone->flag & BONE_HINGE) {
+ /* pose_mat = par_pose-space_location * chan_mat */
+ float tmat[4][4];
- if (pchan->bone->flag & BONE_HINGE) {
- /* pose_mat = par_pose-space_location * chan_mat */
- float tmat[4][4];
-
- /* the rotation of the parent restposition */
- Mat4CpyMat4(tmat, pchan->bone->parent->arm_mat);
-
- /* the location of actual parent transform */
- VECCOPY(tmat[3], offs_bone[3]);
- offs_bone[3][0]= offs_bone[3][1]= offs_bone[3][2]= 0.0f;
- Mat4MulVecfl(pchan->parent->pose_mat, tmat[3]);
-
- Mat4MulMat4(diff_mat, offs_bone, tmat);
- Mat4CpyMat4(tempmat, mat);
- Mat4MulMat4(mat, tempmat, diff_mat);
- }
- else {
- /* pose_mat = par_pose_mat * bone_mat * chan_mat */
- Mat4MulMat4(diff_mat, offs_bone, pchan->parent->pose_mat);
- Mat4CpyMat4(tempmat, mat);
- Mat4MulMat4(mat, tempmat, diff_mat);
- }
+ /* the rotation of the parent restposition */
+ Mat4CpyMat4(tmat, pchan->bone->parent->arm_mat);
+
+ /* the location of actual parent transform */
+ VECCOPY(tmat[3], offs_bone[3]);
+ offs_bone[3][0]= offs_bone[3][1]= offs_bone[3][2]= 0.0f;
+ Mat4MulVecfl(pchan->parent->pose_mat, tmat[3]);
+
+ Mat4MulMat4(diff_mat, offs_bone, tmat);
+ Mat4CpyMat4(tempmat, mat);
+ Mat4MulMat4(mat, tempmat, diff_mat);
}
else {
- Mat4CpyMat4(diff_mat, pchan->bone->arm_mat);
-
+ /* pose_mat = par_pose_mat * bone_mat * chan_mat */
+ Mat4MulMat4(diff_mat, offs_bone, pchan->parent->pose_mat);
Mat4CpyMat4(tempmat, mat);
Mat4MulMat4(mat, tempmat, diff_mat);
}
}
+ else {
+ Mat4CpyMat4(diff_mat, pchan->bone->arm_mat);
+
+ Mat4CpyMat4(tempmat, mat);
+ Mat4MulMat4(mat, tempmat, diff_mat);
+ }
}
- /* local to world */
- if (to == CONSTRAINT_SPACE_WORLD) {
+
+ /* use pose-space as stepping stone for other spaces */
+ if (ELEM(to, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_PARLOCAL)) {
/* call self with slightly different values */
constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to);
- }
+ }
}
break;
case CONSTRAINT_SPACE_PARLOCAL: /* -------------- FROM LOCAL WITH PARENT ---------- */
{
- /* local to pose */
- if (to==CONSTRAINT_SPACE_POSE || to==CONSTRAINT_SPACE_WORLD) {
- if (pchan->bone) {
- Mat4CpyMat4(diff_mat, pchan->bone->arm_mat);
- Mat4CpyMat4(tempmat, mat);
- Mat4MulMat4(mat, diff_mat, tempmat);
- }
+ /* local + parent to pose */
+ if (pchan->bone) {
+ Mat4CpyMat4(diff_mat, pchan->bone->arm_mat);
+ Mat4CpyMat4(tempmat, mat);
+ Mat4MulMat4(mat, diff_mat, tempmat);
}
- /* local to world */
- if (to == CONSTRAINT_SPACE_WORLD) {
+
+ /* use pose-space as stepping stone for other spaces */
+ if (ELEM(to, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_LOCAL)) {
/* call self with slightly different values */
constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to);
}
@@ -586,8 +548,8 @@ static void contarget_get_mesh_mat (Object *ob, char *substring, float mat[][4])
if (dgroup < 0) return;
/* get DerivedMesh */
- if (G.obedit && G.editMesh) {
- /* we are in editmode, so get a special derived mesh */
+ if ((G.obedit == ob) && (G.editMesh)) {
+ /* target is in editmode, so get a special derived mesh */
dm = CDDM_from_editmesh(G.editMesh, ob->data);
}
else {
@@ -880,7 +842,7 @@ static void default_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstrain
if (nocopy == 0) { \
datatar= ct->tar; \
strcpy(datasubtarget, ct->subtarget); \
- con->tarspace= ct->space; \
+ con->tarspace= (char)ct->space; \
} \
\
BLI_freelinkN(list, ct); \
@@ -900,7 +862,7 @@ static void default_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstrain
bConstraintTarget *ctn = ct->next; \
if (nocopy == 0) { \
datatar= ct->tar; \
- con->tarspace= ct->space; \
+ con->tarspace= (char)ct->space; \
} \
\
BLI_freelinkN(list, ct); \
@@ -920,7 +882,7 @@ static void childof_new_data (void *cdata)
Mat4One(data->invmat);
}
-static void childof_get_tars (bConstraint *con, ListBase *list)
+static int childof_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bChildOfConstraint *data= con->data;
@@ -928,7 +890,11 @@ static void childof_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void childof_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -1018,7 +984,7 @@ static void trackto_new_data (void *cdata)
data->reserved2 = UP_Z;
}
-static void trackto_get_tars (bConstraint *con, ListBase *list)
+static int trackto_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bTrackToConstraint *data= con->data;
@@ -1026,7 +992,11 @@ static void trackto_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void trackto_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -1124,9 +1094,9 @@ static void vectomat (float *vec, float *target_up, short axis, short upflag, sh
/* identity matrix - don't do anything if the two axes are the same */
else {
m[0][0]= m[1][1]= m[2][2]= 1.0;
- m[0][1]= m[0][2]= m[0][3]= 0.0;
- m[1][0]= m[1][2]= m[1][3]= 0.0;
- m[2][0]= m[2][1]= m[2][3]= 0.0;
+ m[0][1]= m[0][2]= 0.0;
+ m[1][0]= m[1][2]= 0.0;
+ m[2][0]= m[2][1]= 0.0;
}
}
@@ -1195,16 +1165,20 @@ static void kinematic_new_data (void *cdata)
data->flag= CONSTRAINT_IK_TIP|CONSTRAINT_IK_STRETCH|CONSTRAINT_IK_POS;
}
-static void kinematic_get_tars (bConstraint *con, ListBase *list)
+static int kinematic_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bKinematicConstraint *data= con->data;
bConstraintTarget *ct;
- /* standard target-getting macro for single-target constraints */
+ /* standard target-getting macro for single-target constraints is used twice here */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
SINGLETARGET_GET_TARS(con, data->poletar, data->polesubtarget, ct, list)
+
+ return 2;
}
+
+ return 0;
}
static void kinematic_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -1273,7 +1247,7 @@ static void followpath_new_data (void *cdata)
data->followflag = 0;
}
-static void followpath_get_tars (bConstraint *con, ListBase *list)
+static int followpath_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bFollowPathConstraint *data= con->data;
@@ -1281,7 +1255,11 @@ static void followpath_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints without subtargets */
SINGLETARGETNS_GET_TARS(con, data->tar, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void followpath_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -1301,7 +1279,7 @@ static void followpath_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstr
if (VALID_CONS_TARGET(ct)) {
Curve *cu= ct->tar->data;
- float q[4], vec[4], dir[3], *quat, x1;
+ float q[4], vec[4], dir[3], quat[4], x1;
float totmat[4][4];
float curvetime;
@@ -1326,7 +1304,7 @@ static void followpath_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstr
if ( where_on_path(ct->tar, curvetime, vec, dir) ) {
if (data->followflag) {
- quat= vectoquat(dir, (short) data->trackflag, (short) data->upflag);
+ vectoquat(dir, (short) data->trackflag, (short) data->upflag, quat);
Normalize(dir);
q[0]= (float)cos(0.5*vec[3]);
@@ -1456,9 +1434,9 @@ static void rotlimit_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *t
Mat4ToEul(cob->matrix, eul);
/* eulers: radians to degrees! */
- eul[0] = (eul[0] / M_PI * 180);
- eul[1] = (eul[1] / M_PI * 180);
- eul[2] = (eul[2] / M_PI * 180);
+ eul[0] = (float)(eul[0] / M_PI * 180);
+ eul[1] = (float)(eul[1] / M_PI * 180);
+ eul[2] = (float)(eul[2] / M_PI * 180);
/* limiting of euler values... */
if (data->flag & LIMIT_XROT) {
@@ -1484,9 +1462,9 @@ static void rotlimit_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *t
}
/* eulers: degrees to radians ! */
- eul[0] = (eul[0] / 180 * M_PI);
- eul[1] = (eul[1] / 180 * M_PI);
- eul[2] = (eul[2] / 180 * M_PI);
+ eul[0] = (float)(eul[0] / 180 * M_PI);
+ eul[1] = (float)(eul[1] / 180 * M_PI);
+ eul[2] = (float)(eul[2] / 180 * M_PI);
LocEulSizeToMat4(cob->matrix, loc, eul, size);
}
@@ -1574,7 +1552,7 @@ static void loclike_new_data (void *cdata)
data->flag = LOCLIKE_X|LOCLIKE_Y|LOCLIKE_Z;
}
-static void loclike_get_tars (bConstraint *con, ListBase *list)
+static int loclike_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bLocateLikeConstraint *data= con->data;
@@ -1582,7 +1560,11 @@ static void loclike_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void loclike_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -1652,7 +1634,7 @@ static void rotlike_new_data (void *cdata)
data->flag = ROTLIKE_X|ROTLIKE_Y|ROTLIKE_Z;
}
-static void rotlike_get_tars (bConstraint *con, ListBase *list)
+static int rotlike_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bRotateLikeConstraint *data= con->data;
@@ -1660,7 +1642,11 @@ static void rotlike_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void rotlike_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -1749,7 +1735,7 @@ static void sizelike_new_data (void *cdata)
data->flag = SIZELIKE_X|SIZELIKE_Y|SIZELIKE_Z;
}
-static void sizelike_get_tars (bConstraint *con, ListBase *list)
+static int sizelike_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bSizeLikeConstraint *data= con->data;
@@ -1757,7 +1743,11 @@ static void sizelike_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void sizelike_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -1824,6 +1814,7 @@ static bConstraintTypeInfo CTI_SIZELIKE = {
sizelike_evaluate /* evaluate */
};
+
/* ----------- Python Constraint -------------- */
static void pycon_free (bConstraint *con)
@@ -1863,14 +1854,18 @@ static void pycon_new_data (void *cdata)
data->prop->type = IDP_GROUP;
}
-static void pycon_get_tars (bConstraint *con, ListBase *list)
+static int pycon_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bPythonConstraint *data= con->data;
list->first = data->targets.first;
list->last = data->targets.last;
+
+ return data->tarnum;
}
+
+ return 0;
}
/* Whether this approach is maintained remains to be seen (aligorith) */
@@ -1892,7 +1887,12 @@ static void pycon_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstraintT
* this matrix if it needs to do so
*/
constraint_target_to_mat4(ct->tar, ct->subtarget, ct->matrix, CONSTRAINT_SPACE_WORLD, ct->space, con->headtail);
- BPY_pyconstraint_target(data, ct);
+
+ /* only execute target calculation if allowed */
+#ifndef DISABLE_PYTHON
+ if (G.f & G_DOSCRIPTLINKS)
+ BPY_pyconstraint_target(data, ct);
+#endif
}
else if (ct)
Mat4One(ct->matrix);
@@ -1900,8 +1900,14 @@ static void pycon_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstraintT
static void pycon_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
{
+#ifdef DISABLE_PYTHON
+ return;
+#else
bPythonConstraint *data= con->data;
+ /* only evaluate in python if we're allowed to do so */
+ if ((G.f & G_DOSCRIPTLINKS)==0) return;
+
/* currently removed, until I this can be re-implemented for multiple targets */
#if 0
/* Firstly, run the 'driver' function which has direct access to the objects involved
@@ -1913,6 +1919,7 @@ static void pycon_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targ
/* Now, run the actual 'constraint' function, which should only access the matrices */
BPY_pyconstraint_eval(data, cob, targets);
+#endif /* DISABLE_PYTHON */
}
static bConstraintTypeInfo CTI_PYTHON = {
@@ -1946,7 +1953,7 @@ static void actcon_new_data (void *cdata)
data->type = 20;
}
-static void actcon_get_tars (bConstraint *con, ListBase *list)
+static int actcon_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bActionConstraint *data= con->data;
@@ -1954,7 +1961,11 @@ static void actcon_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void actcon_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -2031,8 +2042,7 @@ static void actcon_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstraint
Mat4CpyMat4(ct->matrix, tchan->chan_mat);
/* Clean up */
- free_pose_channels(pose);
- MEM_freeN(pose);
+ free_pose(pose);
}
else if (cob->type == CONSTRAINT_OBTYPE_OBJECT) {
/* evaluate using workob */
@@ -2086,7 +2096,7 @@ static void locktrack_new_data (void *cdata)
data->lockflag = LOCK_Z;
}
-static void locktrack_get_tars (bConstraint *con, ListBase *list)
+static int locktrack_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bLockTrackConstraint *data= con->data;
@@ -2094,7 +2104,11 @@ static void locktrack_get_tars (bConstraint *con, ListBase *list)
/* the following macro is used for all standard single-target constraints */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void locktrack_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -2425,6 +2439,122 @@ static bConstraintTypeInfo CTI_LOCKTRACK = {
locktrack_evaluate /* evaluate */
};
+/* ---------- Limit Distance Constraint ----------- */
+
+static void distlimit_new_data (void *cdata)
+{
+ bDistLimitConstraint *data= (bDistLimitConstraint *)cdata;
+
+ data->dist= 0.0;
+}
+
+static int distlimit_get_tars (bConstraint *con, ListBase *list)
+{
+ if (con && list) {
+ bDistLimitConstraint *data= con->data;
+ bConstraintTarget *ct;
+
+ /* standard target-getting macro for single-target constraints */
+ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
+ }
+
+ return 0;
+}
+
+static void distlimit_flush_tars (bConstraint *con, ListBase *list, short nocopy)
+{
+ if (con && list) {
+ bDistLimitConstraint *data= con->data;
+ bConstraintTarget *ct= list->first;
+
+ /* the following macro is used for all standard single-target constraints */
+ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
+ }
+}
+
+static void distlimit_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
+{
+ bDistLimitConstraint *data= con->data;
+ bConstraintTarget *ct= targets->first;
+
+ /* only evaluate if there is a target */
+ if (VALID_CONS_TARGET(ct)) {
+ float dvec[3], dist=0.0f, sfac=1.0f;
+ short clamp_surf= 0;
+
+ /* calculate our current distance from the target */
+ dist= VecLenf(cob->matrix[3], ct->matrix[3]);
+
+ /* set distance (flag is only set when user demands it) */
+ if (data->dist == 0)
+ data->dist= dist;
+
+ /* check if we're which way to clamp from, and calculate interpolation factor (if needed) */
+ if (data->mode == LIMITDIST_OUTSIDE) {
+ /* if inside, then move to surface */
+ if (dist <= data->dist) {
+ clamp_surf= 1;
+ sfac= data->dist / dist;
+ }
+ /* if soft-distance is enabled, start fading once owner is dist+softdist from the target */
+ else if (data->flag & LIMITDIST_USESOFT) {
+ if (dist <= (data->dist + data->soft)) {
+
+ }
+ }
+ }
+ else if (data->mode == LIMITDIST_INSIDE) {
+ /* if outside, then move to surface */
+ if (dist >= data->dist) {
+ clamp_surf= 1;
+ sfac= data->dist / dist;
+ }
+ /* if soft-distance is enabled, start fading once owner is dist-soft from the target */
+ else if (data->flag & LIMITDIST_USESOFT) {
+ // FIXME: there's a problem with "jumping" when this kicks in
+ if (dist >= (data->dist - data->soft)) {
+ sfac = (float)( data->soft*(1.0 - exp(-(dist - data->dist)/data->soft)) + data->dist );
+ sfac /= dist;
+
+ clamp_surf= 1;
+ }
+ }
+ }
+ else {
+ if (IS_EQ(dist, data->dist)==0) {
+ clamp_surf= 1;
+ sfac= data->dist / dist;
+ }
+ }
+
+ /* clamp to 'surface' (i.e. move owner so that dist == data->dist) */
+ if (clamp_surf) {
+ /* simply interpolate along line formed by target -> owner */
+ VecLerpf(dvec, ct->matrix[3], cob->matrix[3], sfac);
+
+ /* copy new vector onto owner */
+ VECCOPY(cob->matrix[3], dvec);
+ }
+ }
+}
+
+static bConstraintTypeInfo CTI_DISTLIMIT = {
+ CONSTRAINT_TYPE_DISTLIMIT, /* type */
+ sizeof(bDistLimitConstraint), /* size */
+ "Limit Distance", /* name */
+ "bDistLimitConstraint", /* struct name */
+ NULL, /* free data */
+ NULL, /* relink data */
+ NULL, /* copy data */
+ distlimit_new_data, /* new data */
+ distlimit_get_tars, /* get constraint targets */
+ distlimit_flush_tars, /* flush constraint targets */
+ default_get_tarmat, /* get a target matrix */
+ distlimit_evaluate /* evaluate */
+};
+
/* ---------- Stretch To ------------ */
static void stretchto_new_data (void *cdata)
@@ -2437,7 +2567,7 @@ static void stretchto_new_data (void *cdata)
data->bulge = 1.0;
}
-static void stretchto_get_tars (bConstraint *con, ListBase *list)
+static int stretchto_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bStretchToConstraint *data= con->data;
@@ -2445,7 +2575,11 @@ static void stretchto_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void stretchto_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -2613,7 +2747,7 @@ static void minmax_new_data (void *cdata)
data->flag = 0;
}
-static void minmax_get_tars (bConstraint *con, ListBase *list)
+static int minmax_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bMinMaxConstraint *data= con->data;
@@ -2621,7 +2755,11 @@ static void minmax_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void minmax_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -2743,7 +2881,7 @@ static void rbj_new_data (void *cdata)
data->type=1;
}
-static void rbj_get_tars (bConstraint *con, ListBase *list)
+static int rbj_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bRigidBodyJointConstraint *data= con->data;
@@ -2751,7 +2889,11 @@ static void rbj_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints without subtargets */
SINGLETARGETNS_GET_TARS(con, data->tar, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void rbj_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -2782,7 +2924,7 @@ static bConstraintTypeInfo CTI_RIGIDBODYJOINT = {
/* -------- Clamp To ---------- */
-static void clampto_get_tars (bConstraint *con, ListBase *list)
+static int clampto_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bClampToConstraint *data= con->data;
@@ -2790,7 +2932,11 @@ static void clampto_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints without subtargets */
SINGLETARGETNS_GET_TARS(con, data->tar, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void clampto_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -2955,7 +3101,7 @@ static void transform_new_data (void *cdata)
data->map[2]= 2;
}
-static void transform_get_tars (bConstraint *con, ListBase *list)
+static int transform_get_tars (bConstraint *con, ListBase *list)
{
if (con && list) {
bTransformConstraint *data= con->data;
@@ -2963,7 +3109,11 @@ static void transform_get_tars (bConstraint *con, ListBase *list)
/* standard target-getting macro for single-target constraints */
SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
+
+ return 1;
}
+
+ return 0;
}
static void transform_flush_tars (bConstraint *con, ListBase *list, short nocopy)
@@ -2990,11 +3140,13 @@ static void transform_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *
/* obtain target effect */
switch (data->from) {
- case 2: /* scale */
+ case 2: /* scale */
Mat4ToSize(ct->matrix, dvec);
break;
- case 1: /* rotation */
+ case 1: /* rotation (convert to degrees first) */
Mat4ToEul(ct->matrix, dvec);
+ for (i=0; i<3; i++)
+ dvec[i] = (float)(dvec[i] / M_PI * 180);
break;
default: /* location */
VecCopyf(dvec, ct->matrix[3]);
@@ -3004,7 +3156,7 @@ static void transform_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *
/* extract components of owner's matrix */
VECCOPY(loc, cob->matrix[3]);
Mat4ToEul(cob->matrix, eul);
- Mat4ToSize(cob->matrix, size);
+ Mat4ToSize(cob->matrix, size);
/* determine where in range current transforms lie */
if (data->expo) {
@@ -3026,17 +3178,6 @@ static void transform_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *
}
}
- /* convert radian<->degree */
- if (data->from==1 && data->to==0) {
- /* from radians to degrees */
- for (i=0; i<3; i++)
- sval[i] = sval[i] / M_PI * 180;
- }
- else if (data->from==0 && data->to==1) {
- /* from degrees to radians */
- for (i=0; i<3; i++)
- sval[i] = sval[i] / 180 * M_PI;
- }
/* apply transforms */
switch (data->to) {
@@ -3048,11 +3189,14 @@ static void transform_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *
for (i=0; i<3; i++) {
float tmin, tmax;
- /* convert destination min/max ranges from degrees to radians */
- tmin= data->to_min[i] / M_PI * 180;
- tmax= data->to_max[i] / M_PI * 180;
+ tmin= data->to_min[i];
+ tmax= data->to_max[i];
+ /* all values here should be in degrees */
eul[i]= tmin + (sval[data->map[i]] * (tmax - tmin));
+
+ /* now convert final value back to radians */
+ eul[i] = (float)(eul[i] / 180 * M_PI);
}
break;
default: /* location */
@@ -3110,12 +3254,12 @@ static void constraints_init_typeinfo () {
constraintsTypeInfo[11]= &CTI_PYTHON; /* Python/Script Constraint */
constraintsTypeInfo[12]= &CTI_ACTION; /* Action Constraint */
constraintsTypeInfo[13]= &CTI_LOCKTRACK; /* Locked-Track Constraint */
- constraintsTypeInfo[14]= NULL; /* 'Distance Limit' Constraint */
+ constraintsTypeInfo[14]= &CTI_DISTLIMIT; /* Limit Distance Constraint */
constraintsTypeInfo[15]= &CTI_STRETCHTO; /* StretchTo Constaint */
constraintsTypeInfo[16]= &CTI_MINMAX; /* Floor Constraint */
constraintsTypeInfo[17]= &CTI_RIGIDBODYJOINT; /* RigidBody Constraint */
constraintsTypeInfo[18]= &CTI_CLAMPTO; /* ClampTo Constraint */
- constraintsTypeInfo[19]= &CTI_TRANSFORM; /* Transformation Constraint */
+ constraintsTypeInfo[19]= &CTI_TRANSFORM; /* Transformation Constraint */
}
/* This function should be used for getting the appropriate type-info when only
@@ -3241,6 +3385,46 @@ void copy_constraints (ListBase *dst, ListBase *src)
}
}
+/* -------- Constraints and Proxies ------- */
+
+/* Rescue all constraints tagged as being CONSTRAINT_PROXY_LOCAL (i.e. added to bone that's proxy-synced in this file) */
+void extract_proxylocal_constraints (ListBase *dst, ListBase *src)
+{
+ bConstraint *con, *next;
+
+ /* for each tagged constraint, remove from src and move to dst */
+ for (con= src->first; con; con= next) {
+ next= con->next;
+
+ /* check if tagged */
+ if (con->flag & CONSTRAINT_PROXY_LOCAL) {
+ BLI_remlink(src, con);
+ BLI_addtail(dst, con);
+ }
+ }
+}
+
+/* Returns if the owner of the constraint is proxy-protected */
+short proxylocked_constraints_owner (Object *ob, bPoseChannel *pchan)
+{
+ /* Currently, constraints can only be on object or bone level */
+ if (ob && ob->proxy) {
+ if (ob->pose && pchan) {
+ bArmature *arm= ob->data;
+
+ /* On bone-level, check if bone is on proxy-protected layer */
+ if ((pchan->bone) && (pchan->bone->layer & arm->layer_protected))
+ return 1;
+ }
+ else {
+ /* FIXME: constraints on object-level are not handled well yet */
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
/* -------- Target-Matrix Stuff ------- */
/* This function is a relic from the prior implementations of the constraints system, when all
diff --git a/source/blender/blenkernel/intern/curve.c b/source/blender/blenkernel/intern/curve.c
index 90e65b629b4..1a671dfe771 100644
--- a/source/blender/blenkernel/intern/curve.c
+++ b/source/blender/blenkernel/intern/curve.c
@@ -247,7 +247,7 @@ void tex_space_curve(Curve *cu)
{
DispList *dl;
BoundBox *bb;
- float *data, min[3], max[3], loc[3], size[3];
+ float *fp, min[3], max[3], loc[3], size[3];
int tot, doit= 0;
if(cu->bb==NULL) cu->bb= MEM_callocN(sizeof(BoundBox), "boundbox");
@@ -262,10 +262,10 @@ void tex_space_curve(Curve *cu)
else tot= dl->nr*dl->parts;
if(tot) doit= 1;
- data= dl->verts;
+ fp= dl->verts;
while(tot--) {
- DO_MINMAX(data, min, max);
- data+= 3;
+ DO_MINMAX(fp, min, max);
+ fp += 3;
}
dl= dl->next;
}
@@ -348,9 +348,9 @@ void freeNurb(Nurb *nu)
if(nu->bp) MEM_freeN(nu->bp);
nu->bp= 0;
if(nu->knotsu) MEM_freeN(nu->knotsu);
- nu->knotsu= 0;
+ nu->knotsu= NULL;
if(nu->knotsv) MEM_freeN(nu->knotsv);
- nu->knotsv= 0;
+ nu->knotsv= NULL;
/* if(nu->trim.first) freeNurblist(&(nu->trim)); */
MEM_freeN(nu);
@@ -393,7 +393,7 @@ Nurb *duplicateNurb(Nurb *nu)
(BPoint*)MEM_mallocN((len)* sizeof(BPoint),"duplicateNurb3");
memcpy(newnu->bp, nu->bp, len*sizeof(BPoint));
- newnu->knotsu=newnu->knotsv= 0;
+ newnu->knotsu= newnu->knotsv= NULL;
if(nu->knotsu) {
len= KNOTSU(nu);
@@ -506,6 +506,7 @@ static void calcknots(float *knots, short aantal, short order, short type)
}
}
else if(type==2) {
+ /* Warning, the order MUST be 2 or 4, if this is not enforced, the displist will be corrupt */
if(order==4) {
k= 0.34;
for(a=0;a<t;a++) {
@@ -520,6 +521,9 @@ static void calcknots(float *knots, short aantal, short order, short type)
knots[a]= (float)floor(k);
}
}
+ else {
+ printf("bez nurb curve order is not 3 or 4, should never happen\n");
+ }
}
}
@@ -529,7 +533,8 @@ static void makecyclicknots(float *knots, short pnts, short order)
int a, b, order2, c;
if(knots==0) return;
- order2=order-1;
+
+ order2=order-1;
/* do first long rows (order -1), remove identical knots at endpoints */
if(order>2) {
@@ -549,26 +554,35 @@ static void makecyclicknots(float *knots, short pnts, short order)
}
-void makeknots(Nurb *nu, short uv, short type) /* 0: uniform, 1: endpoints, 2: bezier */
+/* type - 0: uniform, 1: endpoints, 2: bezier, note, cyclic nurbs are always uniform */
+void makeknots(Nurb *nu, short uv, short type)
{
if( (nu->type & 7)==CU_NURBS ) {
- if(uv & 1) {
+ if(uv == 1) {
if(nu->knotsu) MEM_freeN(nu->knotsu);
- if(nu->pntsu>1) {
+ if(check_valid_nurb_u(nu)) {
nu->knotsu= MEM_callocN(4+sizeof(float)*KNOTSU(nu), "makeknots");
- calcknots(nu->knotsu, nu->pntsu, nu->orderu, type);
- if(nu->flagu & 1) makecyclicknots(nu->knotsu, nu->pntsu, nu->orderu);
+ if(nu->flagu & CU_CYCLIC) {
+ calcknots(nu->knotsu, nu->pntsu, nu->orderu, 0); /* cyclic should be uniform */
+ makecyclicknots(nu->knotsu, nu->pntsu, nu->orderu);
+ } else {
+ calcknots(nu->knotsu, nu->pntsu, nu->orderu, type);
+ }
}
- else nu->knotsu= 0;
- }
- if(uv & 2) {
+ else nu->knotsu= NULL;
+
+ } else if(uv == 2) {
if(nu->knotsv) MEM_freeN(nu->knotsv);
- if(nu->pntsv>1) {
+ if(check_valid_nurb_v(nu)) {
nu->knotsv= MEM_callocN(4+sizeof(float)*KNOTSV(nu), "makeknots");
- calcknots(nu->knotsv, nu->pntsv, nu->orderv, type);
- if(nu->flagv & 1) makecyclicknots(nu->knotsv, nu->pntsv, nu->orderv);
+ if(nu->flagv & CU_CYCLIC) {
+ calcknots(nu->knotsv, nu->pntsv, nu->orderv, 0); /* cyclic should be uniform */
+ makecyclicknots(nu->knotsv, nu->pntsv, nu->orderv);
+ } else {
+ calcknots(nu->knotsv, nu->pntsv, nu->orderv, type);
+ }
}
- else nu->knotsv= 0;
+ else nu->knotsv= NULL;
}
}
}
@@ -636,31 +650,31 @@ static void basisNurb(float t, short order, short pnts, float *knots, float *bas
}
-void makeNurbfaces(Nurb *nu, float *data, int rowstride)
-/* data has to be 3*4*resolu*resolv in size, and zero-ed */
+void makeNurbfaces(Nurb *nu, float *coord_array, int rowstride)
+/* coord_array has to be 3*4*resolu*resolv in size, and zero-ed */
{
BPoint *bp;
float *basisu, *basis, *basisv, *sum, *fp, *in;
float u, v, ustart, uend, ustep, vstart, vend, vstep, sumdiv;
int i, j, iofs, jofs, cycl, len, resolu, resolv;
int istart, iend, jsta, jen, *jstart, *jend, ratcomp;
-
- if(nu->knotsu==0 || nu->knotsv==0) return;
+
+ int totu = nu->pntsu*nu->resolu, totv = nu->pntsv*nu->resolv;
+
+ if(nu->knotsu==NULL || nu->knotsv==NULL) return;
if(nu->orderu>nu->pntsu) return;
if(nu->orderv>nu->pntsv) return;
- if(data==0) return;
-
+ if(coord_array==NULL) return;
+
/* allocate and initialize */
- len= nu->pntsu*nu->pntsv;
+ len = totu * totv;
if(len==0) return;
sum= (float *)MEM_callocN(sizeof(float)*len, "makeNurbfaces1");
-
- resolu= nu->resolu;
- resolv= nu->resolv;
- len= resolu*resolv;
+
+ len= totu*totv;
if(len==0) {
MEM_freeN(sum);
return;
@@ -676,46 +690,50 @@ void makeNurbfaces(Nurb *nu, float *data, int rowstride)
}
bp++;
}
-
+
fp= nu->knotsu;
ustart= fp[nu->orderu-1];
- if(nu->flagu & 1) uend= fp[nu->pntsu+nu->orderu-1];
+ if(nu->flagu & CU_CYCLIC) uend= fp[nu->pntsu+nu->orderu-1];
else uend= fp[nu->pntsu];
- ustep= (uend-ustart)/(resolu-1+(nu->flagu & 1));
+ ustep= (uend-ustart)/((nu->flagu & CU_CYCLIC) ? totu : totu - 1);
+
basisu= (float *)MEM_mallocN(sizeof(float)*KNOTSU(nu), "makeNurbfaces3");
fp= nu->knotsv;
vstart= fp[nu->orderv-1];
- if(nu->flagv & 1) vend= fp[nu->pntsv+nu->orderv-1];
+ if(nu->flagv & CU_CYCLIC) vend= fp[nu->pntsv+nu->orderv-1];
else vend= fp[nu->pntsv];
- vstep= (vend-vstart)/(resolv-1+(nu->flagv & 1));
+ vstep= (vend-vstart)/((nu->flagv & CU_CYCLIC) ? totv : totv - 1);
+
len= KNOTSV(nu);
- basisv= (float *)MEM_mallocN(sizeof(float)*len*resolv, "makeNurbfaces3");
- jstart= (int *)MEM_mallocN(sizeof(float)*resolv, "makeNurbfaces4");
- jend= (int *)MEM_mallocN(sizeof(float)*resolv, "makeNurbfaces5");
+ basisv= (float *)MEM_mallocN(sizeof(float)*len*totv, "makeNurbfaces3");
+ jstart= (int *)MEM_mallocN(sizeof(float)*totv, "makeNurbfaces4");
+ jend= (int *)MEM_mallocN(sizeof(float)*totv, "makeNurbfaces5");
/* precalculation of basisv and jstart,jend */
- if(nu->flagv & 1) cycl= nu->orderv-1;
+ if(nu->flagv & CU_CYCLIC) cycl= nu->orderv-1;
else cycl= 0;
v= vstart;
basis= basisv;
+ resolv= totv;
while(resolv--) {
basisNurb(v, nu->orderv, (short)(nu->pntsv+cycl), nu->knotsv, basis, jstart+resolv, jend+resolv);
basis+= KNOTSV(nu);
v+= vstep;
}
- if(nu->flagu & 1) cycl= nu->orderu-1;
+ if(nu->flagu & CU_CYCLIC) cycl= nu->orderu-1;
else cycl= 0;
- in= data;
+ in= coord_array;
u= ustart;
+ resolu= totu;
while(resolu--) {
basisNurb(u, nu->orderu, (short)(nu->pntsu+cycl), nu->knotsu, basisu, &istart, &iend);
basis= basisv;
- resolv= nu->resolv;
+ resolv= totv;
while(resolv--) {
jsta= jstart[resolv];
@@ -784,7 +802,7 @@ void makeNurbfaces(Nurb *nu, float *data, int rowstride)
basis+= KNOTSV(nu);
}
u+= ustep;
- if (rowstride!=0) in = (float*) (((unsigned char*) in) + (rowstride - 3*nu->resolv*sizeof(*in)));
+ if (rowstride!=0) in = (float*) (((unsigned char*) in) + (rowstride - 3*totv*sizeof(*in)));
}
/* free */
@@ -795,24 +813,28 @@ void makeNurbfaces(Nurb *nu, float *data, int rowstride)
MEM_freeN(jend);
}
-void makeNurbcurve(Nurb *nu, float *data, int resolu, int dim)
-/* data has to be dim*4*pntsu*resolu in size and zero-ed */
+void makeNurbcurve(Nurb *nu, float *coord_array, float *tilt_array, float *radius_array, int resolu)
+/* coord_array has to be 3*4*pntsu*resolu in size and zero-ed
+ * tilt_array and radius_array will be written to if valid */
{
BPoint *bp;
float u, ustart, uend, ustep, sumdiv;
- float *basisu, *sum, *fp, *in;
+ float *basisu, *sum, *fp;
+ float *coord_fp= coord_array, *tilt_fp= tilt_array, *radius_fp= radius_array;
int i, len, istart, iend, cycl;
- if(nu->knotsu==0) return;
+ if(nu->knotsu==NULL) return;
if(nu->orderu>nu->pntsu) return;
- if(data==0) return;
+ if(coord_array==0) return;
/* allocate and initialize */
len= nu->pntsu;
if(len==0) return;
sum= (float *)MEM_callocN(sizeof(float)*len, "makeNurbcurve1");
-
- resolu*= nu->pntsu;
+
+ resolu= (resolu*SEGMENTSU(nu));
+ if((nu->flagu & CU_CYCLIC)==0) resolu++;
+
if(resolu==0) {
MEM_freeN(sum);
return;
@@ -820,15 +842,15 @@ void makeNurbcurve(Nurb *nu, float *data, int resolu, int dim)
fp= nu->knotsu;
ustart= fp[nu->orderu-1];
- if(nu->flagu & 1) uend= fp[nu->pntsu+nu->orderu-1];
+ if(nu->flagu & CU_CYCLIC) uend= fp[nu->pntsu+nu->orderu-1];
else uend= fp[nu->pntsu];
- ustep= (uend-ustart)/(resolu-1+(nu->flagu & 1));
+ ustep= (uend-ustart)/(resolu - ((nu->flagu & CU_CYCLIC) ? 0 : 1));
+
basisu= (float *)MEM_mallocN(sizeof(float)*KNOTSU(nu), "makeNurbcurve3");
- if(nu->flagu & 1) cycl= nu->orderu-1;
+ if(nu->flagu & CU_CYCLIC) cycl= nu->orderu-1;
else cycl= 0;
- in= data;
u= ustart;
while(resolu--) {
@@ -863,17 +885,24 @@ void makeNurbcurve(Nurb *nu, float *data, int resolu, int dim)
if(*fp!=0.0) {
- in[0]+= (*fp) * bp->vec[0];
- in[1]+= (*fp) * bp->vec[1];
- if(dim>=3) {
- in[2]+= (*fp) * bp->vec[2];
- if(dim==4) in[3]+= (*fp) * bp->alfa;
- }
+ coord_fp[0]+= (*fp) * bp->vec[0];
+ coord_fp[1]+= (*fp) * bp->vec[1];
+ coord_fp[2]+= (*fp) * bp->vec[2];
+
+ if (tilt_fp)
+ (*tilt_fp) += (*fp) * bp->alfa;
+
+ if (radius_fp)
+ (*radius_fp) += (*fp) * bp->radius;
+
}
}
- in+= dim;
-
+ coord_fp+= 3;
+
+ if (tilt_fp) tilt_fp++;
+ if (radius_fp) radius_fp++;
+
u+= ustep;
}
@@ -918,7 +947,7 @@ float *make_orco_surf(Object *ob)
Nurb *nu;
int a, b, tot=0;
int sizeu, sizev;
- float *data, *orco;
+ float *fp, *coord_array;
/* first calculate the size of the datablock */
nu= cu->nurb.first;
@@ -932,8 +961,8 @@ float *make_orco_surf(Object *ob)
See also convertblender.c: init_render_surf()
*/
- sizeu = nu->resolu;
- sizev = nu->resolv;
+ sizeu = nu->pntsu*nu->resolu;
+ sizev = nu->pntsv*nu->resolv;
if (nu->flagu & CU_CYCLIC) sizeu++;
if (nu->flagv & CU_CYCLIC) sizev++;
if(nu->pntsv>1) tot+= sizeu * sizev;
@@ -941,13 +970,13 @@ float *make_orco_surf(Object *ob)
nu= nu->next;
}
/* makeNurbfaces wants zeros */
- data= orco= MEM_callocN(3*sizeof(float)*tot, "make_orco");
+ fp= coord_array= MEM_callocN(3*sizeof(float)*tot, "make_orco");
nu= cu->nurb.first;
while(nu) {
if(nu->pntsv>1) {
- sizeu = nu->resolu;
- sizev = nu->resolv;
+ sizeu = nu->pntsu*nu->resolu;
+ sizev = nu->pntsv*nu->resolv;
if (nu->flagu & CU_CYCLIC) sizeu++;
if (nu->flagv & CU_CYCLIC) sizev++;
@@ -955,20 +984,20 @@ float *make_orco_surf(Object *ob)
for(b=0; b< sizeu; b++) {
for(a=0; a< sizev; a++) {
- if(sizev <2) data[0]= 0.0f;
- else data[0]= -1.0f + 2.0f*((float)a)/(sizev - 1);
+ if(sizev <2) fp[0]= 0.0f;
+ else fp[0]= -1.0f + 2.0f*((float)a)/(sizev - 1);
- if(sizeu <2) data[1]= 0.0f;
- else data[1]= -1.0f + 2.0f*((float)b)/(sizeu - 1);
+ if(sizeu <2) fp[1]= 0.0f;
+ else fp[1]= -1.0f + 2.0f*((float)b)/(sizeu - 1);
- data[2]= 0.0;
+ fp[2]= 0.0;
- data+= 3;
+ fp+= 3;
}
}
}
else {
- float *_tdata= MEM_callocN(nu->resolu*nu->resolv*3*sizeof(float), "temp data");
+ float *_tdata= MEM_callocN((nu->pntsu*nu->resolu) * (nu->pntsv*nu->resolv) *3*sizeof(float), "temp data");
float *tdata= _tdata;
makeNurbfaces(nu, tdata, 0);
@@ -983,12 +1012,12 @@ float *make_orco_surf(Object *ob)
if (a==sizev-1 && (nu->flagv & CU_CYCLIC))
use_a= 0;
- tdata = _tdata + 3 * (use_b * nu->resolv + use_a);
+ tdata = _tdata + 3 * (use_b * (nu->pntsv*nu->resolv) + use_a);
- data[0]= (tdata[0]-cu->loc[0])/cu->size[0];
- data[1]= (tdata[1]-cu->loc[1])/cu->size[1];
- data[2]= (tdata[2]-cu->loc[2])/cu->size[2];
- data+= 3;
+ fp[0]= (tdata[0]-cu->loc[0])/cu->size[0];
+ fp[1]= (tdata[1]-cu->loc[1])/cu->size[1];
+ fp[2]= (tdata[2]-cu->loc[2])/cu->size[2];
+ fp+= 3;
}
}
@@ -998,7 +1027,7 @@ float *make_orco_surf(Object *ob)
nu= nu->next;
}
- return orco;
+ return coord_array;
}
@@ -1010,7 +1039,7 @@ float *make_orco_curve(Object *ob)
Curve *cu = ob->data;
DispList *dl;
int u, v, numVerts;
- float *fp, *orco;
+ float *fp, *coord_array;
int remakeDisp = 0;
if (!(cu->flag&CU_UV_ORCO) && cu->key && cu->key->refkey) {
@@ -1038,7 +1067,7 @@ float *make_orco_curve(Object *ob)
}
}
- fp= orco= MEM_mallocN(3*sizeof(float)*numVerts, "cu_orco");
+ fp= coord_array= MEM_mallocN(3*sizeof(float)*numVerts, "cu_orco");
for (dl=cu->disp.first; dl; dl=dl->next) {
if (dl->type==DL_INDEX3) {
for (u=0; u<dl->nr; u++, fp+=3) {
@@ -1071,9 +1100,12 @@ float *make_orco_curve(Object *ob)
fp[1]= 2.0f*v/(dl->nr-1) - 1.0f;
fp[2]= 0.0;
} else {
+ float *vert;
int realv= v % dl->nr;
-
- VECCOPY(fp, &dl->verts[(dl->nr*u + realv)*3]);
+ int realu= u % dl->parts;
+
+ vert= dl->verts + 3*(dl->nr*realu + realv);
+ VECCOPY(fp, vert);
fp[0]= (fp[0]-cu->loc[0])/cu->size[0];
fp[1]= (fp[1]-cu->loc[1])/cu->size[1];
@@ -1088,7 +1120,7 @@ float *make_orco_curve(Object *ob)
makeDispListCurveTypes(ob, 0);
}
- return orco;
+ return coord_array;
}
@@ -1415,7 +1447,7 @@ static void calc_bevel_sin_cos(float x1, float y1, float x2, float y2, float *si
}
-static void alfa_bezpart(BezTriple *prevbezt, BezTriple *bezt, Nurb *nu, float *data_a, int resolu)
+static void alfa_bezpart(BezTriple *prevbezt, BezTriple *bezt, Nurb *nu, float *tilt_array, float *radius_array, int resolu)
{
BezTriple *pprev, *next, *last;
float fac, dfac, t[4];
@@ -1425,14 +1457,14 @@ static void alfa_bezpart(BezTriple *prevbezt, BezTriple *bezt, Nurb *nu, float *
/* returns a point */
if(prevbezt==nu->bezt) {
- if(nu->flagu & 1) pprev= last;
+ if(nu->flagu & CU_CYCLIC) pprev= last;
else pprev= prevbezt;
}
else pprev= prevbezt-1;
/* next point */
if(bezt==last) {
- if(nu->flagu & 1) next= nu->bezt;
+ if(nu->flagu & CU_CYCLIC) next= nu->bezt;
else next= bezt;
}
else next= bezt+1;
@@ -1441,10 +1473,30 @@ static void alfa_bezpart(BezTriple *prevbezt, BezTriple *bezt, Nurb *nu, float *
dfac= 1.0f/(float)resolu;
for(a=0; a<resolu; a++, fac+= dfac) {
+ if (tilt_array) {
+ if (nu->tilt_interp==3) { /* May as well support for tilt also 2.47 ease interp */
+ tilt_array[a] = prevbezt->alfa + (bezt->alfa - prevbezt->alfa)*(3.0f*fac*fac - 2.0f*fac*fac*fac);
+ } else {
+ set_four_ipo(fac, t, nu->tilt_interp);
+ tilt_array[a]= t[0]*pprev->alfa + t[1]*prevbezt->alfa + t[2]*bezt->alfa + t[3]*next->alfa;
+ }
+ }
- set_four_ipo(fac, t, nu->tilt_interp);
-
- data_a[a]= t[0]*pprev->alfa + t[1]*prevbezt->alfa + t[2]*bezt->alfa + t[3]*next->alfa;
+ if (radius_array) {
+ if (nu->radius_interp==3) {
+ /* Support 2.47 ease interp
+ * Note! - this only takes the 2 points into account,
+ * giving much more localized results to changes in radius, sometimes you want that */
+ radius_array[a] = prevbezt->radius + (bezt->radius - prevbezt->radius)*(3.0f*fac*fac - 2.0f*fac*fac*fac);
+ } else {
+
+ /* reuse interpolation from tilt if we can */
+ if (tilt_array==NULL || nu->tilt_interp != nu->radius_interp) {
+ set_four_ipo(fac, t, nu->radius_interp);
+ }
+ radius_array[a]= t[0]*pprev->radius + t[1]*prevbezt->radius + t[2]*bezt->radius + t[3]*next->radius;
+ }
+ }
}
}
@@ -1462,13 +1514,19 @@ void makeBevelList(Object *ob)
BPoint *bp;
BevList *bl, *blnew, *blnext;
BevPoint *bevp, *bevp2, *bevp1 = NULL, *bevp0;
- float *data, *data_a, *v1, *v2, min, inp, x1, x2, y1, y2, vec[3];
+ float min, inp, x1, x2, y1, y2, vec[3];
+ float *coord_array, *tilt_array=NULL, *radius_array=NULL, *coord_fp, *tilt_fp=NULL, *radius_fp=NULL;
+ float *v1, *v2;
struct bevelsort *sortdata, *sd, *sd1;
- int a, b, len, nr, poly, resolu;
-
+ int a, b, nr, poly, resolu, len=0;
+ int do_tilt, do_radius;
+
/* this function needs an object, because of tflag and upflag */
cu= ob->data;
+ /* do we need to calculate the radius for each point? */
+ /* do_radius = (cu->bevobj || cu->taperobj || (cu->flag & CU_FRONT) || (cu->flag & CU_BACK)) ? 0 : 1; */
+
/* STEP 1: MAKE POLYS */
BLI_freelistN(&(cu->bev));
@@ -1476,8 +1534,15 @@ void makeBevelList(Object *ob)
else nu= cu->nurb.first;
while(nu) {
- if(nu->pntsu<=1) {
- bl= MEM_callocN(sizeof(BevList)+1*sizeof(BevPoint), "makeBevelList");
+
+ /* check if we will calculate tilt data */
+ do_tilt = ((nu->type & CU_2D) && (cu->flag & CU_3D)==0) ? 0 : 1;
+ do_radius = (do_tilt || cu->bevobj) ? 1 : 0; /* normal display uses the radius, better just to calculate them */
+
+ /* check we are a single point? also check we are not a surface and that the orderu is sane,
+ * enforced in the UI but can go wrong possibly */
+ if(!check_valid_nurb_u(nu)) {
+ bl= MEM_callocN(sizeof(BevList)+1*sizeof(BevPoint), "makeBevelList1");
BLI_addtail(&(cu->bev), bl);
bl->nr= 0;
} else {
@@ -1487,11 +1552,11 @@ void makeBevelList(Object *ob)
resolu= nu->resolu;
if((nu->type & 7)==CU_POLY) {
-
- bl= MEM_callocN(sizeof(BevList)+len*sizeof(BevPoint), "makeBevelList");
+ len= nu->pntsu;
+ bl= MEM_callocN(sizeof(BevList)+len*sizeof(BevPoint), "makeBevelList2");
BLI_addtail(&(cu->bev), bl);
- if(nu->flagu & 1) bl->poly= 0;
+ if(nu->flagu & CU_CYCLIC) bl->poly= 0;
else bl->poly= -1;
bl->nr= len;
bl->flag= 0;
@@ -1503,24 +1568,25 @@ void makeBevelList(Object *ob)
bevp->y= bp->vec[1];
bevp->z= bp->vec[2];
bevp->alfa= bp->alfa;
- bevp->f1= 1;
+ bevp->radius= bp->radius;
+ bevp->f1= SELECT;
bevp++;
bp++;
}
}
else if((nu->type & 7)==CU_BEZIER) {
- len= resolu*(nu->pntsu+ (nu->flagu & 1) -1)+1; /* in case last point is not cyclic */
- bl= MEM_callocN(sizeof(BevList)+len*sizeof(BevPoint), "makeBevelList");
+ len= resolu*(nu->pntsu+ (nu->flagu & CU_CYCLIC) -1)+1; /* in case last point is not cyclic */
+ bl= MEM_callocN(sizeof(BevList)+len*sizeof(BevPoint), "makeBevelBPoints");
BLI_addtail(&(cu->bev), bl);
- if(nu->flagu & 1) bl->poly= 0;
+ if(nu->flagu & CU_CYCLIC) bl->poly= 0;
else bl->poly= -1;
bevp= (BevPoint *)(bl+1);
a= nu->pntsu-1;
bezt= nu->bezt;
- if(nu->flagu & 1) {
+ if(nu->flagu & CU_CYCLIC) {
a++;
prevbezt= nu->bezt+(nu->pntsu-1);
}
@@ -1529,8 +1595,13 @@ void makeBevelList(Object *ob)
bezt++;
}
- data= MEM_mallocN(3*sizeof(float)*(resolu+1), "makeBevelList2");
- data_a= MEM_callocN(sizeof(float)*(resolu+1), "data_a");
+ coord_array= coord_fp= MEM_mallocN(3*sizeof(float)*(resolu+1), "makeBevelCoords");
+
+ if(do_tilt)
+ tilt_array= tilt_fp= MEM_callocN(sizeof(float)*(resolu+1), "makeBevelTilt");
+
+ if (do_radius)
+ radius_array= radius_fp= MEM_callocN(sizeof(float)*(resolu+1), "nakeBevelRadius");
while(a--) {
if(prevbezt->h2==HD_VECT && bezt->h1==HD_VECT) {
@@ -1539,6 +1610,7 @@ void makeBevelList(Object *ob)
bevp->y= prevbezt->vec[1][1];
bevp->z= prevbezt->vec[1][2];
bevp->alfa= prevbezt->alfa;
+ bevp->radius= prevbezt->radius;
bevp->f1= SELECT;
bevp->f2= 0;
bevp++;
@@ -1550,38 +1622,44 @@ void makeBevelList(Object *ob)
v2= bezt->vec[0];
/* always do all three, to prevent data hanging around */
- forward_diff_bezier(v1[0], v1[3], v2[0], v2[3], data, resolu, 3);
- forward_diff_bezier(v1[1], v1[4], v2[1], v2[4], data+1, resolu, 3);
- forward_diff_bezier(v1[2], v1[5], v2[2], v2[5], data+2, resolu, 3);
-
- if((nu->type & CU_2D)==0) {
- if(cu->flag & CU_3D) {
- alfa_bezpart(prevbezt, bezt, nu, data_a, resolu);
- }
- }
+ forward_diff_bezier(v1[0], v1[3], v2[0], v2[3], coord_array, resolu, 3);
+ forward_diff_bezier(v1[1], v1[4], v2[1], v2[4], coord_array+1, resolu, 3);
+ forward_diff_bezier(v1[2], v1[5], v2[2], v2[5], coord_array+2, resolu, 3);
+ if (do_tilt || do_radius)
+ alfa_bezpart(prevbezt, bezt, nu, tilt_array, radius_array, resolu);
/* indicate with handlecodes double points */
if(prevbezt->h1==prevbezt->h2) {
- if(prevbezt->h1==0 || prevbezt->h1==HD_VECT) bevp->f1= 1;
+ if(prevbezt->h1==0 || prevbezt->h1==HD_VECT) bevp->f1= SELECT;
}
else {
- if(prevbezt->h1==0 || prevbezt->h1==HD_VECT) bevp->f1= 1;
- else if(prevbezt->h2==0 || prevbezt->h2==HD_VECT) bevp->f1= 1;
+ if(prevbezt->h1==0 || prevbezt->h1==HD_VECT) bevp->f1= SELECT;
+ else if(prevbezt->h2==0 || prevbezt->h2==HD_VECT) bevp->f1= SELECT;
}
- v1= data;
- v2= data_a;
nr= resolu;
+ coord_fp = coord_array;
+ tilt_fp = tilt_array;
+ radius_fp = radius_array;
+
while(nr--) {
- bevp->x= v1[0];
- bevp->y= v1[1];
- bevp->z= v1[2];
- bevp->alfa= v2[0];
+ bevp->x= coord_fp[0];
+ bevp->y= coord_fp[1];
+ bevp->z= coord_fp[2];
+ coord_fp+=3;
+
+ if (do_tilt) {
+ bevp->alfa= *tilt_fp;
+ tilt_fp++;
+ }
+
+ if (do_radius) {
+ bevp->radius= *radius_fp;
+ radius_fp++;
+ }
bevp++;
- v1+=3;
- v2++;
}
bl->nr+= resolu;
@@ -1590,44 +1668,67 @@ void makeBevelList(Object *ob)
bezt++;
}
- MEM_freeN(data);
- MEM_freeN(data_a);
+ MEM_freeN(coord_array);
+ if (do_tilt) MEM_freeN(tilt_array);
+ if (do_radius) MEM_freeN(radius_array);
+ coord_array = tilt_array = radius_array = NULL;
- if((nu->flagu & 1)==0) { /* not cyclic: endpoint */
+ if((nu->flagu & CU_CYCLIC)==0) { /* not cyclic: endpoint */
bevp->x= prevbezt->vec[1][0];
bevp->y= prevbezt->vec[1][1];
bevp->z= prevbezt->vec[1][2];
bevp->alfa= prevbezt->alfa;
+ bevp->radius= prevbezt->radius;
bl->nr++;
}
-
}
else if((nu->type & 7)==CU_NURBS) {
if(nu->pntsv==1) {
- len= resolu*nu->pntsu;
- bl= MEM_mallocN(sizeof(BevList)+len*sizeof(BevPoint), "makeBevelList3");
+ len= (resolu*SEGMENTSU(nu));
+ if((nu->flagu & CU_CYCLIC)==0) len++;
+
+ bl= MEM_callocN(sizeof(BevList)+len*sizeof(BevPoint), "makeBevelList3");
BLI_addtail(&(cu->bev), bl);
bl->nr= len;
bl->flag= 0;
- if(nu->flagu & 1) bl->poly= 0;
+ if(nu->flagu & CU_CYCLIC) bl->poly= 0;
else bl->poly= -1;
bevp= (BevPoint *)(bl+1);
- data= MEM_callocN(4*sizeof(float)*len, "makeBevelList4"); /* has to be zero-ed */
- makeNurbcurve(nu, data, resolu, 4);
+ coord_array= coord_fp= MEM_callocN(3*sizeof(float)*len, "makeBevelCoords"); /* has to be zero-ed */
+
+ if(do_tilt)
+ tilt_array= tilt_fp= MEM_callocN(sizeof(float)*len, "makeBevelTilt");
+
+ if (do_radius)
+ radius_array= radius_fp= MEM_callocN(sizeof(float)*len, "nakeBevelRadius");
+
+ makeNurbcurve(nu, coord_array, tilt_array, radius_array, resolu);
- v1= data;
while(len--) {
- bevp->x= v1[0];
- bevp->y= v1[1];
- bevp->z= v1[2];
- bevp->alfa= v1[3];
+ bevp->x= coord_fp[0];
+ bevp->y= coord_fp[1];
+ bevp->z= coord_fp[2];
+ coord_fp+=3;
+
+ if (do_tilt) {
+ bevp->alfa= *tilt_fp;
+ tilt_fp++;
+ }
+
+ if (do_radius) {
+ bevp->radius= *radius_fp;
+ radius_fp++;
+ }
+
bevp->f1= bevp->f2= 0;
bevp++;
- v1+=4;
}
- MEM_freeN(data);
+ MEM_freeN(coord_array);
+ if (do_tilt) MEM_freeN(tilt_array);
+ if (do_radius) MEM_freeN(radius_array);
+ coord_array = tilt_array = radius_array = NULL;
}
}
}
@@ -1662,7 +1763,7 @@ void makeBevelList(Object *ob)
blnext= bl->next;
if(bl->nr && bl->flag) {
nr= bl->nr- bl->flag+1; /* +1 because vectorbezier sets flag too */
- blnew= MEM_mallocN(sizeof(BevList)+nr*sizeof(BevPoint), "makeBevelList");
+ blnew= MEM_mallocN(sizeof(BevList)+nr*sizeof(BevPoint), "makeBevelList4");
memcpy(blnew, bl, sizeof(BevList));
blnew->nr= 0;
BLI_remlink(&(cu->bev), bl);
@@ -1785,13 +1886,13 @@ void makeBevelList(Object *ob)
bevp2->cosa= bevp1->cosa;
if(cu->flag & CU_3D) { /* 3D */
- float *quat, q[4];
+ float quat[4], q[4];
vec[0]= bevp1->x - bevp2->x;
vec[1]= bevp1->y - bevp2->y;
vec[2]= bevp1->z - bevp2->z;
- quat= vectoquat(vec, 5, 1);
+ vectoquat(vec, 5, 1, quat);
Normalize(vec);
q[0]= (float)cos(0.5*bevp1->alfa);
@@ -1817,7 +1918,7 @@ void makeBevelList(Object *ob)
while(nr--) {
if(cu->flag & CU_3D) { /* 3D */
- float *quat, q[4];
+ float quat[4], q[4];
vec[0]= bevp2->x - bevp0->x;
vec[1]= bevp2->y - bevp0->y;
@@ -1825,7 +1926,7 @@ void makeBevelList(Object *ob)
Normalize(vec);
- quat= vectoquat(vec, 5, 1);
+ vectoquat(vec, 5, 1, quat);
q[0]= (float)cos(0.5*bevp1->alfa);
x1= (float)sin(0.5*bevp1->alfa);
@@ -1870,134 +1971,6 @@ void makeBevelList(Object *ob)
}
}
-/* calculates a bevel width (radius) for a particular subdivided curve part,
- * based on the radius value of the surrounding CVs */
-float calc_curve_subdiv_radius(Curve *cu, Nurb *nu, int cursubdiv)
-{
- BezTriple *bezt, *beztfirst, *beztlast, *beztnext, *beztprev;
- BPoint *bp, *bpfirst, *bplast;
- int resolu;
- float prevrad=0.0, nextrad=0.0, rad=0.0, ratio=0.0;
- int vectseg=0, subdivs=0;
-
- if((nu==NULL) || (nu->pntsu<=1)) return 1.0;
- bezt= nu->bezt;
- bp = nu->bp;
-
- if(G.rendering && cu->resolu_ren!=0) resolu= cu->resolu_ren;
- else resolu= nu->resolu;
-
- if(((nu->type & 7)==CU_BEZIER) && (bezt != NULL)) {
- beztfirst = nu->bezt;
- beztlast = nu->bezt + (nu->pntsu - 1);
-
- /* loop through the CVs to end up with a pointer to the CV before the subdiv in question, and a ratio
- * of how far that subdiv is between this CV and the next */
- while(bezt<=beztlast) {
- beztnext = bezt+1;
- beztprev = bezt-1;
- vectseg=0;
-
- if (subdivs==cursubdiv) {
- ratio= 0.0;
- break;
- }
-
- /* check to see if we're looking at a vector segment (no subdivisions) */
- if (nu->flagu & CU_CYCLIC) {
- if (bezt == beztfirst) {
- if ((beztlast->h2==HD_VECT) && (bezt->h1==HD_VECT)) vectseg = 1;
- } else {
- if ((beztprev->h2==HD_VECT) && (bezt->h1==HD_VECT)) vectseg = 1;
- }
- } else if ((bezt->h2==HD_VECT) && (beztnext->h1==HD_VECT)) vectseg = 1;
-
-
- if (vectseg==0) {
- /* if it's NOT a vector segment, check to see if the subdiv falls within the segment */
- subdivs += resolu;
-
- if (cursubdiv < subdivs) {
- ratio = 1.0 - ((subdivs - cursubdiv)/(float)resolu);
- break;
- }
- } else {
- /* must be a vector segment.. loop again! */
- subdivs += 1;
- }
-
- bezt++;
- }
-
- /* Now we have a nice bezt pointer to the CV that we want. But cyclic messes it up, so must correct for that..
- * (cyclic goes last-> first -> first+1 -> first+2 -> ...) */
- if (nu->flagu & CU_CYCLIC) {
- if (bezt == beztfirst) bezt = beztlast;
- else bezt--;
- }
-
- /* find the radii at the bounding CVs and interpolate between them based on ratio */
- rad = prevrad = bezt->radius;
-
- if ((bezt == beztlast) && (nu->flagu & CU_CYCLIC)) { /* loop around */
- bezt= beztfirst;
- } else if (bezt != beztlast) {
- bezt++;
- }
- nextrad = bezt->radius;
-
- }
- else if( ( ((nu->type & 7)==CU_NURBS) || ((nu->type & 7)==CU_POLY)) && (bp != NULL)) {
- /* follows similar algo as for bezt above */
- bpfirst = nu->bp;
- bplast = nu->bp + (nu->pntsu - 1);
-
- if ((nu->type & 7)==CU_POLY) resolu=1;
-
- while(bp<=bplast) {
- if (subdivs==cursubdiv) {
- ratio= 0.0;
- break;
- }
-
- subdivs += resolu;
-
- if (cursubdiv < subdivs) {
- ratio = 1.0 - ((subdivs - cursubdiv)/(float)resolu);
- break;
- }
-
- bp++;
- }
-
- if ( ((nu->type & 7)==CU_NURBS) && (nu->flagu & CU_CYCLIC)) {
- if (bp == bplast) bp = bpfirst;
- else bp++;
- }
-
- rad = prevrad = bp->radius;
-
- if ((bp == bplast) && (nu->flagu & CU_CYCLIC)) { /* loop around */
- bp= bpfirst;
- } else if (bp != bplast) {
- bp++;
- }
- nextrad = bp->radius;
-
- }
-
-
- if (nextrad != prevrad) {
- /* smooth interpolation */
- rad = prevrad + (nextrad-prevrad)*(3.0f*ratio*ratio - 2.0f*ratio*ratio*ratio);
- }
-
- if (rad > 0.0)
- return rad;
- else
- return 1.0;
-}
-
/* ****************** HANDLES ************** */
/*
@@ -2204,7 +2177,7 @@ void calchandlesNurb(Nurb *nu) /* first, if needed, set handle flags */
a= nu->pntsu;
bezt= nu->bezt;
- if(nu->flagu & 1) prev= bezt+(a-1);
+ if(nu->flagu & CU_CYCLIC) prev= bezt+(a-1);
else prev= 0;
next= bezt+1;
@@ -2212,7 +2185,7 @@ void calchandlesNurb(Nurb *nu) /* first, if needed, set handle flags */
calchandleNurb(bezt, prev, next, 0);
prev= bezt;
if(a==1) {
- if(nu->flagu & 1) next= nu->bezt;
+ if(nu->flagu & CU_CYCLIC) next= nu->bezt;
else next= 0;
}
else next++;
@@ -2366,9 +2339,9 @@ void sethandlesNurb(short code)
bezt= nu->bezt;
a= nu->pntsu;
while(a--) {
- if(bezt->f1 || bezt->f3) {
- if(bezt->f1) bezt->h1= code;
- if(bezt->f3) bezt->h2= code;
+ if((bezt->f1 & SELECT) || (bezt->f3 & SELECT)) {
+ if(bezt->f1 & SELECT) bezt->h1= code;
+ if(bezt->f3 & SELECT) bezt->h2= code;
if(bezt->h1!=bezt->h2) {
if ELEM(bezt->h1, HD_ALIGN, HD_AUTO) bezt->h1= HD_FREE;
if ELEM(bezt->h2, HD_ALIGN, HD_AUTO) bezt->h2= HD_FREE;
@@ -2396,8 +2369,8 @@ void sethandlesNurb(short code)
bezt= nu->bezt;
a= nu->pntsu;
while(a--) {
- if(bezt->f1 && bezt->h1) ok= 1;
- if(bezt->f3 && bezt->h2) ok= 1;
+ if((bezt->f1 & SELECT) && bezt->h1) ok= 1;
+ if((bezt->f3 & SELECT) && bezt->h2) ok= 1;
if(ok) break;
bezt++;
}
@@ -2413,8 +2386,8 @@ void sethandlesNurb(short code)
bezt= nu->bezt;
a= nu->pntsu;
while(a--) {
- if(bezt->f1) bezt->h1= ok;
- if(bezt->f3 ) bezt->h2= ok;
+ if(bezt->f1 & SELECT) bezt->h1= ok;
+ if(bezt->f3 & SELECT) bezt->h2= ok;
bezt++;
}
@@ -2603,3 +2576,63 @@ void curve_applyVertexCos(Curve *cu, ListBase *lb, float (*vertexCos)[3])
}
}
}
+
+int check_valid_nurb_u( struct Nurb *nu )
+{
+ if (nu==NULL) return 0;
+ if (nu->pntsu <= 1) return 0;
+ if ((nu->type & 7)!=CU_NURBS) return 1; /* not a nurb, lets assume its valid */
+
+ if (nu->pntsu < nu->orderu) return 0;
+ if (((nu->flag & CU_CYCLIC)==0) && ((nu->flagu>>1) & 2)) { /* Bezier U Endpoints */
+ if (nu->orderu==4) {
+ if (nu->pntsu < 5) return 0; /* bezier with 4 orderu needs 5 points */
+ } else if (nu->orderu != 3) return 0; /* order must be 3 or 4 */
+ }
+ return 1;
+}
+int check_valid_nurb_v( struct Nurb *nu)
+{
+ if (nu==NULL) return 0;
+ if (nu->pntsv <= 1) return 0;
+ if ((nu->type & 7)!=CU_NURBS) return 1; /* not a nurb, lets assume its valid */
+
+ if (nu->pntsv < nu->orderv) return 0;
+ if (((nu->flag & CU_CYCLIC)==0) && ((nu->flagv>>1) & 2)) { /* Bezier V Endpoints */
+ if (nu->orderv==4) {
+ if (nu->pntsv < 5) return 0; /* bezier with 4 orderu needs 5 points */
+ } else if (nu->orderv != 3) return 0; /* order must be 3 or 4 */
+ }
+ return 1;
+}
+
+int clamp_nurb_order_u( struct Nurb *nu )
+{
+ int change = 0;
+ if(nu->pntsu<nu->orderu) {
+ nu->orderu= nu->pntsu;
+ change= 1;
+ }
+ if(((nu->flag & CU_CYCLIC)==0) && (nu->flagu>>1)&2) {
+ CLAMP(nu->orderu, 3,4);
+ change= 1;
+ }
+ return change;
+}
+
+int clamp_nurb_order_v( struct Nurb *nu)
+{
+ int change = 0;
+ if(nu->pntsv<nu->orderv) {
+ nu->orderv= nu->pntsv;
+ change= 1;
+ }
+ if(((nu->flag & CU_CYCLIC)==0) && (nu->flagv>>1)&2) {
+ CLAMP(nu->orderv, 3,4);
+ change= 1;
+ }
+ return change;
+}
+
+
+
diff --git a/source/blender/blenkernel/intern/customdata.c b/source/blender/blenkernel/intern/customdata.c
index d8ce311b5ca..e93266c85f3 100644
--- a/source/blender/blenkernel/intern/customdata.c
+++ b/source/blender/blenkernel/intern/customdata.c
@@ -36,6 +36,7 @@
#include "BLI_blenlib.h"
#include "BLI_linklist.h"
+#include "BLI_mempool.h"
#include "DNA_customdata_types.h"
#include "DNA_listBase.h"
@@ -97,11 +98,16 @@ static void layerCopy_mdeformvert(const void *source, void *dest,
for(i = 0; i < count; ++i) {
MDeformVert *dvert = (MDeformVert *)((char *)dest + i * size);
- MDeformWeight *dw = MEM_callocN(dvert->totweight * sizeof(*dw),
- "layerCopy_mdeformvert dw");
- memcpy(dw, dvert->dw, dvert->totweight * sizeof(*dw));
- dvert->dw = dw;
+ if(dvert->totweight) {
+ MDeformWeight *dw = MEM_callocN(dvert->totweight * sizeof(*dw),
+ "layerCopy_mdeformvert dw");
+
+ memcpy(dw, dvert->dw, dvert->totweight * sizeof(*dw));
+ dvert->dw = dw;
+ }
+ else
+ dvert->dw = NULL;
}
}
@@ -259,14 +265,34 @@ static void layerSwap_tface(void *data, int *corner_indices)
{
MTFace *tf = data;
float uv[4][2];
+ static const short pin_flags[4] =
+ { TF_PIN1, TF_PIN2, TF_PIN3, TF_PIN4 };
+ static const char sel_flags[4] =
+ { TF_SEL1, TF_SEL2, TF_SEL3, TF_SEL4 };
+ short unwrap = tf->unwrap & ~(TF_PIN1 | TF_PIN2 | TF_PIN3 | TF_PIN4);
+ char flag = tf->flag & ~(TF_SEL1 | TF_SEL2 | TF_SEL3 | TF_SEL4);
int j;
for(j = 0; j < 4; ++j) {
- uv[j][0] = tf->uv[corner_indices[j]][0];
- uv[j][1] = tf->uv[corner_indices[j]][1];
+ int source_index = corner_indices[j];
+
+ uv[j][0] = tf->uv[source_index][0];
+ uv[j][1] = tf->uv[source_index][1];
+
+ // swap pinning flags around
+ if(tf->unwrap & pin_flags[source_index]) {
+ unwrap |= pin_flags[j];
+ }
+
+ // swap selection flags around
+ if(tf->flag & sel_flags[source_index]) {
+ flag |= sel_flags[j];
+ }
}
memcpy(tf->uv, uv, sizeof(tf->uv));
+ tf->unwrap = unwrap;
+ tf->flag = flag;
}
static void layerDefault_tface(void *data, int count)
@@ -354,8 +380,80 @@ static void layerDefault_origspace_face(void *data, int count)
}
/* --------- */
+static void layerDefault_mloopcol(void *data, int count)
+{
+ static MLoopCol default_mloopcol = {255,255,255,255};
+ MLoopCol *mlcol = (MLoopCol*)data;
+ int i;
+ for(i = 0; i < count; i++)
+ mlcol[i] = default_mloopcol;
+
+}
+
+static void layerInterp_mloopcol(void **sources, float *weights,
+ float *sub_weights, int count, void *dest)
+{
+ MLoopCol *mc = dest;
+ int i;
+ float *sub_weight;
+ struct {
+ float a;
+ float r;
+ float g;
+ float b;
+ } col;
+ col.a = col.r = col.g = col.b = 0;
+ sub_weight = sub_weights;
+ for(i = 0; i < count; ++i){
+ float weight = weights ? weights[i] : 1;
+ MLoopCol *src = sources[i];
+ if(sub_weights){
+ col.a += src->a * (*sub_weight) * weight;
+ col.r += src->r * (*sub_weight) * weight;
+ col.g += src->g * (*sub_weight) * weight;
+ col.b += src->b * (*sub_weight) * weight;
+ sub_weight++;
+ } else {
+ col.a += src->a * weight;
+ col.r += src->r * weight;
+ col.g += src->g * weight;
+ col.b += src->b * weight;
+ }
+ }
+ mc->a = (int)col.a;
+ mc->r = (int)col.r;
+ mc->g = (int)col.g;
+ mc->b = (int)col.b;
+}
+static void layerInterp_mloopuv(void **sources, float *weights,
+ float *sub_weights, int count, void *dest)
+{
+ MLoopUV *mluv = dest;
+ int i;
+ float *sub_weight;
+ struct {
+ float u;
+ float v;
+ }uv;
+ uv.u = uv.v = 0.0;
+ sub_weight = sub_weights;
+ for(i = 0; i < count; ++i){
+ float weight = weights ? weights[i] : 1;
+ MLoopUV *src = sources[i];
+ if(sub_weights){
+ uv.u += src->uv[0] * (*sub_weight) * weight;
+ uv.v += src->uv[1] * (*sub_weight) * weight;
+ sub_weight++;
+ } else {
+ uv.u += src->uv[0] * weight;
+ uv.v += src->uv[1] * weight;
+ }
+ }
+ mluv->uv[0] = uv.u;
+ mluv->uv[1] = uv.v;
+}
static void layerInterp_mcol(void **sources, float *weights,
float *sub_weights, int count, void *dest)
@@ -427,6 +525,8 @@ static void layerDefault_mcol(void *data, int count)
mcol[i] = default_mcol;
}
+
+
const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = {
{sizeof(MVert), "MVert", 1, NULL, NULL, NULL, NULL, NULL, NULL},
{sizeof(MSticky), "MSticky", 1, NULL, NULL, NULL, layerInterp_msticky, NULL,
@@ -449,13 +549,17 @@ const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = {
{sizeof(MStringProperty), "MStringProperty",1,"String",NULL,NULL,NULL,NULL},
{sizeof(OrigSpaceFace), "OrigSpaceFace", 1, "UVTex", layerCopy_origspace_face, NULL,
layerInterp_origspace_face, layerSwap_origspace_face, layerDefault_origspace_face},
- {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL}
+ {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
+ {sizeof(MTexPoly), "MTexPoly", 1, "Face Texture", NULL, NULL, NULL, NULL, NULL},
+ {sizeof(MLoopUV), "MLoopUV", 1, "UV coord", NULL, NULL, layerInterp_mloopuv, NULL, NULL},
+ {sizeof(MLoopCol), "MLoopCol", 1, "Col", NULL, NULL, layerInterp_mloopcol, NULL, layerDefault_mloopcol},
+ {sizeof(float)*3*4, "", 0, NULL, NULL, NULL, NULL, NULL, NULL}
};
const char *LAYERTYPENAMES[CD_NUMTYPES] = {
"CDMVert", "CDMSticky", "CDMDeformVert", "CDMEdge", "CDMFace", "CDMTFace",
"CDMCol", "CDOrigIndex", "CDNormal", "CDFlags","CDMFloatProperty",
- "CDMIntProperty","CDMStringProperty", "CDOrigSpace", "CDOrco"};
+ "CDMIntProperty","CDMStringProperty", "CDOrigSpace", "CDOrco", "CDMTexPoly", "CDMLoopUV", "CDMloopCol", "CDTangent"};
const CustomDataMask CD_MASK_BAREMESH =
CD_MASK_MVERT | CD_MASK_MEDGE | CD_MASK_MFACE;
@@ -469,7 +573,13 @@ const CustomDataMask CD_MASK_EDITMESH =
const CustomDataMask CD_MASK_DERIVEDMESH =
CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE |
CD_MASK_MCOL | CD_MASK_ORIGINDEX | CD_MASK_PROP_FLT | CD_MASK_PROP_INT |
- CD_MASK_PROP_STR | CD_MASK_ORIGSPACE | CD_MASK_ORCO;
+ CD_MASK_PROP_STR | CD_MASK_ORIGSPACE | CD_MASK_ORCO | CD_MASK_TANGENT;
+const CustomDataMask CD_MASK_BMESH =
+ CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR;
+const CustomDataMask CD_MASK_FACECORNERS =
+ CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_MTEXPOLY | CD_MASK_MLOOPUV |
+ CD_MASK_MLOOPCOL;
+
static const LayerTypeInfo *layerType_getInfo(int type)
{
@@ -816,12 +926,9 @@ void *CustomData_add_layer_named(CustomData *data, int type, int alloctype,
int CustomData_free_layer(CustomData *data, int type, int totelem, int index)
{
int i;
- CustomDataLayer *layer;
if (index < 0) return 0;
- layer = &data->layers[index];
-
customData_free_layer__internal(&data->layers[index], totelem);
for (i=index+1; i < data->totlayer; ++i)
@@ -1236,7 +1343,8 @@ void CustomData_em_copy_data(const CustomData *source, CustomData *dest,
if(dest_i >= dest->totlayer) return;
/* if we found a matching layer, copy the data */
- if(dest->layers[dest_i].type == source->layers[src_i].type) {
+ if(dest->layers[dest_i].type == source->layers[src_i].type &&
+ strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
char *src_data = (char*)src_block + source->layers[src_i].offset;
char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
@@ -1272,7 +1380,7 @@ void *CustomData_em_get_n(const CustomData *data, void *block, int type, int n)
int layer_index;
/* get the layer index of the first layer of type */
- layer_index = CustomData_get_active_layer_index(data, type);
+ layer_index = CustomData_get_layer_index(data, type);
if(layer_index < 0) return NULL;
return (char *)block + data->layers[layer_index+n].offset;
@@ -1443,6 +1551,302 @@ void CustomData_from_em_block(const CustomData *source, CustomData *dest,
}
+/*Bmesh functions*/
+/*needed to convert to/from different face reps*/
+void CustomData_to_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata)
+{
+ int i;
+ for(i=0; i < fdata->totlayer; i++){
+ if(fdata->layers[i].type == CD_MTFACE){
+ CustomData_add_layer(pdata, CD_MTEXPOLY, CD_CALLOC, &(fdata->layers[i].name), 0);
+ CustomData_add_layer(ldata, CD_MLOOPUV, CD_CALLOC, &(fdata->layers[i].name), 0);
+ }
+ else if(fdata->layers[i].type == CD_MCOL)
+ CustomData_add_layer(ldata, CD_MLOOPCOL, CD_CALLOC, &(fdata->layers[i].name), 0);
+ }
+}
+void CustomData_from_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata, int total){
+ int i;
+ for(i=0; i < pdata->totlayer; i++){
+ if(pdata->layers[i].type == CD_MTEXPOLY)
+ CustomData_add_layer(fdata, CD_MTFACE, CD_CALLOC, &(pdata->layers[i].name), total);
+ }
+ for(i=0; i < ldata->totlayer; i++){
+ if(ldata->layers[i].type == CD_MLOOPCOL)
+ CustomData_add_layer(fdata, CD_MCOL, CD_CALLOC, &(ldata->layers[i].name), total);
+ }
+}
+
+
+void CustomData_bmesh_init_pool(CustomData *data, int allocsize){
+ if(data->totlayer)data->pool = BLI_mempool_create(data->totsize, allocsize, allocsize);
+}
+
+void CustomData_bmesh_free_block(CustomData *data, void **block)
+{
+ const LayerTypeInfo *typeInfo;
+ int i;
+
+ if(!*block) return;
+ for(i = 0; i < data->totlayer; ++i) {
+ if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
+ typeInfo = layerType_getInfo(data->layers[i].type);
+
+ if(typeInfo->free) {
+ int offset = data->layers[i].offset;
+ typeInfo->free((char*)*block + offset, 1, typeInfo->size);
+ }
+ }
+ }
+
+ BLI_mempool_free(data->pool, *block);
+ *block = NULL;
+}
+
+static void CustomData_bmesh_alloc_block(CustomData *data, void **block)
+{
+
+ if (*block)
+ CustomData_bmesh_free_block(data, block);
+
+ if (data->totsize > 0)
+ *block = BLI_mempool_calloc(data->pool);
+ else
+ *block = NULL;
+}
+
+void CustomData_bmesh_copy_data(const CustomData *source, CustomData *dest,
+ void *src_block, void **dest_block)
+{
+ const LayerTypeInfo *typeInfo;
+ int dest_i, src_i;
+
+ if (!*dest_block)
+ CustomData_bmesh_alloc_block(dest, dest_block);
+
+ /* copies a layer at a time */
+ dest_i = 0;
+ for(src_i = 0; src_i < source->totlayer; ++src_i) {
+
+ /* find the first dest layer with type >= the source type
+ * (this should work because layers are ordered by type)
+ */
+ while(dest_i < dest->totlayer
+ && dest->layers[dest_i].type < source->layers[src_i].type)
+ ++dest_i;
+
+ /* if there are no more dest layers, we're done */
+ if(dest_i >= dest->totlayer) return;
+
+ /* if we found a matching layer, copy the data */
+ if(dest->layers[dest_i].type == source->layers[src_i].type &&
+ strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
+ char *src_data = (char*)src_block + source->layers[src_i].offset;
+ char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
+
+ typeInfo = layerType_getInfo(source->layers[src_i].type);
+
+ if(typeInfo->copy)
+ typeInfo->copy(src_data, dest_data, 1);
+ else
+ memcpy(dest_data, src_data, typeInfo->size);
+
+ /* if there are multiple source & dest layers of the same type,
+ * we don't want to copy all source layers to the same dest, so
+ * increment dest_i
+ */
+ ++dest_i;
+ }
+ }
+}
+
+/*Bmesh Custom Data Functions. Should replace editmesh ones with these as well, due to more effecient memory alloc*/
+void *CustomData_bmesh_get(const CustomData *data, void *block, int type)
+{
+ int layer_index;
+
+ /* get the layer index of the first layer of type */
+ layer_index = CustomData_get_active_layer_index(data, type);
+ if(layer_index < 0) return NULL;
+
+ return (char *)block + data->layers[layer_index].offset;
+}
+
+void *CustomData_bmesh_get_n(const CustomData *data, void *block, int type, int n)
+{
+ int layer_index;
+
+ /* get the layer index of the first layer of type */
+ layer_index = CustomData_get_layer_index(data, type);
+ if(layer_index < 0) return NULL;
+
+ return (char *)block + data->layers[layer_index+n].offset;
+}
+
+void CustomData_bmesh_set(const CustomData *data, void *block, int type, void *source)
+{
+ void *dest = CustomData_bmesh_get(data, block, type);
+ const LayerTypeInfo *typeInfo = layerType_getInfo(type);
+
+ if(!dest) return;
+
+ if(typeInfo->copy)
+ typeInfo->copy(source, dest, 1);
+ else
+ memcpy(dest, source, typeInfo->size);
+}
+
+void CustomData_bmesh_set_n(CustomData *data, void *block, int type, int n, void *source)
+{
+ void *dest = CustomData_bmesh_get_n(data, block, type, n);
+ const LayerTypeInfo *typeInfo = layerType_getInfo(type);
+
+ if(!dest) return;
+
+ if(typeInfo->copy)
+ typeInfo->copy(source, dest, 1);
+ else
+ memcpy(dest, source, typeInfo->size);
+}
+
+void CustomData_bmesh_interp(CustomData *data, void **src_blocks, float *weights,
+ float *sub_weights, int count, void *dest_block)
+{
+ int i, j;
+ void *source_buf[SOURCE_BUF_SIZE];
+ void **sources = source_buf;
+
+ /* slow fallback in case we're interpolating a ridiculous number of
+ * elements
+ */
+ if(count > SOURCE_BUF_SIZE)
+ sources = MEM_callocN(sizeof(*sources) * count,
+ "CustomData_interp sources");
+
+ /* interpolates a layer at a time */
+ for(i = 0; i < data->totlayer; ++i) {
+ CustomDataLayer *layer = &data->layers[i];
+ const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
+ if(typeInfo->interp) {
+ for(j = 0; j < count; ++j)
+ sources[j] = (char *)src_blocks[j] + layer->offset;
+
+ typeInfo->interp(sources, weights, sub_weights, count,
+ (char *)dest_block + layer->offset);
+ }
+ }
+
+ if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
+}
+
+void CustomData_bmesh_set_default(CustomData *data, void **block)
+{
+ const LayerTypeInfo *typeInfo;
+ int i;
+
+ if (!*block)
+ CustomData_bmesh_alloc_block(data, block);
+
+ for(i = 0; i < data->totlayer; ++i) {
+ int offset = data->layers[i].offset;
+
+ typeInfo = layerType_getInfo(data->layers[i].type);
+
+ if(typeInfo->set_default)
+ typeInfo->set_default((char*)*block + offset, 1);
+ }
+}
+
+void CustomData_to_bmesh_block(const CustomData *source, CustomData *dest,
+ int src_index, void **dest_block)
+{
+ const LayerTypeInfo *typeInfo;
+ int dest_i, src_i, src_offset;
+
+ if (!*dest_block)
+ CustomData_bmesh_alloc_block(dest, dest_block);
+
+ /* copies a layer at a time */
+ dest_i = 0;
+ for(src_i = 0; src_i < source->totlayer; ++src_i) {
+
+ /* find the first dest layer with type >= the source type
+ * (this should work because layers are ordered by type)
+ */
+ while(dest_i < dest->totlayer
+ && dest->layers[dest_i].type < source->layers[src_i].type)
+ ++dest_i;
+
+ /* if there are no more dest layers, we're done */
+ if(dest_i >= dest->totlayer) return;
+
+ /* if we found a matching layer, copy the data */
+ if(dest->layers[dest_i].type == source->layers[src_i].type) {
+ int offset = dest->layers[dest_i].offset;
+ char *src_data = source->layers[src_i].data;
+ char *dest_data = (char*)*dest_block + offset;
+
+ typeInfo = layerType_getInfo(dest->layers[dest_i].type);
+ src_offset = src_index * typeInfo->size;
+
+ if(typeInfo->copy)
+ typeInfo->copy(src_data + src_offset, dest_data, 1);
+ else
+ memcpy(dest_data, src_data + src_offset, typeInfo->size);
+
+ /* if there are multiple source & dest layers of the same type,
+ * we don't want to copy all source layers to the same dest, so
+ * increment dest_i
+ */
+ ++dest_i;
+ }
+ }
+}
+
+void CustomData_from_bmesh_block(const CustomData *source, CustomData *dest,
+ void *src_block, int dest_index)
+{
+ const LayerTypeInfo *typeInfo;
+ int dest_i, src_i, dest_offset;
+
+ /* copies a layer at a time */
+ dest_i = 0;
+ for(src_i = 0; src_i < source->totlayer; ++src_i) {
+
+ /* find the first dest layer with type >= the source type
+ * (this should work because layers are ordered by type)
+ */
+ while(dest_i < dest->totlayer
+ && dest->layers[dest_i].type < source->layers[src_i].type)
+ ++dest_i;
+
+ /* if there are no more dest layers, we're done */
+ if(dest_i >= dest->totlayer) return;
+
+ /* if we found a matching layer, copy the data */
+ if(dest->layers[dest_i].type == source->layers[src_i].type) {
+ int offset = source->layers[src_i].offset;
+ char *src_data = (char*)src_block + offset;
+ char *dest_data = dest->layers[dest_i].data;
+
+ typeInfo = layerType_getInfo(dest->layers[dest_i].type);
+ dest_offset = dest_index * typeInfo->size;
+
+ if(typeInfo->copy)
+ typeInfo->copy(src_data, dest_data + dest_offset, 1);
+ else
+ memcpy(dest_data + dest_offset, src_data, typeInfo->size);
+
+ /* if there are multiple source & dest layers of the same type,
+ * we don't want to copy all source layers to the same dest, so
+ * increment dest_i
+ */
+ ++dest_i;
+ }
+ }
+
+}
+
void CustomData_file_write_info(int type, char **structname, int *structnum)
{
const LayerTypeInfo *typeInfo = layerType_getInfo(type);
diff --git a/source/blender/blenkernel/intern/deform.c b/source/blender/blenkernel/intern/deform.c
index ab53571b62d..47736865273 100644
--- a/source/blender/blenkernel/intern/deform.c
+++ b/source/blender/blenkernel/intern/deform.c
@@ -220,3 +220,28 @@ void unique_vertexgroup_name (bDeformGroup *dg, Object *ob)
}
}
}
+
+float deformvert_get_weight(const struct MDeformVert *dvert, int group_num)
+{
+ if(dvert)
+ {
+ const MDeformWeight *dw = dvert->dw;
+ int i;
+
+ for(i=dvert->totweight; i>0; i--, dw++)
+ if(dw->def_nr == group_num)
+ return dw->weight;
+ }
+
+ /* Not found */
+ return 0.0;
+}
+
+float vertexgroup_get_vertex_weight(const struct MDeformVert *dvert, int index, int group_num)
+{
+ if(group_num == -1 || dvert == NULL)
+ return 1.0;
+
+ return deformvert_get_weight(dvert+index, group_num);
+}
+
diff --git a/source/blender/blenkernel/intern/depsgraph.c b/source/blender/blenkernel/intern/depsgraph.c
index 0ce318eb57f..f5deda9c3c9 100644
--- a/source/blender/blenkernel/intern/depsgraph.c
+++ b/source/blender/blenkernel/intern/depsgraph.c
@@ -46,6 +46,7 @@
#include "DNA_effect_types.h"
#include "DNA_group_types.h"
#include "DNA_lattice_types.h"
+#include "DNA_lamp_types.h"
#include "DNA_key_types.h"
#include "DNA_mesh_types.h"
#include "DNA_modifier_types.h"
@@ -71,12 +72,15 @@
#include "BKE_modifier.h"
#include "BKE_object.h"
#include "BKE_particle.h"
+#include "BKE_pointcache.h"
#include "BKE_utildefines.h"
#include "BKE_scene.h"
#include "MEM_guardedalloc.h"
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h"
+#endif
#include "depsgraph_private.h"
@@ -310,6 +314,7 @@ static void dag_add_driver_relation(Ipo *ipo, DagForest *dag, DagNode *node, int
if ((icu->driver->flag & IPO_DRIVER_FLAG_INVALID) || (icu->driver->name[0] == '\0'))
continue; /* empty or invalid expression */
+#ifndef DISABLE_PYTHON
else {
/* now we need refs to all objects mentioned in this
* pydriver expression, to call 'dag_add_relation'
@@ -322,22 +327,41 @@ static void dag_add_driver_relation(Ipo *ipo, DagForest *dag, DagNode *node, int
ob = *oba;
node1 = dag_get_node(dag, ob);
if (ob->type == OB_ARMATURE)
- dag_add_relation(dag, node1, node, isdata?DAG_RL_DATA_DATA:DAG_RL_DATA_OB);
+ dag_add_relation(dag, node1, node, isdata?DAG_RL_DATA_DATA:DAG_RL_DATA_OB, "Python Ipo Driver");
else
- dag_add_relation(dag, node1, node, isdata?DAG_RL_OB_DATA:DAG_RL_OB_OB);
+ dag_add_relation(dag, node1, node, isdata?DAG_RL_OB_DATA:DAG_RL_OB_OB, "Python Ipo Driver");
oba++;
}
MEM_freeN(obarray);
}
}
+#endif /* DISABLE_PYTHON */
}
else if (icu->driver->ob) {
node1 = dag_get_node(dag, icu->driver->ob);
if(icu->driver->blocktype==ID_AR)
- dag_add_relation(dag, node1, node, isdata?DAG_RL_DATA_DATA:DAG_RL_DATA_OB);
+ dag_add_relation(dag, node1, node, isdata?DAG_RL_DATA_DATA:DAG_RL_DATA_OB, "Ipo Driver");
else
- dag_add_relation(dag, node1, node, isdata?DAG_RL_OB_DATA:DAG_RL_OB_OB);
+ dag_add_relation(dag, node1, node, isdata?DAG_RL_OB_DATA:DAG_RL_OB_OB, "Ipo Driver");
+ }
+ }
+ }
+}
+
+static void dag_add_collision_field_relation(DagForest *dag, Object *ob, DagNode *node)
+{
+ Base *base;
+ DagNode *node2;
+
+ // would be nice to have a list of colliders here
+ // so for now walk all objects in scene check 'same layer rule'
+ for(base = G.scene->base.first; base; base= base->next) {
+ if((base->lay & ob->lay) && base->object->pd) {
+ Object *ob1= base->object;
+ if((ob1->pd->deflect || ob1->pd->forcefield) && (ob1 != ob)) {
+ node2 = dag_get_node(dag, ob1);
+ dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Field Collision");
}
}
}
@@ -358,7 +382,7 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Object *ob, int
if ((ob->data) && (mask&DAG_RL_DATA)) {
node2 = dag_get_node(dag,ob->data);
- dag_add_relation(dag,node,node2,DAG_RL_DATA);
+ dag_add_relation(dag,node,node2,DAG_RL_DATA, "Object-Data Relation");
node2->first_ancestor = ob;
node2->ancestor_count += 1;
}
@@ -383,11 +407,11 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Object *ob, int
node3 = dag_get_node(dag, ct->tar);
if (ct->subtarget[0])
- dag_add_relation(dag,node3,node, DAG_RL_OB_DATA|DAG_RL_DATA_DATA);
+ dag_add_relation(dag,node3,node, DAG_RL_OB_DATA|DAG_RL_DATA_DATA, cti->name);
else if(ELEM(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO))
- dag_add_relation(dag,node3,node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
+ dag_add_relation(dag,node3,node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA, cti->name);
else
- dag_add_relation(dag,node3,node, DAG_RL_OB_DATA);
+ dag_add_relation(dag,node3,node, DAG_RL_OB_DATA, cti->name);
}
}
@@ -435,7 +459,7 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Object *ob, int
for(amod= strip->modifiers.first; amod; amod= amod->next) {
if(amod->ob) {
node2 = dag_get_node(dag, amod->ob);
- dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
+ dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "NLA Strip Modifier");
}
}
}
@@ -455,46 +479,55 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Object *ob, int
switch(ob->partype) {
case PARSKEL:
- dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_OB);
+ dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_OB, "Parent");
break;
case PARVERT1: case PARVERT3: case PARBONE:
- dag_add_relation(dag,node2,node,DAG_RL_DATA_OB|DAG_RL_OB_OB);
+ dag_add_relation(dag,node2,node,DAG_RL_DATA_OB|DAG_RL_OB_OB, "Vertex Parent");
break;
default:
if(ob->parent->type==OB_LATTICE)
- dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_OB);
+ dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_OB, "Lattice Parent");
else if(ob->parent->type==OB_CURVE) {
Curve *cu= ob->parent->data;
if(cu->flag & CU_PATH)
- dag_add_relation(dag,node2,node,DAG_RL_DATA_OB|DAG_RL_OB_OB);
+ dag_add_relation(dag,node2,node,DAG_RL_DATA_OB|DAG_RL_OB_OB, "Curve Parent");
else
- dag_add_relation(dag,node2,node,DAG_RL_OB_OB);
+ dag_add_relation(dag,node2,node,DAG_RL_OB_OB, "Curve Parent");
}
- else
- dag_add_relation(dag,node2,node,DAG_RL_OB_OB);
+ else
+ dag_add_relation(dag,node2,node,DAG_RL_OB_OB, "Parent");
}
/* exception case: parent is duplivert */
if(ob->type==OB_MBALL && (ob->parent->transflag & OB_DUPLIVERTS)) {
- dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_OB);
+ dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_OB, "Duplivert");
}
addtoroot = 0;
}
if (ob->track) {
node2 = dag_get_node(dag,ob->track);
- dag_add_relation(dag,node2,node,DAG_RL_OB_OB);
+ dag_add_relation(dag,node2,node,DAG_RL_OB_OB, "Track To");
addtoroot = 0;
}
if (ob->proxy) {
node2 = dag_get_node(dag, ob->proxy);
- dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA|DAG_RL_OB_OB);
+ dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA|DAG_RL_OB_OB, "Proxy");
/* inverted relation, so addtoroot shouldn't be set to zero */
}
if (ob->type==OB_CAMERA) {
Camera *cam = (Camera *)ob->data;
+ if (cam->ipo) {
+ dag_add_driver_relation(cam->ipo, dag, node, 1);
+ }
if (cam->dof_ob) {
node2 = dag_get_node(dag, cam->dof_ob);
- dag_add_relation(dag,node2,node,DAG_RL_OB_OB);
+ dag_add_relation(dag,node2,node,DAG_RL_OB_OB, "Camera DoF");
+ }
+ }
+ if (ob->type==OB_LAMP) {
+ Lamp *la = (Lamp *)ob->data;
+ if (la->ipo) {
+ dag_add_driver_relation(la->ipo, dag, node, 1);
}
}
if (ob->transflag & OB_DUPLI) {
@@ -504,46 +537,33 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Object *ob, int
if(go->ob) {
node2 = dag_get_node(dag, go->ob);
/* node2 changes node1, this keeps animations updated in groups?? not logical? */
- dag_add_relation(dag, node2, node, DAG_RL_OB_OB);
+ dag_add_relation(dag, node2, node, DAG_RL_OB_OB, "Dupligroup");
}
}
}
}
/* softbody collision */
- if((ob->type==OB_MESH) || (ob->type==OB_CURVE) || (ob->type==OB_LATTICE)) {
- Base *base;
- if(modifiers_isSoftbodyEnabled(ob)){
- // would be nice to have a list of colliders here
- // so for now walk all objects in scene check 'same layer rule'
- for(base = G.scene->base.first; base; base= base->next) {
- if( (base->lay & ob->lay) && base->object->pd) {
- Object *ob1= base->object;
- if((ob1->pd->deflect) && (ob1 != ob)) {
- node2 = dag_get_node(dag, ob1);
- dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
- }
- }
- }
- }
- }
+ if((ob->type==OB_MESH) || (ob->type==OB_CURVE) || (ob->type==OB_LATTICE))
+ if(modifiers_isSoftbodyEnabled(ob) || modifiers_isClothEnabled(ob))
+ dag_add_collision_field_relation(dag, ob, node);
if (ob->type==OB_MBALL) {
Object *mom= find_basis_mball(ob);
if(mom!=ob) {
node2 = dag_get_node(dag, mom);
- dag_add_relation(dag,node,node2,DAG_RL_DATA_DATA|DAG_RL_OB_DATA); // mom depends on children!
+ dag_add_relation(dag,node,node2,DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Metaball"); // mom depends on children!
}
}
else if (ob->type==OB_CURVE) {
Curve *cu= ob->data;
if(cu->bevobj) {
node2 = dag_get_node(dag, cu->bevobj);
- dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
+ dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Curve Bevel");
}
if(cu->taperobj) {
node2 = dag_get_node(dag, cu->taperobj);
- dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
+ dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Curve Taper");
}
if(cu->ipo)
dag_add_driver_relation(cu->ipo, dag, node, 1);
@@ -553,52 +573,41 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Object *ob, int
Curve *cu= ob->data;
if(cu->textoncurve) {
node2 = dag_get_node(dag, cu->textoncurve);
- dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
- }
- }
- else if(ob->type==OB_MESH) {
- PartEff *paf= give_parteff(ob);
- if(paf) {
- ListBase *listb;
- pEffectorCache *ec;
-
- /* ob location depends on itself */
- if((paf->flag & PAF_STATIC)==0)
- dag_add_relation(dag, node, node, DAG_RL_OB_DATA);
-
- listb= pdInitEffectors(ob, paf->group); /* note, makes copy... */
- if(listb) {
- for(ec= listb->first; ec; ec= ec->next) {
- Object *ob1= ec->ob;
- PartDeflect *pd= ob1->pd;
-
- if(pd->forcefield) {
- node2 = dag_get_node(dag, ob1);
- if(pd->forcefield==PFIELD_GUIDE)
- dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
- else
- dag_add_relation(dag, node2, node, DAG_RL_OB_DATA);
- }
- }
-
- pdEndEffectors(listb); /* restores copy... */
- }
+ dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Texture On Curve");
}
}
-
+
psys= ob->particlesystem.first;
if(psys) {
ParticleEffectorCache *nec;
+ GroupObject *go;
for(; psys; psys=psys->next) {
ParticleSettings *part= psys->part;
-
- dag_add_relation(dag, node, node, DAG_RL_OB_DATA);
+
+ dag_add_relation(dag, node, node, DAG_RL_OB_DATA, "Particle-Object Relation");
+
+ if(psys->flag & PSYS_DISABLED || psys->flag & PSYS_DELETE)
+ continue;
if(part->phystype==PART_PHYS_KEYED && psys->keyed_ob &&
BLI_findlink(&psys->keyed_ob->particlesystem,psys->keyed_psys-1)) {
node2 = dag_get_node(dag, psys->keyed_ob);
- dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA);
+ dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA, "Particle Keyed Physics");
+ }
+
+ if(part->draw_as == PART_DRAW_OB && part->dup_ob) {
+ node2 = dag_get_node(dag, part->dup_ob);
+ dag_add_relation(dag, node, node2, DAG_RL_OB_OB, "Particle Object Visualisation");
+ if(part->dup_ob->type == OB_MBALL)
+ dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA, "Particle Object Visualisation");
+ }
+
+ if(part->draw_as == PART_DRAW_GR && part->dup_group) {
+ for(go=part->dup_group->gobject.first; go; go=go->next) {
+ node2 = dag_get_node(dag, go->ob);
+ dag_add_relation(dag, node, node2, DAG_RL_OB_OB, "Particle Group Visualisation");
+ }
}
if(psys->effectors.first)
@@ -612,22 +621,22 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Object *ob, int
if(nec->type & PSYS_EC_EFFECTOR) {
node2 = dag_get_node(dag, ob1);
if(ob1->pd->forcefield==PFIELD_GUIDE)
- dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
+ dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Particle Field");
else
- dag_add_relation(dag, node2, node, DAG_RL_OB_DATA);
+ dag_add_relation(dag, node2, node, DAG_RL_OB_DATA, "Particle Field");
}
else if(nec->type & PSYS_EC_DEFLECT) {
node2 = dag_get_node(dag, ob1);
- dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA);
+ dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Particle Collision");
}
else if(nec->type & PSYS_EC_PARTICLE) {
node2 = dag_get_node(dag, ob1);
- dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA);
+ dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA, "Particle Field");
}
if(nec->type & PSYS_EC_REACTOR) {
node2 = dag_get_node(dag, ob1);
- dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA);
+ dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA, "Particle Reactor");
}
}
}
@@ -652,12 +661,12 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Object *ob, int
node2 = dag_get_node(dag, obt);
if (ELEM(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO))
- dag_add_relation(dag, node2, node, DAG_RL_DATA_OB|DAG_RL_OB_OB);
+ dag_add_relation(dag, node2, node, DAG_RL_DATA_OB|DAG_RL_OB_OB, cti->name);
else {
if (ELEM3(obt->type, OB_ARMATURE, OB_MESH, OB_LATTICE) && (ct->subtarget[0]))
- dag_add_relation(dag, node2, node, DAG_RL_DATA_OB|DAG_RL_OB_OB);
+ dag_add_relation(dag, node2, node, DAG_RL_DATA_OB|DAG_RL_OB_OB, cti->name);
else
- dag_add_relation(dag, node2, node, DAG_RL_OB_OB);
+ dag_add_relation(dag, node2, node, DAG_RL_OB_OB, cti->name);
}
addtoroot = 0;
}
@@ -668,7 +677,7 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Object *ob, int
}
if (addtoroot == 1 )
- dag_add_relation(dag,scenenode,node,DAG_RL_SCENE);
+ dag_add_relation(dag,scenenode,node,DAG_RL_SCENE, "Scene Relation");
}
struct DagForest *build_dag(struct Scene *sce, short mask)
@@ -859,12 +868,12 @@ DagNode * dag_get_sub_node (DagForest *forest,void * fob)
return node;
}
-void dag_add_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel)
+static void dag_add_parent_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel, char *name)
{
- DagAdjList *itA = fob1->child;
+ DagAdjList *itA = fob2->parent;
while (itA) { /* search if relation exist already */
- if (itA->node == fob2) {
+ if (itA->node == fob1) {
itA->type |= rel;
itA->count += 1;
return;
@@ -873,19 +882,23 @@ void dag_add_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel
}
/* create new relation and insert at head. MALLOC alert! */
itA = MEM_mallocN(sizeof(DagAdjList),"DAG adj list");
- itA->node = fob2;
+ itA->node = fob1;
itA->type = rel;
itA->count = 1;
- itA->next = fob1->child;
- fob1->child = itA;
+ itA->next = fob2->parent;
+ itA->name = name;
+ fob2->parent = itA;
}
-static void dag_add_parent_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel)
+void dag_add_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel, char *name)
{
- DagAdjList *itA = fob2->parent;
+ DagAdjList *itA = fob1->child;
+ /* parent relation is for cycle checking */
+ dag_add_parent_relation(forest, fob1, fob2, rel, name);
+
while (itA) { /* search if relation exist already */
- if (itA->node == fob1) {
+ if (itA->node == fob2) {
itA->type |= rel;
itA->count += 1;
return;
@@ -894,13 +907,127 @@ static void dag_add_parent_relation(DagForest *forest, DagNode *fob1, DagNode *f
}
/* create new relation and insert at head. MALLOC alert! */
itA = MEM_mallocN(sizeof(DagAdjList),"DAG adj list");
- itA->node = fob1;
+ itA->node = fob2;
itA->type = rel;
itA->count = 1;
- itA->next = fob2->parent;
- fob2->parent = itA;
+ itA->next = fob1->child;
+ itA->name = name;
+ fob1->child = itA;
}
+static char *dag_node_name(DagNode *node)
+{
+ if(node->ob == NULL)
+ return "null";
+ else if(ugly_hack_sorry)
+ return ((ID*)(node->ob))->name+2;
+ else
+ return ((bPoseChannel*)(node->ob))->name;
+}
+
+#if 0
+static void dag_node_print_dependencies(DagNode *node)
+{
+ DagAdjList *itA;
+
+ printf("%s depends on:\n", dag_node_name(node));
+
+ for(itA= node->parent; itA; itA= itA->next)
+ printf(" %s through %s\n", dag_node_name(itA->node), itA->name);
+ printf("\n");
+}
+#endif
+
+static int dag_node_print_dependency_recurs(DagNode *node, DagNode *endnode)
+{
+ DagAdjList *itA;
+
+ if(node->color == DAG_BLACK)
+ return 0;
+
+ node->color= DAG_BLACK;
+
+ if(node == endnode)
+ return 1;
+
+ for(itA= node->parent; itA; itA= itA->next) {
+ if(dag_node_print_dependency_recurs(itA->node, endnode)) {
+ printf(" %s depends on %s through %s.\n", dag_node_name(node), dag_node_name(itA->node), itA->name);
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+static void dag_node_print_dependency_cycle(DagForest *dag, DagNode *startnode, DagNode *endnode, char *name)
+{
+ DagNode *node;
+
+ for(node = dag->DagNode.first; node; node= node->next)
+ node->color= DAG_WHITE;
+
+ printf(" %s depends on %s through %s.\n", dag_node_name(endnode), dag_node_name(startnode), name);
+ dag_node_print_dependency_recurs(startnode, endnode);
+ printf("\n");
+}
+
+static int dag_node_recurs_level(DagNode *node, int level)
+{
+ DagAdjList *itA;
+ int newlevel;
+
+ node->color= DAG_BLACK; /* done */
+ newlevel= ++level;
+
+ for(itA= node->parent; itA; itA= itA->next) {
+ if(itA->node->color==DAG_WHITE) {
+ itA->node->ancestor_count= dag_node_recurs_level(itA->node, level);
+ newlevel= MAX2(newlevel, level+itA->node->ancestor_count);
+ }
+ else
+ newlevel= MAX2(newlevel, level+itA->node->ancestor_count);
+ }
+
+ return newlevel;
+}
+
+static void dag_check_cycle(DagForest *dag)
+{
+ DagNode *node;
+ DagAdjList *itA;
+
+ /* tag nodes unchecked */
+ for(node = dag->DagNode.first; node; node= node->next)
+ node->color= DAG_WHITE;
+
+ for(node = dag->DagNode.first; node; node= node->next) {
+ if(node->color==DAG_WHITE) {
+ node->ancestor_count= dag_node_recurs_level(node, 0);
+ }
+ }
+
+ /* check relations, and print errors */
+ for(node = dag->DagNode.first; node; node= node->next) {
+ for(itA= node->parent; itA; itA= itA->next) {
+ if(itA->node->ancestor_count > node->ancestor_count) {
+ if(node->ob && itA->node->ob) {
+ printf("Dependency cycle detected:\n");
+ dag_node_print_dependency_cycle(dag, itA->node, node, itA->name);
+ }
+ }
+ }
+ }
+
+ /* parent relations are only needed for cycle checking, so free now */
+ for(node = dag->DagNode.first; node; node= node->next) {
+ while (node->parent) {
+ itA = node->parent->next;
+ MEM_freeN(node->parent);
+ node->parent = itA;
+ }
+ }
+}
/*
* MainDAG is the DAG of all objects in current scene
@@ -1539,6 +1666,8 @@ void DAG_scene_sort(struct Scene *sce)
build_dag(sce, DAG_RL_ALL_BUT_DATA);
+ dag_check_cycle(sce->theDag);
+
nqueue = queue_create(DAGQUEUEALLOC);
for(node = sce->theDag->DagNode.first; node; node= node->next) {
@@ -1630,11 +1759,12 @@ static void flush_update_node(DagNode *node, unsigned int layer, int curtime)
ob= node->ob;
if(ob && (ob->recalc & OB_RECALC)) {
all_layer= ob->lay;
+
/* got an object node that changes, now check relations */
for(itA = node->child; itA; itA= itA->next) {
all_layer |= itA->lay;
/* the relationship is visible */
- if(itA->lay & layer) {
+ if((itA->lay & layer) || (itA->node->ob == G.obedit)) {
if(itA->node->type==ID_OB) {
obc= itA->node->ob;
oldflag= obc->recalc;
@@ -1665,7 +1795,7 @@ static void flush_update_node(DagNode *node, unsigned int layer, int curtime)
}
}
/* even nicer, we can clear recalc flags... */
- if((all_layer & layer)==0) {
+ if((all_layer & layer)==0 && (ob != G.obedit)) {
/* but existing displaylists or derivedmesh should be freed */
if(ob->recalc & OB_RECALC_DATA)
object_free_display(ob);
@@ -1679,7 +1809,7 @@ static void flush_update_node(DagNode *node, unsigned int layer, int curtime)
/* could merge this in with loop above...? (ton) */
for(itA = node->child; itA; itA= itA->next) {
/* the relationship is visible */
- if(itA->lay & layer) {
+ if((itA->lay & layer) || (itA->node->ob == G.obedit)) {
if(itA->node->type==ID_OB) {
obc= itA->node->ob;
/* child moves */
@@ -1703,18 +1833,24 @@ static void flush_update_node(DagNode *node, unsigned int layer, int curtime)
}
/* node was checked to have lasttime != curtime , and is of type ID_OB */
-static unsigned int flush_layer_node(DagNode *node, int curtime)
+static unsigned int flush_layer_node(Scene *sce, DagNode *node, int curtime)
{
+ Base *base;
DagAdjList *itA;
node->lasttime= curtime;
- node->lay= ((Object *)node->ob)->lay;
+ node->lay= 0;
+ for(base= sce->base.first; base; base= base->next) {
+ if(node->ob == base->object) {
+ node->lay= ((Object *)node->ob)->lay;
+ break;
+ }
+ }
for(itA = node->child; itA; itA= itA->next) {
if(itA->node->type==ID_OB) {
if(itA->node->lasttime!=curtime) {
- itA->lay= flush_layer_node(itA->node, curtime); // lay is only set once for each relation
- //printf("layer %d for relation %s to %s\n", itA->lay, ((Object *)node->ob)->id.name, ((Object *)itA->node->ob)->id.name);
+ itA->lay= flush_layer_node(sce, itA->node, curtime); // lay is only set once for each relation
}
else itA->lay= itA->node->lay;
@@ -1725,11 +1861,38 @@ static unsigned int flush_layer_node(DagNode *node, int curtime)
return node->lay;
}
+/* node was checked to have lasttime != curtime , and is of type ID_OB */
+static void flush_pointcache_reset(DagNode *node, int curtime, int reset)
+{
+ DagAdjList *itA;
+ Object *ob;
+
+ node->lasttime= curtime;
+
+ for(itA = node->child; itA; itA= itA->next) {
+ if(itA->node->type==ID_OB) {
+ if(itA->node->lasttime!=curtime) {
+ ob= (Object*)(node->ob);
+
+ if(reset || (ob->recalc & OB_RECALC)) {
+ if(BKE_ptcache_object_reset(ob, PTCACHE_RESET_DEPSGRAPH))
+ ob->recalc |= OB_RECALC_DATA;
+
+ flush_pointcache_reset(itA->node, curtime, 1);
+ }
+ else
+ flush_pointcache_reset(itA->node, curtime, 0);
+ }
+ }
+ }
+}
+
/* flushes all recalc flags in objects down the dependency tree */
-void DAG_scene_flush_update(Scene *sce, unsigned int lay)
+void DAG_scene_flush_update(Scene *sce, unsigned int lay, int time)
{
DagNode *firstnode;
DagAdjList *itA;
+ Object *ob;
int lasttime;
if(sce->theDag==NULL) {
@@ -1738,21 +1901,43 @@ void DAG_scene_flush_update(Scene *sce, unsigned int lay)
}
firstnode= sce->theDag->DagNode.first; // always scene node
+
+ for(itA = firstnode->child; itA; itA= itA->next)
+ itA->lay= 0;
/* first we flush the layer flags */
sce->theDag->time++; // so we know which nodes were accessed
lasttime= sce->theDag->time;
- for(itA = firstnode->child; itA; itA= itA->next) {
+
+ for(itA = firstnode->child; itA; itA= itA->next)
if(itA->node->lasttime!=lasttime && itA->node->type==ID_OB)
- flush_layer_node(itA->node, lasttime);
- }
+ flush_layer_node(sce, itA->node, lasttime);
/* then we use the relationships + layer info to flush update events */
sce->theDag->time++; // so we know which nodes were accessed
lasttime= sce->theDag->time;
- for(itA = firstnode->child; itA; itA= itA->next) {
- if(itA->node->lasttime!=lasttime && itA->node->type==ID_OB)
+ for(itA = firstnode->child; itA; itA= itA->next)
+ if(itA->node->lasttime!=lasttime && itA->node->type==ID_OB)
flush_update_node(itA->node, lay, lasttime);
+
+ /* if update is not due to time change, do pointcache clears */
+ if(!time) {
+ sce->theDag->time++; // so we know which nodes were accessed
+ lasttime= sce->theDag->time;
+ for(itA = firstnode->child; itA; itA= itA->next) {
+ if(itA->node->lasttime!=lasttime && itA->node->type==ID_OB) {
+ ob= (Object*)(itA->node->ob);
+
+ if(ob->recalc & OB_RECALC) {
+ if(BKE_ptcache_object_reset(ob, PTCACHE_RESET_DEPSGRAPH))
+ ob->recalc |= OB_RECALC_DATA;
+
+ flush_pointcache_reset(itA->node, lasttime, 1);
+ }
+ else
+ flush_pointcache_reset(itA->node, lasttime, 0);
+ }
+ }
}
}
@@ -1807,8 +1992,10 @@ static void dag_object_time_update_flags(Object *ob)
}
}
}
- else if(ob->scriptlink.totscript) ob->recalc |= OB_RECALC_OB;
- else if(ob->parent) {
+
+ if(ob->scriptlink.totscript) ob->recalc |= OB_RECALC_OB;
+
+ if(ob->parent) {
/* motion path or bone child */
if(ob->parent->type==OB_CURVE || ob->parent->type==OB_ARMATURE) ob->recalc |= OB_RECALC_OB;
}
@@ -1829,9 +2016,11 @@ static void dag_object_time_update_flags(Object *ob)
}
}
}
- else if(modifiers_isSoftbodyEnabled(ob)) ob->recalc |= OB_RECALC_DATA;
- else if(object_modifiers_use_time(ob)) ob->recalc |= OB_RECALC_DATA;
- else {
+
+ if(object_modifiers_use_time(ob)) ob->recalc |= OB_RECALC_DATA;
+ if((ob->pose) && (ob->pose->flag & POSE_CONSTRAINTS_TIMEDEPEND)) ob->recalc |= OB_RECALC_DATA;
+
+ {
Mesh *me;
Curve *cu;
Lattice *lt;
@@ -1845,21 +2034,6 @@ static void dag_object_time_update_flags(Object *ob)
ob->shapeflag &= ~OB_SHAPE_TEMPLOCK;
}
}
- else if(ob->effect.first) {
- Effect *eff= ob->effect.first;
- PartEff *paf= give_parteff(ob);
-
- if(eff->type==EFF_WAVE)
- ob->recalc |= OB_RECALC_DATA;
- else if(paf && paf->keys==NULL)
- ob->recalc |= OB_RECALC_DATA;
- }
- if((ob->fluidsimFlag & OB_FLUIDSIM_ENABLE) && (ob->fluidsimSettings)) {
- // fluidsimSettings might not be initialized during load...
- if(ob->fluidsimSettings->type & (OB_FLUIDSIM_DOMAIN|OB_FLUIDSIM_PARTICLE)) {
- ob->recalc |= OB_RECALC_DATA; // NT FSPARTICLE
- }
- }
if(ob->particlesystem.first)
ob->recalc |= OB_RECALC_DATA;
break;
@@ -1937,7 +2111,7 @@ void DAG_scene_update_flags(Scene *scene, unsigned int lay)
}
for(sce= scene; sce; sce= sce->set)
- DAG_scene_flush_update(sce, lay);
+ DAG_scene_flush_update(sce, lay, 1);
/* test: set time flag, to disable baked systems to update */
for(SETLOOPER(scene, base)) {
@@ -1987,7 +2161,9 @@ void DAG_object_flush_update(Scene *sce, Object *ob, short flag)
{
if(ob==NULL || sce->theDag==NULL) return;
+
ob->recalc |= flag;
+ BKE_ptcache_object_reset(ob, PTCACHE_RESET_DEPSGRAPH);
/* all users of this ob->data should be checked */
/* BUT! displists for curves are still only on cu */
@@ -2000,8 +2176,9 @@ void DAG_object_flush_update(Scene *sce, Object *ob, short flag)
else {
Object *obt;
for (obt=G.main->object.first; obt; obt= obt->id.next) {
- if (obt->data==ob->data) {
+ if (obt != ob && obt->data==ob->data) {
obt->recalc |= OB_RECALC_DATA;
+ BKE_ptcache_object_reset(obt, PTCACHE_RESET_DEPSGRAPH);
}
}
}
@@ -2010,9 +2187,9 @@ void DAG_object_flush_update(Scene *sce, Object *ob, short flag)
}
if(G.curscreen)
- DAG_scene_flush_update(sce, dag_screen_view3d_layers());
+ DAG_scene_flush_update(sce, dag_screen_view3d_layers(), 0);
else
- DAG_scene_flush_update(sce, sce->lay);
+ DAG_scene_flush_update(sce, sce->lay, 0);
}
/* recursively descends tree, each node only checked once */
@@ -2060,8 +2237,8 @@ void DAG_object_update_flags(Scene *sce, Object *ob, unsigned int lay)
/* object not in scene? then handle group exception. needs to be dagged once too */
if(node==NULL) {
- Group *group= find_group(ob);
- if(group) {
+ Group *group= NULL;
+ while( (group = find_group(ob, group)) ) {
GroupObject *go;
/* primitive; tag all... this call helps building groups for particles */
for(go= group->gobject.first; go; go= go->next)
@@ -2094,51 +2271,6 @@ void DAG_object_update_flags(Scene *sce, Object *ob, unsigned int lay)
/* ******************* DAG FOR ARMATURE POSE ***************** */
-static int node_recurs_level(DagNode *node, int level)
-{
- DagAdjList *itA;
-
- node->color= DAG_BLACK; /* done */
- level++;
-
- for(itA= node->parent; itA; itA= itA->next) {
- if(itA->node->color==DAG_WHITE)
- itA->node->ancestor_count= node_recurs_level(itA->node, level);
- }
-
- return level;
-}
-
-static void pose_check_cycle(DagForest *dag)
-{
- DagNode *node;
- DagAdjList *itA;
-
- /* tag nodes unchecked */
- for(node = dag->DagNode.first; node; node= node->next)
- node->color= DAG_WHITE;
-
- for(node = dag->DagNode.first; node; node= node->next) {
- if(node->color==DAG_WHITE) {
- node->ancestor_count= node_recurs_level(node, 0);
- }
- }
-
- /* check relations, and print errors */
- for(node = dag->DagNode.first; node; node= node->next) {
- for(itA= node->parent; itA; itA= itA->next) {
- if(itA->node->ancestor_count > node->ancestor_count) {
- bPoseChannel *pchan= (bPoseChannel *)node->ob;
- bPoseChannel *parchan= (bPoseChannel *)itA->node->ob;
-
- if(pchan && parchan)
- if(pchan->parent!=parchan)
- printf("Cycle in %s to %s\n", pchan->name, parchan->name);
- }
- }
- }
-}
-
/* we assume its an armature with pose */
void DAG_pose_sort(Object *ob)
{
@@ -2167,8 +2299,7 @@ void DAG_pose_sort(Object *ob)
if(pchan->parent) {
node2 = dag_get_node(dag, pchan->parent);
- dag_add_relation(dag, node2, node, 0);
- dag_add_parent_relation(dag, node2, node, 0);
+ dag_add_relation(dag, node2, node, 0, "Parent Relation");
addtoroot = 0;
}
for (con = pchan->constraints.first; con; con=con->next) {
@@ -2179,12 +2310,14 @@ void DAG_pose_sort(Object *ob)
if(con->ipo) {
IpoCurve *icu;
for(icu= con->ipo->curve.first; icu; icu= icu->next) {
- if(icu->driver && icu->driver->ob==ob) {
+ /* icu->driver->ob should actually point to ob->proxy if it
+ * is a proxy, but since it wasn't set correct it older
+ * files comparing with ob->proxy makes it work for those */
+ if(icu->driver && (icu->driver->ob==ob || icu->driver->ob==ob->proxy)) {
bPoseChannel *target= get_pose_channel(ob->pose, icu->driver->name);
if(target) {
node2 = dag_get_node(dag, target);
- dag_add_relation(dag, node2, node, 0);
- dag_add_parent_relation(dag, node2, node, 0);
+ dag_add_relation(dag, node2, node, 0, "Ipo Driver");
/* uncommented this line, results in dependencies
* not being added properly for this constraint,
@@ -2203,9 +2336,8 @@ void DAG_pose_sort(Object *ob)
bPoseChannel *target= get_pose_channel(ob->pose, ct->subtarget);
if (target) {
node2= dag_get_node(dag, target);
- dag_add_relation(dag, node2, node, 0);
- dag_add_parent_relation(dag, node2, node, 0);
-
+ dag_add_relation(dag, node2, node, 0, "IK Constraint");
+
if (con->type==CONSTRAINT_TYPE_KINEMATIC) {
bKinematicConstraint *data = (bKinematicConstraint *)con->data;
bPoseChannel *parchan;
@@ -2220,8 +2352,7 @@ void DAG_pose_sort(Object *ob)
/* Walk to the chain's root */
while (parchan) {
node3= dag_get_node(dag, parchan);
- dag_add_relation(dag, node2, node3, 0);
- dag_add_parent_relation(dag, node2, node3, 0);
+ dag_add_relation(dag, node2, node3, 0, "IK Constraint");
segcount++;
if (segcount==data->rootbone || segcount>255) break; // 255 is weak
@@ -2237,12 +2368,11 @@ void DAG_pose_sort(Object *ob)
}
}
if (addtoroot == 1 ) {
- dag_add_relation(dag, rootnode, node, 0);
- dag_add_parent_relation(dag, rootnode, node, 0);
+ dag_add_relation(dag, rootnode, node, 0, "Root Bone Relation");
}
}
- pose_check_cycle(dag);
+ dag_check_cycle(dag);
/* now we try to sort... */
tempbase.first= tempbase.last= NULL;
diff --git a/source/blender/blenkernel/intern/displist.c b/source/blender/blenkernel/intern/displist.c
index 6071ce1c871..44aa439ee3e 100644
--- a/source/blender/blenkernel/intern/displist.c
+++ b/source/blender/blenkernel/intern/displist.c
@@ -87,6 +87,8 @@
#include "RE_pipeline.h"
#include "RE_shader_ext.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
static void boundbox_displist(Object *ob);
@@ -203,8 +205,9 @@ void addnormalsDispList(Object *ob, ListBase *lb)
ndata= dl->nors;
for(a=0; a<dl->parts; a++) {
-
- DL_SURFINDEX(dl->flag & DL_CYCL_U, dl->flag & DL_CYCL_V, dl->nr, dl->parts);
+
+ if (surfindex_displist(dl, a, &b, &p1, &p2, &p3, &p4)==0)
+ break;
v1= vdata+ 3*p1;
n1= ndata+ 3*p1;
@@ -268,6 +271,33 @@ void count_displist(ListBase *lb, int *totvert, int *totface)
}
}
+int surfindex_displist(DispList *dl, int a, int *b, int *p1, int *p2, int *p3, int *p4)
+{
+ if((dl->flag & DL_CYCL_V)==0 && a==(dl->parts)-1) {
+ return 0;
+ }
+
+ if(dl->flag & DL_CYCL_U) {
+ (*p1)= dl->nr*a;
+ (*p2)= (*p1)+ dl->nr-1;
+ (*p3)= (*p1)+ dl->nr;
+ (*p4)= (*p2)+ dl->nr;
+ (*b)= 0;
+ } else {
+ (*p2)= dl->nr*a;
+ (*p1)= (*p2)+1;
+ (*p4)= (*p2)+ dl->nr;
+ (*p3)= (*p1)+ dl->nr;
+ (*b)= 1;
+ }
+
+ if( (dl->flag & DL_CYCL_V) && a==dl->parts-1) { \
+ (*p3)-= dl->nr*dl->parts; \
+ (*p4)-= dl->nr*dl->parts; \
+ }
+
+ return 1;
+}
/* ***************************** shade displist. note colors now are in rgb(a) order ******************** */
@@ -758,7 +788,10 @@ void reshadeall_displist(void)
for(base= G.scene->base.first; base; base= base->next) {
ob= base->object;
- freedisplist(&ob->disp);
+
+ if(ELEM5(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL))
+ freedisplist(&ob->disp);
+
if(base->lay & G.scene->lay) {
/* Metaballs have standard displist at the Object */
if(ob->type==OB_MBALL) shadeDispList(base);
@@ -786,7 +819,7 @@ static void curve_to_displist(Curve *cu, ListBase *nubase, ListBase *dispbase)
else
resolu= nu->resolu;
- if(nu->pntsu<2);
+ if(!check_valid_nurb_u(nu));
else if((nu->type & 7)==CU_BEZIER) {
/* count */
@@ -819,7 +852,7 @@ static void curve_to_displist(Curve *cu, ListBase *nubase, ListBase *dispbase)
data= dl->verts;
- if(nu->flagu & 1) {
+ if(nu->flagu & CU_CYCLIC) {
dl->type= DL_POLY;
a= nu->pntsu;
}
@@ -856,19 +889,22 @@ static void curve_to_displist(Curve *cu, ListBase *nubase, ListBase *dispbase)
}
}
else if((nu->type & 7)==CU_NURBS) {
- len= nu->pntsu*resolu;
+ len= (resolu*SEGMENTSU(nu));
+ if((nu->flagu & CU_CYCLIC)==0) len++;
+
dl= MEM_callocN(sizeof(DispList), "makeDispListsurf");
dl->verts= MEM_callocN(len*3*sizeof(float), "dlverts");
BLI_addtail(dispbase, dl);
dl->parts= 1;
+
dl->nr= len;
dl->col= nu->mat_nr;
dl->charidx = nu->charidx;
data= dl->verts;
- if(nu->flagu & 1) dl->type= DL_POLY;
+ if(nu->flagu & CU_CYCLIC) dl->type= DL_POLY;
else dl->type= DL_SEGM;
- makeNurbcurve(nu, data, resolu, 3);
+ makeNurbcurve(nu, data, NULL, NULL, resolu);
}
else if((nu->type & 7)==CU_POLY) {
len= nu->pntsu;
@@ -881,7 +917,7 @@ static void curve_to_displist(Curve *cu, ListBase *nubase, ListBase *dispbase)
dl->charidx = nu->charidx;
data= dl->verts;
- if(nu->flagu & 1) dl->type= DL_POLY;
+ if(nu->flagu & CU_CYCLIC) dl->type= DL_POLY;
else dl->type= DL_SEGM;
a= len;
@@ -989,9 +1025,9 @@ void filldisplist(ListBase *dispbase, ListBase *to)
efa= fillfacebase.first;
index= dlnew->index;
while(efa) {
- index[0]= (long)efa->v1->tmp.l;
- index[1]= (long)efa->v2->tmp.l;
- index[2]= (long)efa->v3->tmp.l;
+ index[0]= (intptr_t)efa->v1->tmp.l;
+ index[1]= (intptr_t)efa->v2->tmp.l;
+ index[2]= (intptr_t)efa->v3->tmp.l;
index+= 3;
efa= efa->next;
@@ -1174,7 +1210,7 @@ static ModifierData *curve_get_tesselate_point(Object *ob, int forRender, int ed
if ((md->mode & required_mode) != required_mode) continue;
if (mti->isDisabled && mti->isDisabled(md)) continue;
- if (md->type==eModifierType_Hook || md->type==eModifierType_Softbody) {
+ if (ELEM3(md->type, eModifierType_Hook, eModifierType_Softbody, eModifierType_MeshDeform)) {
preTesselatePoint = md;
}
}
@@ -1231,7 +1267,7 @@ void curve_calc_modifiers_pre(Object *ob, ListBase *nurb, int forRender, float (
*numVerts_r = numVerts;
}
-void curve_calc_modifiers_post(Object *ob, ListBase *nurb, ListBase *dispbase, int forRender, float (*originalVerts)[3], float (*deformedVerts)[3])
+static void curve_calc_modifiers_post(Object *ob, ListBase *nurb, ListBase *dispbase, int forRender, float (*originalVerts)[3], float (*deformedVerts)[3])
{
int editmode = (!forRender && ob==G.obedit);
ModifierData *md = modifiers_getVirtualModifierList(ob);
@@ -1250,13 +1286,40 @@ void curve_calc_modifiers_post(Object *ob, ListBase *nurb, ListBase *dispbase, i
for (; md; md=md->next) {
ModifierTypeInfo *mti = modifierType_getInfo(md->type);
-
+
if ((md->mode & required_mode) != required_mode) continue;
if (mti->isDisabled && mti->isDisabled(md)) continue;
if (mti->type!=eModifierTypeType_OnlyDeform && mti->type!=eModifierTypeType_DeformOrConstruct) continue;
- for (dl=dispbase->first; dl; dl=dl->next) {
- mti->deformVerts(md, ob, NULL, (float(*)[3]) dl->verts, (dl->type==DL_INDEX3)?dl->nr:dl->parts*dl->nr);
+ /* need to put all verts in 1 block for curve deform */
+ if(md->type==eModifierType_Curve) {
+ float *allverts, *fp;
+ int totvert= 0;
+
+ for (dl=dispbase->first; dl; dl=dl->next)
+ totvert+= (dl->type==DL_INDEX3)?dl->nr:dl->parts*dl->nr;
+
+ fp= allverts= MEM_mallocN(totvert*sizeof(float)*3, "temp vert");
+ for (dl=dispbase->first; dl; dl=dl->next) {
+ int offs= 3 * ((dl->type==DL_INDEX3)?dl->nr:dl->parts*dl->nr);
+ memcpy(fp, dl->verts, sizeof(float) * offs);
+ fp+= offs;
+ }
+
+ mti->deformVerts(md, ob, NULL, (float(*)[3]) allverts, totvert);
+
+ fp= allverts;
+ for (dl=dispbase->first; dl; dl=dl->next) {
+ int offs= 3 * ((dl->type==DL_INDEX3)?dl->nr:dl->parts*dl->nr);
+ memcpy(dl->verts, fp, sizeof(float) * offs);
+ fp+= offs;
+ }
+ MEM_freeN(allverts);
+ }
+ else {
+ for (dl=dispbase->first; dl; dl=dl->next) {
+ mti->deformVerts(md, ob, NULL, (float(*)[3]) dl->verts, (dl->type==DL_INDEX3)?dl->nr:dl->parts*dl->nr);
+ }
}
}
@@ -1278,7 +1341,8 @@ static void displist_surf_indices(DispList *dl)
for(a=0; a<dl->parts; a++) {
- DL_SURFINDEX(dl->flag & DL_CYCL_U, dl->flag & DL_CYCL_V, dl->nr, dl->parts);
+ if (surfindex_displist(dl, a, &b, &p1, &p2, &p3, &p4)==0)
+ break;
for(; b<dl->nr; b++, index+=4) {
index[0]= p1;
@@ -1333,13 +1397,13 @@ void makeDispListSurf(Object *ob, ListBase *dispbase, int forRender)
dl->rt= nu->flag;
data= dl->verts;
- if(nu->flagu & 1) dl->type= DL_POLY;
+ if(nu->flagu & CU_CYCLIC) dl->type= DL_POLY;
else dl->type= DL_SEGM;
- makeNurbcurve(nu, data, nu->resolu, 3);
+ makeNurbcurve(nu, data, NULL, NULL, nu->resolu);
}
else {
- len= nu->resolu*nu->resolv;
+ len= (nu->pntsu*nu->resolu) * (nu->pntsv*nu->resolv);
dl= MEM_callocN(sizeof(DispList), "makeDispListsurf");
dl->verts= MEM_callocN(len*3*sizeof(float), "dlverts");
@@ -1351,9 +1415,9 @@ void makeDispListSurf(Object *ob, ListBase *dispbase, int forRender)
data= dl->verts;
dl->type= DL_SURF;
-
- dl->parts= nu->resolu; /* in reverse, because makeNurbfaces works that way */
- dl->nr= nu->resolv;
+
+ dl->parts= (nu->pntsu*nu->resolu); /* in reverse, because makeNurbfaces works that way */
+ dl->nr= (nu->pntsv*nu->resolv);
if(nu->flagv & CU_CYCLIC) dl->flag|= DL_CYCL_U; /* reverse too! */
if(nu->flagu & CU_CYCLIC) dl->flag|= DL_CYCL_V;
@@ -1483,7 +1547,7 @@ void makeDispListCurveTypes(Object *ob, int forOrco)
float fac=1.0;
if (cu->taperobj==NULL) {
if ( (cu->bevobj!=NULL) || !((cu->flag & CU_FRONT) || (cu->flag & CU_BACK)) )
- fac = calc_curve_subdiv_radius(cu, nu, a);
+ fac = bevp->radius;
} else {
fac = calc_taper(cu->taperobj, a, bl->nr);
}
diff --git a/source/blender/blenkernel/intern/effect.c b/source/blender/blenkernel/intern/effect.c
index 881e67eef8a..66e8a039dda 100644
--- a/source/blender/blenkernel/intern/effect.c
+++ b/source/blender/blenkernel/intern/effect.c
@@ -58,6 +58,7 @@
#include "BKE_anim.h" /* needed for where_on_path */
#include "BKE_armature.h"
#include "BKE_blender.h"
+#include "BKE_collision.h"
#include "BKE_constraint.h"
#include "BKE_deform.h"
#include "BKE_depsgraph.h"
@@ -98,43 +99,19 @@ typedef struct VeNoCo {
float co[3], no[3];
} VeNoCo;
-Effect *add_effect(int type)
+/* ***************** PARTICLES ***************** */
+
+/* deprecated, only keep this for readfile.c */
+PartEff *give_parteff(Object *ob)
{
- Effect *eff=0;
PartEff *paf;
- int a;
- switch(type) {
- case EFF_PARTICLE:
- paf= MEM_callocN(sizeof(PartEff), "neweff");
- eff= (Effect *)paf;
-
- paf->sta= 1.0;
- paf->end= 100.0;
- paf->lifetime= 50.0;
- for(a=0; a<PAF_MAXMULT; a++) {
- paf->life[a]= 50.0;
- paf->child[a]= 4;
- paf->mat[a]= 1;
- }
-
- paf->totpart= 1000;
- paf->totkey= 8;
- paf->staticstep= 5;
- paf->defvec[2]= 1.0f;
- paf->nabla= 0.05f;
- paf->disp = 100;
- paf->speedtex = 8;
- paf->omat = 1;
- paf->flag= PAF_FACE;
-
- break;
+ paf= ob->effect.first;
+ while(paf) {
+ if(paf->type==EFF_PARTICLE) return paf;
+ paf= paf->next;
}
-
- eff->type= eff->buttype= type;
- eff->flag |= SELECT;
-
- return eff;
+ return 0;
}
void free_effect(Effect *eff)
@@ -161,172 +138,6 @@ void free_effects(ListBase *lb)
}
}
-Effect *copy_effect(Effect *eff)
-{
- Effect *effn;
-
- effn= MEM_dupallocN(eff);
- if(effn->type==EFF_PARTICLE) ((PartEff *)effn)->keys= 0;
-
- return effn;
-}
-
-void copy_act_effect(Object *ob)
-{
- /* return a copy of the active effect */
- Effect *effn, *eff;
-
- eff= ob->effect.first;
- while(eff) {
- if(eff->flag & SELECT) {
-
- effn= copy_effect(eff);
- BLI_addtail(&ob->effect, effn);
-
- eff->flag &= ~SELECT;
- return;
-
- }
- eff= eff->next;
- }
-
- /* when it comes here: add new effect */
- eff= add_effect(EFF_PARTICLE);
- BLI_addtail(&ob->effect, eff);
-
-}
-
-void copy_effects(ListBase *lbn, ListBase *lb)
-{
- Effect *eff, *effn;
-
- lbn->first= lbn->last= 0;
-
- eff= lb->first;
- while(eff) {
- effn= copy_effect(eff);
- BLI_addtail(lbn, effn);
-
- eff= eff->next;
- }
-
-}
-
-void deselectall_eff(Object *ob)
-{
- Effect *eff= ob->effect.first;
-
- while(eff) {
- eff->flag &= ~SELECT;
- eff= eff->next;
- }
-}
-
-/* ***************** PARTICLES ***************** */
-
-static Particle *new_particle(PartEff *paf)
-{
- static Particle *pa;
- static int cur;
-
- /* we agree: when paf->keys==0: alloc */
- if(paf->keys==NULL) {
- pa= paf->keys= MEM_callocN( paf->totkey*paf->totpart*sizeof(Particle), "particlekeys" );
- cur= 0;
- }
- else {
- if(cur && cur<paf->totpart) pa+=paf->totkey;
- cur++;
- }
- return pa;
-}
-
-PartEff *give_parteff(Object *ob)
-{
- PartEff *paf;
-
- paf= ob->effect.first;
- while(paf) {
- if(paf->type==EFF_PARTICLE) return paf;
- paf= paf->next;
- }
- return 0;
-}
-
-void where_is_particle(PartEff *paf, Particle *pa, float ctime, float *vec)
-{
- Particle *p[4];
- float dt, t[4];
- int a;
-
- if(paf->totkey==1 || ctime < pa->time) {
- VECCOPY(vec, pa->co);
- return;
- }
-
- /* first find the first particlekey */
- a= (int)((paf->totkey-1)*(ctime-pa->time)/pa->lifetime);
- if(a>=paf->totkey) a= paf->totkey-1;
- else if(a<0) a= 0;
-
- pa+= a;
-
- if(a>0) p[0]= pa-1; else p[0]= pa;
- p[1]= pa;
-
- if(a+1<paf->totkey) p[2]= pa+1; else p[2]= pa;
- if(a+2<paf->totkey) p[3]= pa+2; else p[3]= p[2];
-
- if(p[1]==p[2] || p[2]->time == p[1]->time) dt= 0.0;
- else dt= (ctime-p[1]->time)/(p[2]->time - p[1]->time);
-
- if(paf->flag & PAF_BSPLINE) set_four_ipo(dt, t, KEY_BSPLINE);
- else set_four_ipo(dt, t, KEY_CARDINAL);
-
- vec[0]= t[0]*p[0]->co[0] + t[1]*p[1]->co[0] + t[2]*p[2]->co[0] + t[3]*p[3]->co[0];
- vec[1]= t[0]*p[0]->co[1] + t[1]*p[1]->co[1] + t[2]*p[2]->co[1] + t[3]*p[3]->co[1];
- vec[2]= t[0]*p[0]->co[2] + t[1]*p[1]->co[2] + t[2]*p[2]->co[2] + t[3]*p[3]->co[2];
-
-}
-
-static void particle_tex(MTex *mtex, PartEff *paf, float *co, float *no)
-{
- float tin, tr, tg, tb, ta;
- float old;
-
- externtex(mtex, co, &tin, &tr, &tg, &tb, &ta);
-
- if(paf->texmap==PAF_TEXINT) {
- tin*= paf->texfac;
- no[0]+= tin*paf->defvec[0];
- no[1]+= tin*paf->defvec[1];
- no[2]+= tin*paf->defvec[2];
- }
- else if(paf->texmap==PAF_TEXRGB) {
- no[0]+= (tr-0.5f)*paf->texfac;
- no[1]+= (tg-0.5f)*paf->texfac;
- no[2]+= (tb-0.5f)*paf->texfac;
- }
- else { /* PAF_TEXGRAD */
-
- old= tin;
- co[0]+= paf->nabla;
- externtex(mtex, co, &tin, &tr, &tg, &tb, &ta);
- no[0]+= (old-tin)*paf->texfac;
-
- co[0]-= paf->nabla;
- co[1]+= paf->nabla;
- externtex(mtex, co, &tin, &tr, &tg, &tb, &ta);
- no[1]+= (old-tin)*paf->texfac;
-
- co[1]-= paf->nabla;
- co[2]+= paf->nabla;
- externtex(mtex, co, &tin, &tr, &tg, &tb, &ta);
- no[2]+= (old-tin)*paf->texfac;
-
- }
-}
-
/* -------------------------- Effectors ------------------ */
static void add_to_effectorcache(ListBase *lb, Object *ob, Object *obsrc)
@@ -349,6 +160,13 @@ static void add_to_effectorcache(ListBase *lb, Object *ob, Object *obsrc)
}
}
else if(pd->forcefield) {
+
+ if(pd->forcefield == PFIELD_WIND)
+ {
+ pd->rng = rng_new(1);
+ rng_srandom(pd->rng, (unsigned int)(ceil(PIL_check_seconds_timer()))); // use better seed
+ }
+
ec= MEM_callocN(sizeof(pEffectorCache), "effector cache");
ec->ob= ob;
BLI_addtail(lb, ec);
@@ -397,1713 +215,354 @@ void pdEndEffectors(ListBase *lb)
pEffectorCache *ec;
/* restore full copy */
for(ec= lb->first; ec; ec= ec->next)
+ {
+ if(ec->ob->pd && (ec->ob->pd->forcefield == PFIELD_WIND))
+ rng_free(ec->ob->pd->rng);
+
*(ec->ob)= ec->obcopy;
+ }
BLI_freelistN(lb);
}
}
-/* local for this c file, only for guides now */
-static void precalc_effectors(Object *ob, PartEff *paf, Particle *pa, ListBase *lb)
-{
- pEffectorCache *ec;
-
- for(ec= lb->first; ec; ec= ec->next) {
- PartDeflect *pd= ec->ob->pd;
-
- ec->oldspeed[0]= ec->oldspeed[1]= ec->oldspeed[2]= 0.0f;
-
- if(pd->forcefield==PFIELD_GUIDE && ec->ob->type==OB_CURVE) {
- float vec[4], dir[3];
-
- if(!(paf->flag & PAF_STATIC))
- where_is_object_time(ec->ob, pa->time);
-
- /* scale corrects speed vector to curve size */
- if(paf->totkey>1) ec->scale= (paf->totkey-1)/pa->lifetime;
- else ec->scale= 1.0f;
-
- /* time_scale is for random life */
- if(pa->lifetime>paf->lifetime)
- ec->time_scale= paf->lifetime/pa->lifetime;
- else
- ec->time_scale= pa->lifetime/paf->lifetime;
-
- /* distance of first path point to particle origin */
- where_on_path(ec->ob, 0.0f, vec, dir);
- VECCOPY(ec->oldloc, vec); /* store local coord for differences */
- Mat4MulVecfl(ec->ob->obmat, vec);
-
- /* for static we need to move to global space */
- if(paf->flag & PAF_STATIC) {
- VECCOPY(dir, pa->co);
- Mat4MulVecfl(ob->obmat, dir);
- ec->guide_dist= VecLenf(vec, dir);
- }
- else
- ec->guide_dist= VecLenf(vec, pa->co);
- }
- }
-}
+/************************************************/
+/* Effectors */
+/************************************************/
-/* -------- pdDoEffectors() --------
- generic force/speed system, now used for particles and softbodies
- lb = listbase with objects that take part in effecting
- opco = global coord, as input
- force = force accumulator
- speed = actual current speed which can be altered
- cur_time = "external" time in frames, is constant for static particles
- loc_time = "local" time in frames, range <0-1> for the lifetime of particle
- par_layer = layer the caller is in
- flags = only used for softbody wind now
- guide = old speed of particle
+// triangle - ray callback function
+static void eff_tri_ray_hit(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
+{
+ // whenever we hit a bounding box, we don't check further
+ hit->dist = -1;
+ hit->index = 1;
+}
-*/
-void pdDoEffectors(ListBase *lb, float *opco, float *force, float *speed, float cur_time, float loc_time, unsigned int flags)
+// get visibility of a wind ray
+static float eff_calc_visibility(Object *ob, float *co, float *dir)
{
-/*
- Modifies the force on a particle according to its
- relation with the effector object
- Different kind of effectors include:
- Forcefields: Gravity-like attractor
- (force power is related to the inverse of distance to the power of a falloff value)
- Vortex fields: swirling effectors
- (particles rotate around Z-axis of the object. otherwise, same relation as)
- (Forcefields, but this is not done through a force/acceleration)
- Guide: particles on a path
- (particles are guided along a curve bezier or old nurbs)
- (is independent of other effectors)
-*/
- Object *ob;
- pEffectorCache *ec;
- PartDeflect *pd;
- float vect_to_vert[3];
- float f_force, force_vec[3];
- float *obloc;
- float distance, force_val, ffall_val;
- float guidecollect[3], guidedist= 0.0f;
- int cur_frame;
+ CollisionModifierData **collobjs = NULL;
+ int numcollobj = 0, i;
+ float norm[3], len = 0.0;
+ float visibility = 1.0;
- guidecollect[0]= guidecollect[1]= guidecollect[2]=0.0f;
-
- /* Cycle through collected objects, get total of (1/(gravity_strength * dist^gravity_power)) */
- /* Check for min distance here? (yes would be cool to add that, ton) */
+ collobjs = get_collisionobjects(ob, &numcollobj);
- for(ec = lb->first; ec; ec= ec->next) {
- /* object effectors were fully checked to be OK to evaluate! */
- ob= ec->ob;
- pd= ob->pd;
-
- /* Get IPO force strength and fall off values here */
- if (has_ipo_code(ob->ipo, OB_PD_FSTR))
- force_val = IPO_GetFloatValue(ob->ipo, OB_PD_FSTR, cur_time);
- else
- force_val = pd->f_strength;
+ if(!collobjs)
+ return 0;
+
+ VECCOPY(norm, dir);
+ VecMulf(norm, -1.0);
+ len = Normalize(norm);
+
+ // check all collision objects
+ for(i = 0; i < numcollobj; i++)
+ {
+ CollisionModifierData *collmd = collobjs[i];
- if (has_ipo_code(ob->ipo, OB_PD_FFALL))
- ffall_val = IPO_GetFloatValue(ob->ipo, OB_PD_FFALL, cur_time);
- else
- ffall_val = pd->f_power;
+ if(collmd->bvhtree)
+ {
+ BVHTreeRayHit hit;
- /* Need to set r.cfra for paths (investigate, ton) (uses ob->ctime now, ton) */
- if(ob->ctime!=cur_time) {
- cur_frame = G.scene->r.cfra;
- G.scene->r.cfra = (int)cur_time;
- where_is_object_time(ob, cur_time);
- G.scene->r.cfra = cur_frame;
- }
-
- /* use center of object for distance calculus */
- obloc= ob->obmat[3];
- VECSUB(vect_to_vert, obloc, opco);
- distance = VecLength(vect_to_vert);
+ hit.index = -1;
+ hit.dist = len + FLT_EPSILON;
- if((pd->flag & PFIELD_USEMAX) && distance>pd->maxdist && pd->forcefield != PFIELD_GUIDE)
- ; /* don't do anything */
- else if(pd->forcefield == PFIELD_WIND) {
- VECCOPY(force_vec, ob->obmat[2]);
-
- /* wind works harder perpendicular to normal, would be nice for softbody later (ton) */
-
- /* Limit minimum distance to vertex so that */
- /* the force is not too big */
- if (distance < 0.001) distance = 0.001f;
- f_force = (force_val)*(1/(1000 * (float)pow((double)distance, (double)ffall_val)));
- /* this option for softbody only */
- if(flags && PE_WIND_AS_SPEED){
- speed[0] -= (force_vec[0] * f_force );
- speed[1] -= (force_vec[1] * f_force );
- speed[2] -= (force_vec[2] * f_force );
- }
- else{
- force[0] += force_vec[0]*f_force;
- force[1] += force_vec[1]*f_force;
- force[2] += force_vec[2]*f_force;
- }
- }
- else if(pd->forcefield == PFIELD_FORCE) {
-
- /* only use center of object */
- obloc= ob->obmat[3];
-
- /* Now calculate the gravitational force */
- VECSUB(vect_to_vert, obloc, opco);
- distance = VecLength(vect_to_vert);
-
- /* Limit minimum distance to vertex so that */
- /* the force is not too big */
- if (distance < 0.001) distance = 0.001f;
- f_force = (force_val)*(1.0/(1000.0 * (float)pow((double)distance, (double)ffall_val)));
- force[0] += (vect_to_vert[0] * f_force );
- force[1] += (vect_to_vert[1] * f_force );
- force[2] += (vect_to_vert[2] * f_force );
- }
- else if(pd->forcefield == PFIELD_VORTEX) {
- float vortexvec[3];
-
- /* only use center of object */
- obloc= ob->obmat[3];
-
- /* Now calculate the vortex force */
- VECSUB(vect_to_vert, obloc, opco);
- distance = VecLength(vect_to_vert);
-
- Crossf(force_vec, ob->obmat[2], vect_to_vert);
- Normalize(force_vec);
-
- /* Limit minimum distance to vertex so that */
- /* the force is not too big */
- if (distance < 0.001) distance = 0.001f;
- f_force = (force_val)*(1.0/(100.0 * (float)pow((double)distance, (double)ffall_val)));
- vortexvec[0]= -(force_vec[0] * f_force );
- vortexvec[1]= -(force_vec[1] * f_force );
- vortexvec[2]= -(force_vec[2] * f_force );
-
- /* this option for softbody only */
- if(flags &&PE_WIND_AS_SPEED) {
- speed[0]+= vortexvec[0];
- speed[1]+= vortexvec[1];
- speed[2]+= vortexvec[2];
- }
- else {
- /* since vortex alters the speed, we have to correct for the previous vortex result */
- speed[0]+= vortexvec[0] - ec->oldspeed[0];
- speed[1]+= vortexvec[1] - ec->oldspeed[1];
- speed[2]+= vortexvec[2] - ec->oldspeed[2];
+ // check if the way is blocked
+ if(BLI_bvhtree_ray_cast(collmd->bvhtree, co, norm, 0.0f, &hit, eff_tri_ray_hit, NULL)>=0)
+ {
+ // visibility is only between 0 and 1, calculated from 1-absorption
+ visibility *= MAX2(0.0, MIN2(1.0, (1.0-((float)collmd->absorption)*0.01)));
- VECCOPY(ec->oldspeed, vortexvec);
+ if(visibility <= 0.0f)
+ break;
}
}
- else if(pd->forcefield == PFIELD_GUIDE) {
- float guidevec[4], guidedir[3];
- float mindist= force_val; /* force_val is actually mindist in the UI */
-
- distance= ec->guide_dist;
-
- /* WARNING: bails out with continue here */
- if((pd->flag & PFIELD_USEMAX) && distance>pd->maxdist) continue;
-
- /* calculate contribution factor for this guide */
- if(distance<=mindist) f_force= 1.0f;
- else if(pd->flag & PFIELD_USEMAX) {
- if(distance>pd->maxdist || mindist>=pd->maxdist) f_force= 0.0f;
- else {
- f_force= 1.0f - (distance-mindist)/(pd->maxdist - mindist);
- if(ffall_val!=0.0f)
- f_force = (float)pow(f_force, ffall_val+1.0);
- }
- }
- else {
- f_force= 1.0f/(1.0f + distance-mindist);
- if(ffall_val!=0.0f)
- f_force = (float)pow(f_force, ffall_val+1.0);
- }
-
- /* now derive path point from loc_time */
- if(pd->flag & PFIELD_GUIDE_PATH_ADD)
- where_on_path(ob, f_force*loc_time*ec->time_scale, guidevec, guidedir);
- else
- where_on_path(ob, loc_time*ec->time_scale, guidevec, guidedir);
-
- VECSUB(guidedir, guidevec, ec->oldloc);
- VECCOPY(ec->oldloc, guidevec);
-
- Mat4Mul3Vecfl(ob->obmat, guidedir);
- VecMulf(guidedir, ec->scale); /* correction for lifetime and speed */
-
- /* we subtract the speed we gave it previous step */
- VECCOPY(guidevec, guidedir);
- VECSUB(guidedir, guidedir, ec->oldspeed);
- VECCOPY(ec->oldspeed, guidevec);
-
- /* if it fully contributes, we stop */
- if(f_force==1.0) {
- VECCOPY(guidecollect, guidedir);
- guidedist= 1.0f;
- break;
- }
- else if(guidedist<1.0f) {
- VecMulf(guidedir, f_force);
- VECADD(guidecollect, guidecollect, guidedir);
- guidedist += f_force;
- }
- }
- }
-
- /* all guides are accumulated here */
- if(guidedist!=0.0f) {
- if(guidedist!=1.0f) VecMulf(guidecollect, 1.0f/guidedist);
- VECADD(speed, speed, guidecollect);
}
-}
-
-static void cache_object_vertices(Object *ob)
-{
- Mesh *me;
- MVert *mvert;
- float *fp;
- int a;
- me= ob->data;
- if(me->totvert==0) return;
-
- fp= ob->sumohandle= MEM_mallocN(3*sizeof(float)*me->totvert, "cache particles");
- mvert= me->mvert;
- a= me->totvert;
- while(a--) {
- VECCOPY(fp, mvert->co);
- Mat4MulVecfl(ob->obmat, fp);
- mvert++;
- fp+= 3;
- }
+ MEM_freeN(collobjs);
+
+ return visibility;
}
-static int pdDoDeflection(RNG *rng, float opco[3], float npco[3], float opno[3],
- float npno[3], float life, float force[3], int def_depth,
- float cur_time, unsigned int par_layer, int *last_object,
- int *last_face, int *same_face)
+// noise function for wind e.g.
+static float wind_func(struct RNG *rng, float strength)
{
- /* Particle deflection code */
- /* The code is in two sections: the first part checks whether a particle has */
- /* intersected a face of a deflector mesh, given its old and new co-ords, opco and npco */
- /* and which face it hit first */
- /* The second part calculates the new co-ordinates given that collision and updates */
- /* the new co-ordinates accordingly */
- Base *base;
- Object *ob, *deflection_object = NULL;
- Mesh *def_mesh;
- MFace *mface, *deflection_face = NULL;
- float *v1, *v2, *v3, *v4, *vcache=NULL;
- float nv1[3], nv2[3], nv3[3], nv4[3], edge1[3], edge2[3];
- float dv1[3] = {0}, dv2[3] = {0}, dv3[3] = {0};
- float vect_to_int[3], refl_vel[3];
- float d_intersect_co[3], d_intersect_vect[3], d_nvect[3], d_i_co_above[3];
- float forcec[3];
- float k_point3, dist_to_plane;
- float first_dist, ref_plane_mag;
- float dk_plane=0, dk_point1=0;
- float icalctop, icalcbot, n_mag;
- float mag_iv, x_m,y_m,z_m;
- float damping, perm_thresh;
- float perm_val, rdamp_val;
- int a, deflected=0, deflected_now=0;
- float t,t2, min_t;
- float mat[3][3], obloc[3] = {0};
- int cur_frame;
- float time_before, time_after;
- float force_mag_norm;
- int d_object=0, d_face=0, ds_object=0, ds_face=0;
-
- first_dist = 200000;
- min_t = 200000;
-
- /* The first part of the code, finding the first intersected face*/
- base= G.scene->base.first;
- while (base) {
- /*Only proceed for mesh object in same layer */
- if(base->object->type==OB_MESH && (base->lay & par_layer)) {
- ob= base->object;
- /* only with deflecting set */
- if(ob->pd && ob->pd->deflect) {
- def_mesh= ob->data;
-
- d_object = d_object + 1;
-
- d_face = d_face + 1;
- mface= def_mesh->mface;
- a = def_mesh->totface;
-
-
- if(ob->parent==NULL && ob->ipo==NULL) { // static
- if(ob->sumohandle==NULL) cache_object_vertices(ob);
- vcache= ob->sumohandle;
- }
- else {
- /*Find out where the object is at this time*/
- cur_frame = G.scene->r.cfra;
- G.scene->r.cfra = (int)cur_time;
- where_is_object_time(ob, cur_time);
- G.scene->r.cfra = cur_frame;
-
- /*Pass the values from ob->obmat to mat*/
- /*and the location values to obloc */
- Mat3CpyMat4(mat,ob->obmat);
- obloc[0] = ob->obmat[3][0];
- obloc[1] = ob->obmat[3][1];
- obloc[2] = ob->obmat[3][2];
- vcache= NULL;
-
- }
-
- while (a--) {
-
- if(vcache) {
- v1= vcache+ 3*(mface->v1);
- VECCOPY(nv1, v1);
- v1= vcache+ 3*(mface->v2);
- VECCOPY(nv2, v1);
- v1= vcache+ 3*(mface->v3);
- VECCOPY(nv3, v1);
- v1= vcache+ 3*(mface->v4);
- VECCOPY(nv4, v1);
- }
- else {
- /* Calculate the global co-ordinates of the vertices*/
- v1= (def_mesh->mvert+(mface->v1))->co;
- v2= (def_mesh->mvert+(mface->v2))->co;
- v3= (def_mesh->mvert+(mface->v3))->co;
- v4= (def_mesh->mvert+(mface->v4))->co;
+ int random = (rng_getInt(rng)+1) % 65535; // max 2357
+ float force = rng_getFloat(rng) + 1.0f;
+ float ret;
+ float sign = 0;
- VECCOPY(nv1, v1);
- VECCOPY(nv2, v2);
- VECCOPY(nv3, v3);
- VECCOPY(nv4, v4);
+ sign = (random > 32000.0) ? 1.0: -1.0; // dividing by 2 is not giving equal sign distribution
- /*Apply the objects deformation matrix*/
- Mat3MulVecfl(mat, nv1);
- Mat3MulVecfl(mat, nv2);
- Mat3MulVecfl(mat, nv3);
- Mat3MulVecfl(mat, nv4);
+ ret = sign*((float)random / force)*strength/65535.0f;
- VECADD(nv1, nv1, obloc);
- VECADD(nv2, nv2, obloc);
- VECADD(nv3, nv3, obloc);
- VECADD(nv4, nv4, obloc);
- }
-
- deflected_now = 0;
-
-
-
-// t= 0.5; // this is labda of line, can use it optimize quad intersection
-// sorry but no .. see below (BM)
- if( LineIntersectsTriangle(opco, npco, nv1, nv2, nv3, &t, NULL) ) {
- if (t < min_t) {
- deflected = 1;
- deflected_now = 1;
- }
- }
-// else if (mface->v4 && (t>=0.0 && t<=1.0)) {
-// no, you can't skip testing the other triangle
-// it might give a smaller t on (close to) the edge .. this is numerics not esoteric maths :)
-// note: the 2 triangles don't need to share a plane ! (BM)
- if (mface->v4) {
- if( LineIntersectsTriangle(opco, npco, nv1, nv3, nv4, &t2, NULL) ) {
- if (t2 < min_t) {
- deflected = 1;
- deflected_now = 2;
- }
- }
- }
-
- if ((deflected_now > 0) && ((t < min_t) ||(t2 < min_t))) {
- min_t = t;
- ds_object = d_object;
- ds_face = d_face;
- deflection_object = ob;
- deflection_face = mface;
- if (deflected_now==1) {
- min_t = t;
- VECCOPY(dv1, nv1);
- VECCOPY(dv2, nv2);
- VECCOPY(dv3, nv3);
- }
- else {
- min_t = t2;
- VECCOPY(dv1, nv1);
- VECCOPY(dv2, nv3);
- VECCOPY(dv3, nv4);
- }
- }
- mface++;
- }
- }
- }
- base = base->next;
- }
-
-
- /* Here's the point to do the permeability calculation */
- /* Set deflected to 0 if a random number is below the value */
- /* Get the permeability IPO here*/
- if (deflected) {
-
- if (has_ipo_code(deflection_object->ipo, OB_PD_PERM))
- perm_val = IPO_GetFloatValue(deflection_object->ipo, OB_PD_PERM, cur_time);
- else
- perm_val = deflection_object->pd->pdef_perm;
-
- perm_thresh = rng_getFloat(rng) - perm_val;
- if (perm_thresh < 0 ) {
- deflected = 0;
- }
- }
-
- /* Now for the second part of the deflection code - work out the new speed */
- /* and position of the particle if a collision occurred */
- if (deflected) {
- VECSUB(edge1, dv1, dv2);
- VECSUB(edge2, dv3, dv2);
- Crossf(d_nvect, edge2, edge1);
- n_mag = Normalize(d_nvect);
- dk_plane = INPR(d_nvect, nv1);
- dk_point1 = INPR(d_nvect,opco);
-
- VECSUB(d_intersect_vect, npco, opco);
-
- d_intersect_co[0] = opco[0] + (min_t * (npco[0] - opco[0]));
- d_intersect_co[1] = opco[1] + (min_t * (npco[1] - opco[1]));
- d_intersect_co[2] = opco[2] + (min_t * (npco[2] - opco[2]));
-
- d_i_co_above[0] = (d_intersect_co[0] + (0.001f * d_nvect[0]));
- d_i_co_above[1] = (d_intersect_co[1] + (0.001f * d_nvect[1]));
- d_i_co_above[2] = (d_intersect_co[2] + (0.001f * d_nvect[2]));
- mag_iv = Normalize(d_intersect_vect);
- VECCOPY(npco, d_intersect_co);
-
- VECSUB(vect_to_int, opco, d_intersect_co);
- first_dist = Normalize(vect_to_int);
-
- /* Work out the lengths of time before and after collision*/
- time_before = (life*(first_dist / (mag_iv)));
- time_after = (life*((mag_iv - first_dist) / (mag_iv)));
-
- /* We have to recalculate what the speed would have been at the */
- /* point of collision, not the key frame time */
- npno[0]= opno[0] + time_before*force[0];
- npno[1]= opno[1] + time_before*force[1];
- npno[2]= opno[2] + time_before*force[2];
-
-
- /* Reflect the speed vector in the face */
- x_m = (2 * npno[0] * d_nvect[0]);
- y_m = (2 * npno[1] * d_nvect[1]);
- z_m = (2 * npno[2] * d_nvect[2]);
- refl_vel[0] = npno[0] - (d_nvect[0] * (x_m + y_m + z_m));
- refl_vel[1] = npno[1] - (d_nvect[1] * (x_m + y_m + z_m));
- refl_vel[2] = npno[2] - (d_nvect[2] * (x_m + y_m + z_m));
-
- /*A random variation in the damping factor........ */
- /*Get the IPO values for damping here*/
-
- if (has_ipo_code(deflection_object->ipo, OB_PD_SDAMP))
- damping = IPO_GetFloatValue(deflection_object->ipo, OB_PD_SDAMP, cur_time);
- else
- damping = deflection_object->pd->pdef_damp;
-
- if (has_ipo_code(deflection_object->ipo, OB_PD_RDAMP))
- rdamp_val = IPO_GetFloatValue(deflection_object->ipo, OB_PD_RDAMP, cur_time);
- else
- rdamp_val = deflection_object->pd->pdef_rdamp;
-
- damping = damping + ((1.0f - damping) * rng_getFloat(rng) *rdamp_val);
- damping = damping * damping;
- ref_plane_mag = INPR(refl_vel,d_nvect);
-
- if (damping > 0.999) damping = 0.999f;
-
- /* Now add in the damping force - only damp in the direction of */
- /* the faces normal vector */
- npno[0] = (refl_vel[0] - (d_nvect[0] * ref_plane_mag * damping));
- npno[1] = (refl_vel[1] - (d_nvect[1] * ref_plane_mag * damping));
- npno[2] = (refl_vel[2] - (d_nvect[2] * ref_plane_mag * damping));
-
- /* Now reset opno */
- VECCOPY(opno,npno);
- VECCOPY(forcec, force);
-
- /* If the particle has bounced more than four times on the same */
- /* face within this cycle (depth > 4, same face > 4 ) */
- /* Then set the force to be only that component of the force */
- /* in the same direction as the face normal */
- /* i.e. subtract the component of the force in the direction */
- /* of the face normal from the actual force */
- if ((ds_object == *last_object) && (ds_face == *last_face)) {
- /* Increment same_face */
- *same_face = *same_face + 1;
- if ((*same_face > 3) && (def_depth > 3)) {
- force_mag_norm = INPR(forcec, d_nvect);
- forcec[0] = forcec[0] - (d_nvect[0] * force_mag_norm);
- forcec[1] = forcec[1] - (d_nvect[1] * force_mag_norm);
- forcec[2] = forcec[2] - (d_nvect[2] * force_mag_norm);
- }
- }
- else *same_face = 1;
-
- *last_object = ds_object;
- *last_face = ds_face;
-
- /* We have the particles speed at the point of collision */
- /* Now we want the particles speed at the current key frame */
-
- npno[0]= npno[0] + time_after*forcec[0];
- npno[1]= npno[1] + time_after*forcec[1];
- npno[2]= npno[2] + time_after*forcec[2];
-
- /* Now we have to recalculate pa->co for the remainder*/
- /* of the time since the intersect*/
- npco[0]= npco[0] + time_after*npno[0];
- npco[1]= npco[1] + time_after*npno[1];
- npco[2]= npco[2] + time_after*npno[2];
-
- /* And set the old co-ordinates back to the point just above the intersection */
- VECCOPY(opco, d_i_co_above);
-
- /* Finally update the time */
- life = time_after;
- cur_time += time_before;
-
- /* The particle may have fallen through the face again by now!!*/
- /* So check if the particle has changed sides of the plane compared*/
- /* the co-ordinates at the last keyframe*/
- /* But only do this as a last resort, if we've got to the end of the */
- /* number of collisions allowed */
- if (def_depth==9) {
- k_point3 = INPR(d_nvect,npco);
- if (((dk_plane > k_point3) && (dk_plane < dk_point1))||((dk_plane < k_point3) && (dk_plane > dk_point1))) {
-
- /* Yup, the pesky particle may have fallen through a hole!!! */
- /* So we'll cheat a bit and move the particle along the normal vector */
- /* until it's just the other side of the plane */
- icalctop = (dk_plane - d_nvect[0]*npco[0] - d_nvect[1]*npco[1] - d_nvect[2]*npco[2]);
- icalcbot = (d_nvect[0]*d_nvect[0] + d_nvect[1]*d_nvect[1] + d_nvect[2]*d_nvect[2]);
- dist_to_plane = icalctop / icalcbot;
-
- /* Now just increase the distance a little to place */
- /* the point the other side of the plane */
- dist_to_plane *= 1.1f;
- npco[0]= npco[0] + (dist_to_plane * d_nvect[0]);
- npco[1]= npco[1] + (dist_to_plane * d_nvect[1]);
- npco[2]= npco[2] + (dist_to_plane * d_nvect[2]);
-
- }
- }
- }
- return deflected;
+ return ret;
}
-/*
- rng= random number generator
- ob = object that spawns the particles
- depth = for fireworks
- nr = index nr of current particle
- paf = the particle system
- part = current particle
- force = force vector
- deform = flag to indicate lattice deform
- */
-static void make_particle_keys(RNG *rng, Object *ob, int depth, int nr, PartEff *paf, Particle *part, float *force, int deform, MTex *mtex, ListBase *effectorbase)
+
+static float falloff_func(float fac, int usemin, float mindist, int usemax, float maxdist, float power)
{
- Particle *pa, *opa = NULL;
- float damp, deltalife, life;
- float cur_time, maxspeed= paf->maxlen/(float)paf->totkey;
- float opco[3], opno[3], npco[3], npno[3], new_force[3], new_speed[3];
- int b, rt1, rt2, deflected, deflection, finish_defs, def_count;
- int last_ob, last_fc, same_fc;
-
- damp= 1.0f-paf->damp;
- pa= part;
-
- /* start speed: random */
- if(paf->randfac!=0.0) {
- pa->no[0]+= paf->randfac*(rng_getFloat(rng) - 0.5f);
- pa->no[1]+= paf->randfac*(rng_getFloat(rng) - 0.5f);
- pa->no[2]+= paf->randfac*(rng_getFloat(rng) - 0.5f);
- }
+ if(!usemin)
+ mindist= 0.0f;
- /* start speed: texture */
- if(mtex && paf->texfac!=0.0) {
- particle_tex(mtex, paf, pa->co, pa->no);
+ if(fac < mindist) {
+ return 1.0f;
}
+ else if(usemax) {
+ if(fac>maxdist || (maxdist-mindist)<=0.0f)
+ return 0.0f;
- /* effectors here? */
- if(effectorbase)
- precalc_effectors(ob, paf, pa, effectorbase);
-
- if(paf->totkey>1) deltalife= pa->lifetime/(paf->totkey-1);
- else deltalife= pa->lifetime;
-
- /* longer lifetime results in longer distance covered */
- VecMulf(pa->no, deltalife);
-
- opa= pa;
- pa++;
-
- for(b=1; b<paf->totkey; b++) {
-
- /* new time */
- pa->time= opa->time+deltalife;
- cur_time = pa->time;
-
- /* set initial variables */
- VECCOPY(opco, opa->co);
- VECCOPY(new_force, force);
- VECCOPY(new_speed, opa->no);
- VecMulf(new_speed, 1.0f/deltalife);
- //new_speed[0] = new_speed[1] = new_speed[2] = 0.0f;
-
- /* handle differences between static (local coords, fixed frame) and dynamic */
- if(effectorbase) {
- float loc_time= ((float)b)/(float)(paf->totkey-1);
-
- if(paf->flag & PAF_STATIC) {
- float opco1[3], new_force1[3];
-
- /* move co and force to global coords */
- VECCOPY(opco1, opco);
- Mat4MulVecfl(ob->obmat, opco1);
- VECCOPY(new_force1, new_force);
- Mat4Mul3Vecfl(ob->obmat, new_force1);
- Mat4Mul3Vecfl(ob->obmat, new_speed);
-
- cur_time = G.scene->r.cfra;
-
- /* force fields */
- pdDoEffectors(effectorbase, opco1, new_force1, new_speed, cur_time, loc_time, 0);
-
- /* move co, force and newspeed back to local */
- VECCOPY(opco, opco1);
- Mat4MulVecfl(ob->imat, opco);
- VECCOPY(new_force, new_force1);
- Mat4Mul3Vecfl(ob->imat, new_force);
- Mat4Mul3Vecfl(ob->imat, new_speed);
- }
- else {
- /* force fields */
- pdDoEffectors(effectorbase, opco, new_force, new_speed, cur_time, loc_time, 0);
- }
- }
-
- /* new speed */
- pa->no[0]= deltalife * (new_speed[0] + new_force[0]);
- pa->no[1]= deltalife * (new_speed[1] + new_force[1]);
- pa->no[2]= deltalife * (new_speed[2] + new_force[2]);
-
- /* speed limitor */
- if((paf->flag & PAF_STATIC) && maxspeed!=0.0f) {
- float len= VecLength(pa->no);
- if(len > maxspeed)
- VecMulf(pa->no, maxspeed/len);
- }
-
- /* new location */
- pa->co[0]= opa->co[0] + pa->no[0];
- pa->co[1]= opa->co[1] + pa->no[1];
- pa->co[2]= opa->co[2] + pa->no[2];
-
- /* Particle deflection code */
- if((paf->flag & PAF_STATIC)==0) {
- deflection = 0;
- finish_defs = 1;
- def_count = 0;
-
- VECCOPY(opno, opa->no);
- VECCOPY(npco, pa->co);
- VECCOPY(npno, pa->no);
-
- life = deltalife;
- cur_time -= deltalife;
-
- last_ob = -1;
- last_fc = -1;
- same_fc = 0;
-
- /* First call the particle deflection check for the particle moving */
- /* between the old co-ordinates and the new co-ordinates */
- /* If a deflection occurs, call the code again, this time between the */
- /* intersection point and the updated new co-ordinates */
- /* Bail out if we've done the calculation 10 times - this seems ok */
- /* for most scenes I've tested */
- while (finish_defs) {
- deflected = pdDoDeflection(rng, opco, npco, opno, npno, life, new_force,
- def_count, cur_time, ob->lay,
- &last_ob, &last_fc, &same_fc);
- if (deflected) {
- def_count = def_count + 1;
- deflection = 1;
- if (def_count==10) finish_defs = 0;
- }
- else {
- finish_defs = 0;
- }
- }
-
- /* Only update the particle positions and speed if we had a deflection */
- if (deflection) {
- pa->co[0] = npco[0];
- pa->co[1] = npco[1];
- pa->co[2] = npco[2];
- pa->no[0] = npno[0];
- pa->no[1] = npno[1];
- pa->no[2] = npno[2];
- }
- }
-
- /* speed: texture */
- if(mtex && paf->texfac!=0.0) {
- particle_tex(mtex, paf, pa->co, pa->no);
- }
- if(damp!=1.0) {
- pa->no[0]*= damp;
- pa->no[1]*= damp;
- pa->no[2]*= damp;
- }
-
- opa= pa;
- pa++;
- /* opa is used later on too! */
+ fac= (fac-mindist)/(maxdist-mindist);
+ return 1.0f - (float)pow((double)fac, (double)power);
}
+ else
+ return pow((double)1.0f+fac-mindist, (double)-power);
+}
- if(deform) {
- /* deform all keys */
- pa= part;
- b= paf->totkey;
- while(b--) {
- calc_latt_deform(pa->co, 1.0f);
- pa++;
- }
- }
-
- /* the big multiplication */
- if(depth<PAF_MAXMULT && paf->mult[depth]!=0.0) {
-
- /* new 'child' emerges from an average 'mult' part from
- the particles */
- damp = (float)nr;
- rt1= (int)(damp*paf->mult[depth]);
- rt2= (int)((damp+1.0)*paf->mult[depth]);
- if(rt1!=rt2) {
-
- for(b=0; b<paf->child[depth]; b++) {
- pa= new_particle(paf);
- *pa= *opa;
- pa->lifetime= paf->life[depth];
- if(paf->randlife!=0.0) {
- pa->lifetime*= 1.0f + paf->randlife*(rng_getFloat(rng) - 0.5f);
- }
- pa->mat_nr= paf->mat[depth];
+static float falloff_func_dist(PartDeflect *pd, float fac)
+{
+ return falloff_func(fac, pd->flag&PFIELD_USEMIN, pd->mindist, pd->flag&PFIELD_USEMAX, pd->maxdist, pd->f_power);
+}
- make_particle_keys(rng, ob, depth+1, b, paf, pa, force, deform, mtex, effectorbase);
- }
- }
- }
+static float falloff_func_rad(PartDeflect *pd, float fac)
+{
+ return falloff_func(fac, pd->flag&PFIELD_USEMINR, pd->minrad, pd->flag&PFIELD_USEMAXR, pd->maxrad, pd->f_power_r);
}
-static void init_mv_jit(float *jit, int num, int seed2)
+float effector_falloff(PartDeflect *pd, float *eff_velocity, float *vec_to_part)
{
- RNG *rng;
- float *jit2, x, rad1, rad2, rad3;
- int i, num2;
+ float eff_dir[3], temp[3];
+ float falloff=1.0, fac, r_fac;
+
+ if(pd->forcefield==PFIELD_LENNARDJ)
+ return falloff; /* Lennard-Jones field has it's own falloff built in */
+
+ VecCopyf(eff_dir,eff_velocity);
+ Normalize(eff_dir);
+
+ if(pd->flag & PFIELD_POSZ && Inpf(eff_dir,vec_to_part)<0.0f)
+ falloff=0.0f;
+ else switch(pd->falloff){
+ case PFIELD_FALL_SPHERE:
+ fac=VecLength(vec_to_part);
+ falloff= falloff_func_dist(pd, fac);
+ break;
+
+ case PFIELD_FALL_TUBE:
+ fac=Inpf(vec_to_part,eff_dir);
+ falloff= falloff_func_dist(pd, ABS(fac));
+ if(falloff == 0.0f)
+ break;
- if(num==0) return;
+ VECADDFAC(temp,vec_to_part,eff_dir,-fac);
+ r_fac=VecLength(temp);
+ falloff*= falloff_func_rad(pd, r_fac);
+ break;
+ case PFIELD_FALL_CONE:
+ fac=Inpf(vec_to_part,eff_dir);
+ falloff= falloff_func_dist(pd, ABS(fac));
+ if(falloff == 0.0f)
+ break;
- rad1= (float)(1.0/sqrt((float)num));
- rad2= (float)(1.0/((float)num));
- rad3= (float)sqrt((float)num)/((float)num);
+ r_fac=saacos(fac/VecLength(vec_to_part))*180.0f/(float)M_PI;
+ falloff*= falloff_func_rad(pd, r_fac);
- rng = rng_new(31415926 + num + seed2);
- x= 0;
- num2 = 2 * num;
- for(i=0; i<num2; i+=2) {
-
- jit[i]= x + rad1*(0.5f - rng_getFloat(rng));
- jit[i+1]= i/(2.0f*num) + rad1*(0.5f - rng_getFloat(rng));
-
- jit[i]-= (float)floor(jit[i]);
- jit[i+1]-= (float)floor(jit[i+1]);
-
- x+= rad3;
- x -= (float)floor(x);
+ break;
}
- jit2= MEM_mallocN(12 + 2*sizeof(float)*num, "initjit");
-
- for (i=0 ; i<4 ; i++) {
- BLI_jitterate1(jit, jit2, num, rad1);
- BLI_jitterate1(jit, jit2, num, rad1);
- BLI_jitterate2(jit, jit2, num, rad2);
- }
- MEM_freeN(jit2);
- rng_free(rng);
+ return falloff;
}
-#define JIT_RAND 32
-
-/* for a position within a face, tot is total amount of faces */
-static void give_mesh_particle_coord(PartEff *paf, VeNoCo *noco, MFace *mface, int partnr, int subnr, float *co, float *no)
+void do_physical_effector(Object *ob, float *opco, short type, float force_val, float distance, float falloff, float size, float damp, float *eff_velocity, float *vec_to_part, float *velocity, float *field, int planar, struct RNG *rng, float noise_factor, float charge, float pa_size)
{
- static float *jit= NULL;
- static float *trands= NULL;
- static int jitlevel= 1;
- float *v1, *v2, *v3, *v4;
- float u, v;
- float *n1, *n2, *n3, *n4;
-
- /* free signal */
- if(paf==NULL) {
- if(jit) MEM_freeN(jit);
- jit= NULL;
- if(trands) MEM_freeN(trands);
- trands= NULL;
+ float mag_vec[3]={0,0,0};
+ float temp[3], temp2[3];
+ float eff_vel[3];
+ float noise = 0, visibility;
+
+ // calculate visibility
+ visibility = eff_calc_visibility(ob, opco, vec_to_part);
+ if(visibility <= 0.0)
return;
- }
-
- /* first time initialize jitter or trand, partnr then is total amount of particles, subnr total amount of faces */
- if(trands==NULL && jit==NULL) {
- RNG *rng = rng_new(31415926 + paf->seed);
- int i, tot;
-
- if(paf->flag & PAF_TRAND)
- tot= partnr;
- else
- tot= JIT_RAND; /* arbitrary... allows JIT_RAND times more particles in a face for jittered distro */
-
- trands= MEM_callocN(2+2*tot*sizeof(float), "trands");
- for(i=0; i<tot; i++) {
- trands[2*i]= rng_getFloat(rng);
- trands[2*i+1]= rng_getFloat(rng);
- }
- rng_free(rng);
+ falloff *= visibility;
- if((paf->flag & PAF_TRAND)==0) {
- jitlevel= paf->userjit;
+ VecCopyf(eff_vel,eff_velocity);
+ Normalize(eff_vel);
+
+ switch(type){
+ case PFIELD_WIND:
+ VECCOPY(mag_vec,eff_vel);
- if(jitlevel == 0) {
- jitlevel= partnr/subnr;
- if(paf->flag & PAF_EDISTR) jitlevel*= 2; /* looks better in general, not very scietific */
- if(jitlevel<3) jitlevel= 3;
- if(jitlevel>100) jitlevel= 100;
- }
+ // add wind noise here, only if we have wind
+ if((noise_factor > 0.0f) && (force_val > FLT_EPSILON))
+ noise = wind_func(rng, noise_factor);
- jit= MEM_callocN(2+ jitlevel*2*sizeof(float), "jit");
- init_mv_jit(jit, jitlevel, paf->seed);
- BLI_array_randomize(jit, 2*sizeof(float), jitlevel, paf->seed); /* for custom jit or even distribution */
- }
- return;
- }
-
- if(paf->flag & PAF_TRAND) {
- u= trands[2*partnr];
- v= trands[2*partnr+1];
- }
- else {
- /* jittered distribution gets fixed random offset */
- if(subnr>=jitlevel) {
- int jitrand= (subnr/jitlevel) % JIT_RAND;
-
- subnr %= jitlevel;
- u= jit[2*subnr] + trands[2*jitrand];
- v= jit[2*subnr+1] + trands[2*jitrand+1];
- if(u > 1.0f) u-= 1.0f;
- if(v > 1.0f) v-= 1.0f;
- }
- else {
- u= jit[2*subnr];
- v= jit[2*subnr+1];
- }
- }
-
- v1= (noco+(mface->v1))->co;
- v2= (noco+(mface->v2))->co;
- v3= (noco+(mface->v3))->co;
- n1= (noco+(mface->v1))->no;
- n2= (noco+(mface->v2))->no;
- n3= (noco+(mface->v3))->no;
-
- if(mface->v4) {
- float uv= u*v;
- float muv= (1.0f-u)*(v);
- float umv= (u)*(1.0f-v);
- float mumv= (1.0f-u)*(1.0f-v);
-
- v4= (noco+(mface->v4))->co;
- n4= (noco+(mface->v4))->no;
-
- co[0]= mumv*v1[0] + muv*v2[0] + uv*v3[0] + umv*v4[0];
- co[1]= mumv*v1[1] + muv*v2[1] + uv*v3[1] + umv*v4[1];
- co[2]= mumv*v1[2] + muv*v2[2] + uv*v3[2] + umv*v4[2];
+ VecMulf(mag_vec,(force_val+noise)*falloff);
+ VecAddf(field,field,mag_vec);
+ break;
- no[0]= mumv*n1[0] + muv*n2[0] + uv*n3[0] + umv*n4[0];
- no[1]= mumv*n1[1] + muv*n2[1] + uv*n3[1] + umv*n4[1];
- no[2]= mumv*n1[2] + muv*n2[2] + uv*n3[2] + umv*n4[2];
- }
- else {
- /* mirror triangle uv coordinates when on other side */
- if(u + v > 1.0f) {
- u= 1.0f-u;
- v= 1.0f-v;
- }
- co[0]= v1[0] + u*(v3[0]-v1[0]) + v*(v2[0]-v1[0]);
- co[1]= v1[1] + u*(v3[1]-v1[1]) + v*(v2[1]-v1[1]);
- co[2]= v1[2] + u*(v3[2]-v1[2]) + v*(v2[2]-v1[2]);
-
- no[0]= n1[0] + u*(n3[0]-n1[0]) + v*(n2[0]-n1[0]);
- no[1]= n1[1] + u*(n3[1]-n1[1]) + v*(n2[1]-n1[1]);
- no[2]= n1[2] + u*(n3[2]-n1[2]) + v*(n2[2]-n1[2]);
- }
-}
+ case PFIELD_FORCE:
+ if(planar)
+ Projf(mag_vec,vec_to_part,eff_vel);
+ else
+ VecCopyf(mag_vec,vec_to_part);
+ Normalize(mag_vec);
-/* Gets a MDeformVert's weight in group (0 if not in group) */
-/* note; this call could be in mesh.c or deform.c, but OK... it's in armature.c too! (ton) */
-static float vert_weight(MDeformVert *dvert, int group)
-{
- MDeformWeight *dw;
- int i;
-
- if(dvert) {
- dw= dvert->dw;
- for(i= dvert->totweight; i>0; i--, dw++) {
- if(dw->def_nr == group) return dw->weight;
- if(i==1) break; /*otherwise dw will point to somewhere it shouldn't*/
- }
- }
- return 0.0;
-}
+ VecMulf(mag_vec,force_val*falloff);
+ VecAddf(field,field,mag_vec);
+ break;
-/* Gets a faces average weight in a group, helper for below, face and weights are always set */
-static float face_weight(MFace *face, float *weights)
-{
- float tweight;
-
- tweight = weights[face->v1] + weights[face->v2] + weights[face->v3];
-
- if(face->v4) {
- tweight += weights[face->v4];
- tweight /= 4.0;
- }
- else {
- tweight /= 3.0;
- }
+ case PFIELD_VORTEX:
+ Crossf(mag_vec,eff_vel,vec_to_part);
- return tweight;
-}
+ Normalize(mag_vec);
-/* helper function for build_particle_system() */
-static void make_weight_tables(PartEff *paf, Mesh *me, int totpart, VeNoCo *vertlist, int totvert, MFace *facelist, int totface, float **vweights, float **fweights)
-{
- MFace *mface;
- float *foweights=NULL, *voweights=NULL;
- float totvweight=0.0f, totfweight=0.0f;
- int a;
-
- if((paf->flag & PAF_FACE)==0) totface= 0;
-
- /* collect emitting vertices & faces if vert groups used */
- if(paf->vertgroup && me->dvert) {
-
- /* allocate weights array for all vertices, also for lookup of faces later on. note it's a malloc */
- *vweights= voweights= MEM_mallocN( totvert*sizeof(float), "pafvoweights" );
- totvweight= 0.0f;
- for(a=0; a<totvert; a++) {
- voweights[a]= vert_weight(me->dvert+a, paf->vertgroup-1);
- totvweight+= voweights[a];
- }
-
- if(totface) {
- /* allocate weights array for faces, note it's a malloc */
- *fweights= foweights= MEM_mallocN(totface*sizeof(float), "paffoweights" );
- for(a=0, mface=facelist; a<totface; a++, mface++) {
- foweights[a] = face_weight(mface, voweights);
- }
- }
- }
-
- /* make weights for faces or for even area distribution */
- if(totface && (paf->flag & PAF_EDISTR)) {
- float maxfarea= 0.0f, curfarea;
-
- /* two cases for area distro, second case we already have group weights */
- if(foweights==NULL) {
- /* allocate weights array for faces, note it's a malloc */
- *fweights= foweights= MEM_mallocN(totface*sizeof(float), "paffoweights" );
-
- for(a=0, mface=facelist; a<totface; a++, mface++) {
- if (mface->v4)
- curfarea= AreaQ3Dfl(vertlist[mface->v1].co, vertlist[mface->v2].co, vertlist[mface->v3].co, vertlist[mface->v4].co);
- else
- curfarea= AreaT3Dfl(vertlist[mface->v1].co, vertlist[mface->v2].co, vertlist[mface->v3].co);
- if(curfarea>maxfarea)
- maxfarea = curfarea;
- foweights[a]= curfarea;
- }
- }
- else {
- for(a=0, mface=facelist; a<totface; a++, mface++) {
- if(foweights[a]!=0.0f) {
- if (mface->v4)
- curfarea= AreaQ3Dfl(vertlist[mface->v1].co, vertlist[mface->v2].co, vertlist[mface->v3].co, vertlist[mface->v4].co);
- else
- curfarea= AreaT3Dfl(vertlist[mface->v1].co, vertlist[mface->v2].co, vertlist[mface->v3].co);
- if(curfarea>maxfarea)
- maxfarea = curfarea;
- foweights[a]*= curfarea;
- }
- }
- }
-
- /* normalize weights for max face area, calculate tot */
- if(maxfarea!=0.0f) {
- maxfarea= 1.0f/maxfarea;
- for(a=0; a< totface; a++) {
- if(foweights[a]!=0.0) {
- foweights[a] *= maxfarea;
- totfweight+= foweights[a];
- }
- }
- }
- }
- else if(foweights) {
- /* only add totfweight value */
- for(a=0; a< totface; a++) {
- if(foweights[a]!=0.0) {
- totfweight+= foweights[a];
- }
- }
- }
-
- /* if weight arrays, we turn these arrays into the amount of particles */
- if(totvert && voweights) {
- float mult= (float)totpart/totvweight;
-
- for(a=0; a< totvert; a++) {
- if(voweights[a]!=0.0)
- voweights[a] *= mult;
- }
- }
-
- if(totface && foweights) {
- float mult= (float)totpart/totfweight;
-
- for(a=0; a< totface; a++) {
- if(foweights[a]!=0.0)
- foweights[a] *= mult;
- }
- }
-}
+ VecMulf(mag_vec,force_val*distance*falloff);
+ VecAddf(field,field,mag_vec);
-/* helper function for build_particle_system() */
-static void make_length_tables(PartEff *paf, Mesh *me, int totvert, MFace *facelist, int totface, float **vlengths, float **flengths)
-{
- MFace *mface;
- float *folengths=NULL, *volengths=NULL;
- int a;
-
- if((paf->flag & PAF_FACE)==0) totface= 0;
-
- /* collect emitting vertices & faces if vert groups used */
- if(paf->vertgroup_v && me->dvert) {
-
- /* allocate lengths array for all vertices, also for lookup of faces later on. note it's a malloc */
- *vlengths= volengths= MEM_mallocN( totvert*sizeof(float), "pafvolengths" );
- for(a=0; a<totvert; a++) {
- volengths[a]= vert_weight(me->dvert+a, paf->vertgroup_v-1);
- }
-
- if(totface) {
- /* allocate lengths array for faces, note it's a malloc */
- *flengths= folengths= MEM_mallocN(totface*sizeof(float), "paffolengths" );
- for(a=0, mface=facelist; a<totface; a++, mface++) {
- folengths[a] = face_weight(mface, volengths);
- }
- }
- }
-}
+ break;
+ case PFIELD_MAGNET:
+ if(planar)
+ VecCopyf(temp,eff_vel);
+ else
+ /* magnetic field of a moving charge */
+ Crossf(temp,eff_vel,vec_to_part);
+ Normalize(temp);
-/* for paf start to end, store all matrices for objects */
-typedef struct pMatrixCache {
- float obmat[4][4];
- float imat[3][3];
-} pMatrixCache;
+ Crossf(temp2,velocity,temp);
+ VecAddf(mag_vec,mag_vec,temp2);
+ VecMulf(mag_vec,force_val*falloff);
+ VecAddf(field,field,mag_vec);
+ break;
+ case PFIELD_HARMONIC:
+ if(planar)
+ Projf(mag_vec,vec_to_part,eff_vel);
+ else
+ VecCopyf(mag_vec,vec_to_part);
-/* WARN: this function stores data in ob->id.idnew! */
-/* error: this function changes ob->recalc of other objects... */
-static pMatrixCache *cache_object_matrices(Object *ob, int start, int end)
-{
- pMatrixCache *mcache, *mc;
- Group *group= NULL;
- Object *obcopy;
- Base *base;
- float framelenold, cfrao, sfo;
-
- /* object can be linked in group... stupid exception */
- if(NULL==object_in_scene(ob, G.scene))
- group= find_group(ob);
-
- mcache= mc= MEM_mallocN( (end-start+1)*sizeof(pMatrixCache), "ob matrix cache");
-
- framelenold= G.scene->r.framelen;
- G.scene->r.framelen= 1.0f;
- cfrao= G.scene->r.cfra;
- sfo= ob->sf;
- ob->sf= 0.0f;
-
- /* clear storage, copy recalc tag (bad loop) */
- for(obcopy= G.main->object.first; obcopy; obcopy= obcopy->id.next) {
- obcopy->id.newid= NULL;
- obcopy->recalco= obcopy->recalc;
- obcopy->recalc= 0;
- }
-
- /* all objects get tagged recalc that influence this object (does group too) */
- /* note that recalco has the real recalc tags, set by callers of this function */
- ob->recalc |= OB_RECALC_OB; /* make sure a recalc gets flushed */
- DAG_object_update_flags(G.scene, ob, -1);
-
- for(G.scene->r.cfra= start; G.scene->r.cfra<=end; G.scene->r.cfra++, mc++) {
-
- if(group) {
- GroupObject *go;
-
- for(go= group->gobject.first; go; go= go->next) {
- if(go->ob->recalc) {
- where_is_object(go->ob);
-
- do_ob_key(go->ob);
- if(go->ob->type==OB_ARMATURE) {
- do_all_pose_actions(go->ob); // only does this object actions
- where_is_pose(go->ob);
- }
- }
- }
- }
- else {
- for(base= G.scene->base.first; base; base= base->next) {
- if(base->object->recalc) {
- if(base->object->id.newid==NULL)
- base->object->id.newid= MEM_dupallocN(base->object);
-
- where_is_object(base->object);
-
- do_ob_key(base->object);
- if(base->object->type==OB_ARMATURE) {
- do_all_pose_actions(base->object); // only does this object actions
- where_is_pose(base->object);
- }
- }
- }
- }
- Mat4CpyMat4(mc->obmat, ob->obmat);
- Mat4Invert(ob->imat, ob->obmat);
- Mat3CpyMat4(mc->imat, ob->imat);
- Mat3Transp(mc->imat);
- }
-
- /* restore */
- G.scene->r.cfra= cfrao;
- G.scene->r.framelen= framelenold;
- ob->sf= sfo;
-
- if(group) {
- GroupObject *go;
-
- for(go= group->gobject.first; go; go= go->next) {
- if(go->ob->recalc) {
- where_is_object(go->ob);
-
- do_ob_key(go->ob);
- if(go->ob->type==OB_ARMATURE) {
- do_all_pose_actions(go->ob); // only does this object actions
- where_is_pose(go->ob);
- }
- }
- }
- }
- else {
- for(base= G.scene->base.first; base; base= base->next) {
- if(base->object->recalc) {
-
- if(base->object->id.newid) {
- obcopy= (Object *)base->object->id.newid;
- *(base->object) = *(obcopy);
- MEM_freeN(obcopy);
- base->object->id.newid= NULL;
- }
-
- do_ob_key(base->object);
- if(base->object->type==OB_ARMATURE) {
- do_all_pose_actions(base->object); // only does this object actions
- where_is_pose(base->object);
- }
- }
- }
- }
-
- /* copy recalc tag (bad loop) */
- for(obcopy= G.main->object.first; obcopy; obcopy= obcopy->id.next)
- obcopy->recalc= obcopy->recalco;
-
- return mcache;
-}
+ Normalize(mag_vec);
-/* for fluidsim win32 debug messages */
-#if defined(WIN32) && (!(defined snprintf))
-#define snprintf _snprintf
-#endif
+ VecMulf(mag_vec,force_val*falloff);
+ VecSubf(field,field,mag_vec);
-/* main particle building function
- one day particles should become dynamic (realtime) with the current method as a 'bake' (ton) */
-void build_particle_system(Object *ob)
-{
- RNG *rng;
- PartEff *paf;
- Particle *pa;
- Mesh *me;
- Base *base;
- MTex *mtexmove=0, *mtextime=0;
- Material *ma;
- MFace *facelist= NULL;
- pMatrixCache *mcache=NULL, *mcnow, *mcprev;
- ListBase *effectorbase;
- VeNoCo *vertexcosnos;
- double startseconds= PIL_check_seconds_timer();
- float ftime, dtime, force[3], vec[3], fac, co[3], no[3];
- float *voweights= NULL, *foweights= NULL, maxw=1.0f;
- float *volengths= NULL, *folengths= NULL;
- int deform=0, a, totpart, paf_sta, paf_end;
- int waitcursor_set= 0, totvert, totface, curface, curvert;
-#ifndef DISABLE_ELBEEM
- int readMask, activeParts, fileParts;
-#endif
-
- /* return conditions */
- if(ob->type!=OB_MESH) return;
- me= ob->data;
+ VecCopyf(mag_vec,velocity);
+ /* 1.9 is an experimental value to get critical damping at damp=1.0 */
+ VecMulf(mag_vec,damp*1.9f*(float)sqrt(force_val));
+ VecSubf(field,field,mag_vec);
+ break;
+ case PFIELD_CHARGE:
+ if(planar)
+ Projf(mag_vec,vec_to_part,eff_vel);
+ else
+ VecCopyf(mag_vec,vec_to_part);
- paf= give_parteff(ob);
- if(paf==NULL) return;
-
- if(G.rendering==0 && paf->disp==0) return;
-
- if(paf->keys) MEM_freeN(paf->keys); /* free as early as possible, for returns */
- paf->keys= NULL;
-
- //printf("build particles\n");
-
- /* fluid sim particle import handling, actual loading of particles from file */
- #ifndef DISABLE_ELBEEM
- if( (1) && (ob->fluidsimFlag & OB_FLUIDSIM_ENABLE) && // broken, disabled for now!
- (ob->fluidsimSettings) &&
- (ob->fluidsimSettings->type == OB_FLUIDSIM_PARTICLE)) {
- char *suffix = "fluidsurface_particles_#";
- char *suffix2 = ".gz";
- char filename[256];
- char debugStrBuffer[256];
- int curFrame = G.scene->r.cfra -1; // warning - sync with derived mesh fsmesh loading
- int j, numFileParts;
- gzFile gzf;
- float vel[3];
-
- if(ob==G.obedit) { // off...
- paf->totpart = 0; // 1 or 0?
- return;
- }
+ Normalize(mag_vec);
- // ok, start loading
- strcpy(filename, ob->fluidsimSettings->surfdataPath);
- strcat(filename, suffix);
- BLI_convertstringcode(filename, G.sce, curFrame); // fixed #frame-no
- strcat(filename, suffix2);
-
- gzf = gzopen(filename, "rb");
- if (!gzf) {
- snprintf(debugStrBuffer,256,"readFsPartData::error - Unable to open file for reading '%s' \n", filename);
- //elbeemDebugOut(debugStrBuffer);
- paf->totpart = 0;
- return;
- }
+ VecMulf(mag_vec,charge*force_val*falloff);
+ VecAddf(field,field,mag_vec);
+ break;
+ case PFIELD_LENNARDJ:
+ {
+ float fac;
- gzread(gzf, &totpart, sizeof(totpart));
- numFileParts = totpart;
- totpart = (G.rendering)?totpart:(paf->disp*totpart)/100;
- paf->totpart= totpart;
- paf->totkey= 1;
- /* initialize particles */
- new_particle(paf);
- ftime = 0.0; // unused...
-
- // set up reading mask
- readMask = ob->fluidsimSettings->typeFlags;
- activeParts=0;
- fileParts=0;
-
- for(a=0; a<totpart; a++) {
- int ptype=0;
- short shsize=0;
- float convertSize=0.0;
- gzread(gzf, &ptype, sizeof( ptype ));
- if(ptype&readMask) {
- activeParts++;
- pa= new_particle(paf);
- pa->time= ftime;
- pa->lifetime= ftime + 10000.; // add large number to make sure they are displayed, G.scene->r.efra +1.0;
- pa->co[0] = 0.0;
- pa->co[1] =
- pa->co[2] = 1.0*(float)a / (float)totpart;
- pa->no[0] = pa->no[1] = pa->no[2] = 0.0;
- pa->mat_nr= paf->omat;
- gzread(gzf, &convertSize, sizeof( float ));
- // convert range of 1.0-10.0 to shorts 1000-10000)
- shsize = (short)(convertSize*1000.0);
- pa->rt = shsize;
-
- for(j=0; j<3; j++) {
- float wrf;
- gzread(gzf, &wrf, sizeof( wrf ));
- pa->co[j] = wrf;
- //fprintf(stderr,"Rj%d ",j);
- }
- for(j=0; j<3; j++) {
- float wrf;
- gzread(gzf, &wrf, sizeof( wrf ));
- vel[j] = wrf;
- }
- //if(a<25) fprintf(stderr,"FSPARTICLE debug set %s , a%d = %f,%f,%f , life=%f \n", filename, a, pa->co[0],pa->co[1],pa->co[2], pa->lifetime );
- } else {
- // skip...
- for(j=0; j<2*3+1; j++) {
- float wrf; gzread(gzf, &wrf, sizeof( wrf ));
- }
+ if(planar) {
+ Projf(mag_vec,vec_to_part,eff_vel);
+ distance = VecLength(mag_vec);
}
- fileParts++;
- }
- gzclose( gzf );
-
- totpart = paf->totpart = activeParts;
- snprintf(debugStrBuffer,256,"readFsPartData::done - particles:%d, active:%d, file:%d, mask:%d \n", paf->totpart,activeParts,fileParts,readMask);
- elbeemDebugOut(debugStrBuffer);
- return;
- } // fluid sim particles done
- #endif // DISABLE_ELBEEM
-
- if(paf->end < paf->sta) return;
-
- if( (paf->flag & PAF_OFACE) && (paf->flag & PAF_FACE)==0) return;
-
- if(me->totvert==0) return;
-
- if(ob==G.obedit) return;
- totpart= (G.rendering)?paf->totpart:(paf->disp*paf->totpart)/100;
- if(totpart==0) return;
-
- /* No returns after this line! */
-
- /* material */
- ma= give_current_material(ob, paf->omat);
- if(ma) {
- if(paf->speedtex)
- mtexmove= ma->mtex[paf->speedtex-1];
- mtextime= ma->mtex[paf->timetex-1];
- }
+ else
+ VecCopyf(mag_vec,vec_to_part);
- disable_speed_curve(1); /* check this... */
+ /* at this distance the field is 60 times weaker than maximum */
+ if(distance > 2.22 * (size+pa_size))
+ break;
- /* initialize particles */
- new_particle(paf);
+ fac = pow((size+pa_size)/distance,6.0);
+
+ fac = - fac * (1.0 - fac) / distance;
- /* reset deflector cache, sumohandle is free, but its still sorta abuse... (ton) */
- for(base= G.scene->base.first; base; base= base->next)
- base->object->sumohandle= NULL;
+ /* limit the repulsive term drastically to avoid huge forces */
+ fac = ((fac>2.0) ? 2.0 : fac);
- /* all object positions from start to end */
- paf_sta= (int)floor(paf->sta);
- paf_end= (int)ceil(paf->end);
- if((paf->flag & PAF_STATIC)==0)
- mcache= cache_object_matrices(ob, paf_sta, paf_end);
-
- /* mult generations? */
- for(a=0; a<PAF_MAXMULT; a++) {
- if(paf->mult[a]!=0.0) {
- /* interesting formula! this way after 'x' generations the total is paf->totpart */
- totpart= (int)(totpart / (1.0+paf->mult[a]*paf->child[a]));
+ /* 0.003715 is the fac value at 2.22 times (size+pa_size),
+ substracted to avoid discontinuity at the border
+ */
+ VecMulf(mag_vec, force_val * (fac-0.0037315));
+ VecAddf(field,field,mag_vec);
+ break;
}
- else break;
}
+}
- /* for static particles, calculate system on current frame (? ton) */
- if(ma) do_mat_ipo(ma);
-
- /* matrix invert for static too */
- Mat4Invert(ob->imat, ob->obmat);
- Mat4CpyMat4(paf->imat, ob->imat); /* used for duplicators */
-
- /* new random generator */
- rng = rng_new(paf->seed);
-
- /* otherwise it goes way too fast */
- force[0]= paf->force[0]*0.05f;
- force[1]= paf->force[1]*0.05f;
- force[2]= paf->force[2]*0.05f;
-
- if( paf->flag & PAF_STATIC ) deform= 0;
- else {
- Object *parlatt= modifiers_isDeformedByLattice(ob);
- if(parlatt) {
- deform= 1;
- init_latt_deform(parlatt, 0);
- }
- }
-
- /* get the effectors */
- effectorbase= pdInitEffectors(ob, paf->group);
-
- /* init geometry, return is 6 x float * me->totvert in size */
- vertexcosnos= (VeNoCo *)mesh_get_mapped_verts_nors(ob);
- facelist= me->mface;
- totvert= me->totvert;
- totface= me->totface;
-
- /* if vertexweights or even distribution, it makes weight tables, also checks where it emits from */
- make_weight_tables(paf, me, totpart, vertexcosnos, totvert, facelist, totface, &voweights, &foweights);
-
- /* vertexweights can define lengths too */
- make_length_tables(paf, me, totvert, facelist, totface, &volengths, &folengths);
-
- /* now define where to emit from, if there are face weights we skip vertices */
- if(paf->flag & PAF_OFACE) totvert= 0;
- if((paf->flag & PAF_FACE)==0) totface= 0;
- if(foweights) totvert= 0;
-
- /* initialize give_mesh_particle_coord */
- if(totface)
- give_mesh_particle_coord(paf, vertexcosnos, facelist, totpart, totface, NULL, NULL);
-
- /* correction for face timing when using weighted average */
- if(totface && foweights) {
- maxw= (paf->end-paf->sta)/foweights[0];
- }
- else if(totvert && voweights) {
- maxw= (paf->end-paf->sta)/voweights[0];
- }
-
- /* for loop below */
- if (paf->flag & PAF_STATIC) {
- ftime = G.scene->r.cfra;
- dtime= 0.0f;
- } else {
- ftime= paf->sta;
- dtime= (paf->end - paf->sta)/(float)totpart;
- }
-
- curface= curvert= 0;
- for(a=0; a<totpart; a++, ftime+=dtime) {
-
- /* we set waitcursor only when a half second expired, particles now are realtime updated */
- if(waitcursor_set==0 && (a % 256)==255) {
- double seconds= PIL_check_seconds_timer();
- if(seconds - startseconds > 0.5) {
- //XXX waitcursor(1);
- waitcursor_set= 1;
- }
- }
-
- pa= new_particle(paf);
- pa->time= ftime;
+/* -------- pdDoEffectors() --------
+ generic force/speed system, now used for particles and softbodies
+ lb = listbase with objects that take part in effecting
+ opco = global coord, as input
+ force = force accumulator
+ speed = actual current speed which can be altered
+ cur_time = "external" time in frames, is constant for static particles
+ loc_time = "local" time in frames, range <0-1> for the lifetime of particle
+ par_layer = layer the caller is in
+ flags = only used for softbody wind now
+ guide = old speed of particle
- /* get coordinates from faces, only when vertices set to zero */
- if(totvert==0 && totface) {
- int curjit;
-
- /* use weight table, we have to do faces in order to be able to use jitter table... */
- if(foweights) {
-
- if(foweights[curface] < 1.0f) {
- float remainder= 0.0f;
-
- while(remainder + foweights[curface] < 1.0f && curface<totface-1) {
- remainder += foweights[curface];
- curface++;
- }
- /* if this is the last face, the foweights[] can be zero, so we don't add a particle extra */
- if(curface!=totface-1)
- foweights[curface] += remainder;
-
- maxw= (paf->end-paf->sta)/foweights[curface];
- }
+*/
+void pdDoEffectors(ListBase *lb, float *opco, float *force, float *speed, float cur_time, float loc_time, unsigned int flags)
+{
+/*
+ Modifies the force on a particle according to its
+ relation with the effector object
+ Different kind of effectors include:
+ Forcefields: Gravity-like attractor
+ (force power is related to the inverse of distance to the power of a falloff value)
+ Vortex fields: swirling effectors
+ (particles rotate around Z-axis of the object. otherwise, same relation as)
+ (Forcefields, but this is not done through a force/acceleration)
+ Guide: particles on a path
+ (particles are guided along a curve bezier or old nurbs)
+ (is independent of other effectors)
+*/
+ Object *ob;
+ pEffectorCache *ec;
+ PartDeflect *pd;
+
+ float distance, vec_to_part[3];
+ float falloff;
- if(foweights[curface]==0.0f)
- break; /* WARN skips here out of particle generating */
- else {
- if(foweights[curface] >= 1.0f) /* note the >= here, this because of the < 1.0f above, it otherwise will stick to 1 face forever */
- foweights[curface] -= 1.0f;
-
- curjit= (int) foweights[curface];
- give_mesh_particle_coord(paf, vertexcosnos, facelist+curface, a, curjit, co, no);
-
- /* time correction to make particles appear evenly, maxw does interframe (0-1) */
- pa->time= paf->sta + maxw*foweights[curface];
- }
- }
- else {
- curface= a % totface;
- curjit= a/totface;
- give_mesh_particle_coord(paf, vertexcosnos, facelist+curface, a, curjit, co, no);
- }
- }
- /* get coordinates from vertices */
- if(totvert) {
- /* use weight table */
- if(voweights) {
-
- if(voweights[curvert] < 1.0f) {
- float remainder= 0.0f;
-
- while(remainder + voweights[curvert] < 1.0f && curvert<totvert-1) {
- remainder += voweights[curvert];
- curvert++;
- }
- voweights[curvert] += remainder;
- maxw= (paf->end-paf->sta)/voweights[curvert];
- }
-
- if(voweights[curvert]==0.0f)
- break; /* WARN skips here out of particle generating */
- else {
- if(voweights[curvert] > 1.0f)
- voweights[curvert] -= 1.0f;
-
- /* time correction to make particles appear evenly */
- pa->time= paf->sta + maxw*voweights[curvert];
- }
- }
- else {
- curvert= a % totvert;
- if(a >= totvert && totface)
- totvert= 0;
- }
+ /* Cycle through collected objects, get total of (1/(gravity_strength * dist^gravity_power)) */
+ /* Check for min distance here? (yes would be cool to add that, ton) */
+
+ for(ec = lb->first; ec; ec= ec->next) {
+ /* object effectors were fully checked to be OK to evaluate! */
+ ob= ec->ob;
+ pd= ob->pd;
- VECCOPY(co, vertexcosnos[curvert].co);
- VECCOPY(no, vertexcosnos[curvert].no);
- }
-
- VECCOPY(pa->co, co);
-
- /* dynamic options */
- if((paf->flag & PAF_STATIC)==0) {
- int cur;
+ /* Get IPO force strength and fall off values here */
+ where_is_object_time(ob,cur_time);
- /* particle retiming with texture */
- if(mtextime && (paf->flag2 & PAF_TEXTIME)) {
- float tin, tr, tg, tb, ta, orco[3];
-
- /* calculate normalized orco */
- orco[0] = (co[0]-me->loc[0])/me->size[0];
- orco[1] = (co[1]-me->loc[1])/me->size[1];
- orco[2] = (co[2]-me->loc[2])/me->size[2];
- externtex(mtextime, orco, &tin, &tr, &tg, &tb, &ta);
-
- if(paf->flag2neg & PAF_TEXTIME)
- pa->time = paf->sta + (paf->end - paf->sta)*tin;
- else
- pa->time = paf->sta + (paf->end - paf->sta)*(1.0f-tin);
- }
+ /* use center of object for distance calculus */
+ VecSubf(vec_to_part, opco, ob->obmat[3]);
+ distance = VecLength(vec_to_part);
- /* set ob at correct time, we use cached matrices */
- cur= (int)floor(pa->time) + 1 ; /* + 1 has a reason: (obmat/prevobmat) otherwise comet-tails start too late */
-
- if(cur <= paf_end) mcnow= mcache + cur - paf_sta;
- else mcnow= mcache + paf_end - paf_sta;
-
- if(cur > paf_sta) mcprev= mcnow-1;
- else mcprev= mcache;
-
- /* move to global space */
- Mat4MulVecfl(mcnow->obmat, pa->co);
+ falloff=effector_falloff(pd,ob->obmat[2],vec_to_part);
- VECCOPY(vec, co);
- Mat4MulVecfl(mcprev->obmat, vec);
-
- /* first start speed: object */
- VECSUB(pa->no, pa->co, vec);
-
- VecMulf(pa->no, paf->obfac);
-
- /* calculate the correct inter-frame */
- fac= (pa->time- (float)floor(pa->time));
- pa->co[0]= fac*pa->co[0] + (1.0f-fac)*vec[0];
- pa->co[1]= fac*pa->co[1] + (1.0f-fac)*vec[1];
- pa->co[2]= fac*pa->co[2] + (1.0f-fac)*vec[2];
-
- /* start speed: normal */
- if(paf->normfac!=0.0) {
- /* imat is transpose ! */
- VECCOPY(vec, no);
- Mat3MulVecfl(mcnow->imat, vec);
-
- Normalize(vec);
- VecMulf(vec, paf->normfac);
- VECADD(pa->no, pa->no, vec);
- }
- }
+ if(falloff<=0.0f)
+ ; /* don't do anything */
else {
- if(paf->normfac!=0.0) {
- VECCOPY(pa->no, no);
- Normalize(pa->no);
- VecMulf(pa->no, paf->normfac);
- }
- }
-
- pa->lifetime= paf->lifetime;
- if(paf->randlife!=0.0) {
- pa->lifetime*= 1.0f + paf->randlife*(rng_getFloat(rng) - 0.5f);
- }
- pa->mat_nr= paf->omat;
-
- if(folengths)
- pa->lifetime*= folengths[curface];
-
- make_particle_keys(rng, ob, 0, a, paf, pa, force, deform, mtexmove, effectorbase);
- }
-
- /* free stuff */
- give_mesh_particle_coord(NULL, NULL, NULL, 0, 0, NULL, NULL);
- MEM_freeN(vertexcosnos);
- if(voweights) MEM_freeN(voweights);
- if(foweights) MEM_freeN(foweights);
- if(volengths) MEM_freeN(volengths);
- if(folengths) MEM_freeN(folengths);
- if(mcache) MEM_freeN(mcache);
- rng_free(rng);
-
- if(deform) end_latt_deform();
-
- if(effectorbase)
- pdEndEffectors(effectorbase);
-
- /* reset deflector cache */
- for(base= G.scene->base.first; base; base= base->next) {
- if(base->object->sumohandle) {
+ float field[3]={0,0,0}, tmp[3];
+ VECCOPY(field, force);
+ do_physical_effector(ob, opco, pd->forcefield,pd->f_strength,distance,
+ falloff,pd->f_dist,pd->f_damp,ob->obmat[2],vec_to_part,
+ speed,force,pd->flag&PFIELD_PLANAR, pd->rng, pd->f_noise, 0.0f, 0.0f);
- MEM_freeN(base->object->sumohandle);
- base->object->sumohandle= NULL;
+ // for softbody backward compatibility
+ if(flags & PE_WIND_AS_SPEED){
+ VECSUB(tmp, force, field);
+ VECSUB(speed, speed, tmp);
+ }
}
}
-
- disable_speed_curve(0);
-
- //XXX if(waitcursor_set) waitcursor(0);
}
-
diff --git a/source/blender/blenkernel/intern/exotic.c b/source/blender/blenkernel/intern/exotic.c
index 7a138f9ac68..28ed74aa9db 100644
--- a/source/blender/blenkernel/intern/exotic.c
+++ b/source/blender/blenkernel/intern/exotic.c
@@ -76,10 +76,14 @@
#include <fcntl.h>
#include <string.h>
-#ifndef WIN32
+#ifndef _WIN32
#include <unistd.h>
#else
#include <io.h>
+#define open _open
+#define read _read
+#define close _close
+#define write _write
#endif
#include "MEM_guardedalloc.h"
@@ -116,7 +120,9 @@
#include "BKE_curve.h"
#include "BKE_customdata.h"
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h"
+#endif
#include "zlib.h"
@@ -869,7 +875,7 @@ static void read_videoscape_lamp(char *str)
Object *ob;
Lamp *la;
FILE *fp;
- float vec[3], *q1;
+ float vec[3], q1[4];
int tot, val;
char s[50];
@@ -897,7 +903,7 @@ static void read_videoscape_lamp(char *str)
fscanf(fp, "%f %f %f\n", ob->loc, ob->loc+1, ob->loc+2);
val= fscanf(fp, "%f %f %f\n", vec, vec+1, vec+2);
- q1= vectoquat(vec, 5, 2);
+ vectoquat(vec, 5, 2, q1);
QuatToEul(q1, ob->rot);
if(val<=0) break;
@@ -2091,8 +2097,10 @@ static void displist_to_mesh(DispList *dlfirst)
}
for(a=0; a<dl->parts; a++) {
-
- DL_SURFINDEX(dl->flag & DL_CYCL_U, dl->flag & DL_CYCL_V, dl->nr, dl->parts);
+
+ if (surfindex_displist(dl, a, &b, &p1, &p2, &p3, &p4)==0)
+ break;
+
p1+= startve;
p2+= startve;
p3+= startve;
@@ -2419,6 +2427,7 @@ int BKE_read_exotic(char *name)
read_stl_mesh_binary(name);
retval = 1;
}
+#ifndef DISABLE_PYTHON
// TODO: this should not be in the kernel...
else { // unknown format, call Python importloader
if (BPY_call_importloader(name)) {
@@ -2428,6 +2437,7 @@ int BKE_read_exotic(char *name)
}
}
+#endif /* DISABLE_PYTHON */
//XXX waitcursor(0);
}
}
@@ -2626,17 +2636,17 @@ static void write_videoscape_mesh(Object *ob, char *str)
if(evl->v4==0) {
fprintf(fp, "3 %ld %ld %ld 0x%x\n",
- evl->v1->tmp.l,
- evl->v2->tmp.l,
- evl->v3->tmp.l,
+ (long int) evl->v1->tmp.l,
+ (long int) evl->v2->tmp.l,
+ (long int) evl->v3->tmp.l,
kleur[evl->mat_nr]);
}
else {
fprintf(fp, "4 %ld %ld %ld %ld 0x%x\n",
- evl->v1->tmp.l,
- evl->v2->tmp.l,
- evl->v3->tmp.l,
- evl->v4->tmp.l,
+ (long int) evl->v1->tmp.l,
+ (long int) evl->v2->tmp.l,
+ (long int) evl->v3->tmp.l,
+ (long int) evl->v4->tmp.l,
kleur[evl->mat_nr]);
}
evl= evl->next;
diff --git a/source/blender/blenkernel/intern/fluidsim.c b/source/blender/blenkernel/intern/fluidsim.c
new file mode 100644
index 00000000000..29c4e0f2fb5
--- /dev/null
+++ b/source/blender/blenkernel/intern/fluidsim.c
@@ -0,0 +1,660 @@
+/**
+ * fluidsim.c
+ *
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_mesh_types.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_object_force.h" // for pointcache
+#include "DNA_particle_types.h"
+#include "DNA_scene_types.h" // N_T
+
+#include "BLI_arithb.h"
+#include "BLI_blenlib.h"
+
+#include "BKE_cdderivedmesh.h"
+#include "BKE_customdata.h"
+#include "BKE_DerivedMesh.h"
+#include "BKE_fluidsim.h"
+#include "BKE_global.h"
+#include "BKE_modifier.h"
+#include "BKE_mesh.h"
+#include "BKE_pointcache.h"
+#include "BKE_utildefines.h"
+
+// headers for fluidsim bobj meshes
+#include <stdlib.h>
+#include "LBM_fluidsim.h"
+#include "elbeem.h"
+#include <zlib.h>
+#include <string.h>
+#include <stdio.h>
+
+/* ************************* fluidsim bobj file handling **************************** */
+
+// -----------------------------------------
+// forward decleration
+// -----------------------------------------
+
+// -----------------------------------------
+
+void fluidsim_init(FluidsimModifierData *fluidmd)
+{
+#ifndef DISABLE_ELBEEM
+ if(fluidmd)
+ {
+ FluidsimSettings *fss = MEM_callocN(sizeof(FluidsimSettings), "fluidsimsettings");
+
+ fluidmd->fss = fss;
+
+ if(!fss)
+ return;
+
+ fss->type = OB_FSBND_NOSLIP;
+ fss->show_advancedoptions = 0;
+
+ fss->resolutionxyz = 50;
+ fss->previewresxyz = 25;
+ fss->realsize = 0.03;
+ fss->guiDisplayMode = 2; // preview
+ fss->renderDisplayMode = 3; // render
+
+ fss->viscosityMode = 2; // default to water
+ fss->viscosityValue = 1.0;
+ fss->viscosityExponent = 6;
+
+ // dg TODO: change this to []
+ fss->gravx = 0.0;
+ fss->gravy = 0.0;
+ fss->gravz = -9.81;
+ fss->animStart = 0.0;
+ fss->animEnd = 0.30;
+ fss->gstar = 0.005; // used as normgstar
+ fss->maxRefine = -1;
+ // maxRefine is set according to resolutionxyz during bake
+
+ // fluid/inflow settings
+ // fss->iniVel --> automatically set to 0
+
+ /* elubie: changed this to default to the same dir as the render output
+ to prevent saving to C:\ on Windows */
+ BLI_strncpy(fss->surfdataPath, btempdir, FILE_MAX);
+
+ // first init of bounding box
+ // no bounding box needed
+
+ // todo - reuse default init from elbeem!
+ fss->typeFlags = 0;
+ fss->domainNovecgen = 0;
+ fss->volumeInitType = 1; // volume
+ fss->partSlipValue = 0.0;
+
+ fss->generateTracers = 0;
+ fss->generateParticles = 0.0;
+ fss->surfaceSmoothing = 1.0;
+ fss->surfaceSubdivs = 1.0;
+ fss->particleInfSize = 0.0;
+ fss->particleInfAlpha = 0.0;
+
+ // init fluid control settings
+ fss->attractforceStrength = 0.2;
+ fss->attractforceRadius = 0.75;
+ fss->velocityforceStrength = 0.2;
+ fss->velocityforceRadius = 0.75;
+ fss->cpsTimeStart = fss->animStart;
+ fss->cpsTimeEnd = fss->animEnd;
+ fss->cpsQuality = 10.0; // 1.0 / 10.0 => means 0.1 width
+
+ /*
+ BAD TODO: this is done in buttons_object.c in the moment
+ Mesh *mesh = ob->data;
+ // calculate bounding box
+ fluid_get_bb(mesh->mvert, mesh->totvert, ob->obmat, fss->bbStart, fss->bbSize);
+ */
+
+ // (ab)used to store velocities
+ fss->meshSurfNormals = NULL;
+
+ fss->lastgoodframe = -1;
+
+ fss->flag = 0;
+
+ }
+#endif
+ return;
+}
+
+void fluidsim_free(FluidsimModifierData *fluidmd)
+{
+#ifndef DISABLE_ELBEEM
+ if(fluidmd)
+ {
+ if(fluidmd->fss->meshSurfNormals)
+ {
+ MEM_freeN(fluidmd->fss->meshSurfNormals);
+ fluidmd->fss->meshSurfNormals = NULL;
+ }
+ MEM_freeN(fluidmd->fss);
+ }
+#endif
+ return;
+}
+
+DerivedMesh *fluidsimModifier_do(FluidsimModifierData *fluidmd, Object *ob, DerivedMesh *dm, int useRenderParams, int isFinalCalc)
+{
+#ifndef DISABLE_ELBEEM
+ DerivedMesh *result = NULL;
+ int framenr;
+ FluidsimSettings *fss = NULL;
+
+ framenr= (int)G.scene->r.cfra;
+
+ // only handle fluidsim domains
+ if(fluidmd && fluidmd->fss && (fluidmd->fss->type != OB_FLUIDSIM_DOMAIN))
+ return dm;
+
+ // sanity check
+ if(!fluidmd || (fluidmd && !fluidmd->fss))
+ return dm;
+
+ fss = fluidmd->fss;
+
+ // timescale not supported yet
+ // clmd->sim_parms->timescale= timescale;
+
+ // support reversing of baked fluid frames here
+ if((fss->flag & OB_FLUIDSIM_REVERSE) && (fss->lastgoodframe >= 0))
+ {
+ framenr = fss->lastgoodframe - framenr + 1;
+ CLAMP(framenr, 1, fss->lastgoodframe);
+ }
+
+ /* try to read from cache */
+ if(((fss->lastgoodframe >= framenr) || (fss->lastgoodframe < 0)) && (result = fluidsim_read_cache(ob, dm, fluidmd, framenr, useRenderParams)))
+ {
+ // fss->lastgoodframe = framenr; // set also in src/fluidsim.c
+ return result;
+ }
+ else
+ {
+ // display last known good frame
+ if(fss->lastgoodframe >= 0)
+ {
+ if((result = fluidsim_read_cache(ob, dm, fluidmd, fss->lastgoodframe, useRenderParams)))
+ {
+ return result;
+ }
+
+ // it was supposed to be a valid frame but it isn't!
+ fss->lastgoodframe = framenr - 1;
+
+
+ // this could be likely the case when you load an old fluidsim
+ if((result = fluidsim_read_cache(ob, dm, fluidmd, fss->lastgoodframe, useRenderParams)))
+ {
+ return result;
+ }
+ }
+
+ result = CDDM_copy(dm);
+
+ if(result)
+ {
+ return result;
+ }
+ }
+
+ return dm;
+#else
+ return NULL;
+#endif
+}
+
+#ifndef DISABLE_ELBEEM
+/* read .bobj.gz file into a fluidsimDerivedMesh struct */
+static DerivedMesh *fluidsim_read_obj(char *filename)
+{
+ int wri,i,j;
+ float wrf;
+ int gotBytes;
+ gzFile gzf;
+ int numverts = 0, numfaces = 0;
+ DerivedMesh *dm = NULL;
+ MFace *mface;
+ MVert *mvert;
+ short *normals;
+
+ // ------------------------------------------------
+ // get numverts + numfaces first
+ // ------------------------------------------------
+ gzf = gzopen(filename, "rb");
+ if (!gzf)
+ {
+ return NULL;
+ }
+
+ // read numverts
+ gotBytes = gzread(gzf, &wri, sizeof(wri));
+ numverts = wri;
+
+ // skip verts
+ for(i=0; i<numverts*3; i++)
+ {
+ gotBytes = gzread(gzf, &wrf, sizeof( wrf ));
+ }
+
+ // read number of normals
+ gotBytes = gzread(gzf, &wri, sizeof(wri));
+
+ // skip normals
+ for(i=0; i<numverts*3; i++)
+ {
+ gotBytes = gzread(gzf, &wrf, sizeof( wrf ));
+ }
+
+ /* get no. of triangles */
+ gotBytes = gzread(gzf, &wri, sizeof(wri));
+ numfaces = wri;
+
+ gzclose( gzf );
+ // ------------------------------------------------
+
+ if(!numfaces || !numverts)
+ return NULL;
+
+ gzf = gzopen(filename, "rb");
+ if (!gzf)
+ {
+ return NULL;
+ }
+
+ dm = CDDM_new(numverts, 0, numfaces);
+
+ if(!dm)
+ {
+ gzclose( gzf );
+ return NULL;
+ }
+
+ // read numverts
+ gotBytes = gzread(gzf, &wri, sizeof(wri));
+
+ // read vertex position from file
+ mvert = CDDM_get_verts(dm);
+ for(i=0; i<numverts; i++)
+ {
+ MVert *mv = &mvert[i];
+
+ for(j=0; j<3; j++)
+ {
+ gotBytes = gzread(gzf, &wrf, sizeof( wrf ));
+ mv->co[j] = wrf;
+ }
+ }
+
+ // should be the same as numverts
+ gotBytes = gzread(gzf, &wri, sizeof(wri));
+ if(wri != numverts)
+ {
+ if(dm)
+ dm->release(dm);
+ gzclose( gzf );
+ return NULL;
+ }
+
+ normals = MEM_callocN(sizeof(short) * numverts * 3, "fluid_tmp_normals" );
+ if(!normals)
+ {
+ if(dm)
+ dm->release(dm);
+ gzclose( gzf );
+ return NULL;
+ }
+
+ // read normals from file (but don't save them yet)
+ for(i=0; i<numverts*3; i++)
+ {
+ gotBytes = gzread(gzf, &wrf, sizeof( wrf ));
+ normals[i] = (short)(wrf*32767.0f);
+ }
+
+ /* read no. of triangles */
+ gotBytes = gzread(gzf, &wri, sizeof(wri));
+
+ if(wri!=numfaces)
+ printf("Fluidsim: error in reading data from file.\n");
+
+ // read triangles from file
+ mface = CDDM_get_faces(dm);
+ for(i=0; i<numfaces; i++)
+ {
+ int face[4];
+ MFace *mf = &mface[i];
+
+ gotBytes = gzread(gzf, &(face[0]), sizeof( face[0] ));
+ gotBytes = gzread(gzf, &(face[1]), sizeof( face[1] ));
+ gotBytes = gzread(gzf, &(face[2]), sizeof( face[2] ));
+ face[3] = 0;
+
+ // check if 3rd vertex has index 0 (not allowed in blender)
+ if(face[2])
+ {
+ mf->v1 = face[0];
+ mf->v2 = face[1];
+ mf->v3 = face[2];
+ }
+ else
+ {
+ mf->v1 = face[1];
+ mf->v2 = face[2];
+ mf->v3 = face[0];
+ }
+ mf->v4 = face[3];
+
+ test_index_face(mf, NULL, 0, 3);
+ }
+
+ gzclose( gzf );
+
+ CDDM_calc_edges(dm);
+
+ CDDM_apply_vert_normals(dm, (short (*)[3])normals);
+ MEM_freeN(normals);
+
+ // CDDM_calc_normals(result);
+
+ return dm;
+}
+
+DerivedMesh *fluidsim_read_cache(Object *ob, DerivedMesh *orgdm, FluidsimModifierData *fluidmd, int framenr, int useRenderParams)
+{
+ int displaymode = 0;
+ int curFrame = framenr - 1 /*G.scene->r.sfra*/; /* start with 0 at start frame */
+ char targetDir[FILE_MAXFILE+FILE_MAXDIR], targetFile[FILE_MAXFILE+FILE_MAXDIR];
+ FluidsimSettings *fss = fluidmd->fss;
+ DerivedMesh *dm = NULL;
+ MFace *mface;
+ int numfaces;
+ int mat_nr, flag, i;
+
+ if(!useRenderParams) {
+ displaymode = fss->guiDisplayMode;
+ } else {
+ displaymode = fss->renderDisplayMode;
+ }
+
+ strncpy(targetDir, fss->surfdataPath, FILE_MAXDIR);
+
+ // use preview or final mesh?
+ if(displaymode==1)
+ {
+ // just display original object
+ return NULL;
+ }
+ else if(displaymode==2)
+ {
+ strcat(targetDir,"fluidsurface_preview_####");
+ }
+ else
+ { // 3
+ strcat(targetDir,"fluidsurface_final_####");
+ }
+
+ BLI_convertstringcode(targetDir, G.sce);
+ BLI_convertstringframe(targetDir, curFrame); // fixed #frame-no
+
+ strcpy(targetFile,targetDir);
+ strcat(targetFile, ".bobj.gz");
+
+ dm = fluidsim_read_obj(targetFile);
+
+ if(!dm)
+ {
+ // switch, abort background rendering when fluidsim mesh is missing
+ const char *strEnvName2 = "BLENDER_ELBEEMBOBJABORT"; // from blendercall.cpp
+
+ if(G.background==1) {
+ if(getenv(strEnvName2)) {
+ int elevel = atoi(getenv(strEnvName2));
+ if(elevel>0) {
+ printf("Env. var %s set, fluid sim mesh '%s' not found, aborting render...\n",strEnvName2, targetFile);
+ exit(1);
+ }
+ }
+ }
+
+ // display org. object upon failure which is in dm
+ return NULL;
+ }
+
+ // assign material + flags to new dm
+ mface = orgdm->getFaceArray(orgdm);
+ mat_nr = mface[0].mat_nr;
+ flag = mface[0].flag;
+
+ mface = dm->getFaceArray(dm);
+ numfaces = dm->getNumFaces(dm);
+ for(i=0; i<numfaces; i++)
+ {
+ mface[i].mat_nr = mat_nr;
+ mface[i].flag = flag;
+ }
+
+ // load vertex velocities, if they exist...
+ // TODO? use generate flag as loading flag as well?
+ // warning, needs original .bobj.gz mesh loading filename
+ if(displaymode==3)
+ {
+ fluidsim_read_vel_cache(fluidmd, dm, targetFile);
+ }
+ else
+ {
+ if(fss->meshSurfNormals)
+ MEM_freeN(fss->meshSurfNormals);
+
+ fss->meshSurfNormals = NULL;
+ }
+
+ return dm;
+}
+
+
+/* read zipped fluidsim velocities into the co's of the fluidsimsettings normals struct */
+void fluidsim_read_vel_cache(FluidsimModifierData *fluidmd, DerivedMesh *dm, char *filename)
+{
+ int wri, i, j;
+ float wrf;
+ gzFile gzf;
+ FluidsimSettings *fss = fluidmd->fss;
+ int len = strlen(filename);
+ int totvert = dm->getNumVerts(dm);
+ float *velarray = NULL;
+
+ // mesh and vverts have to be valid from loading...
+
+ if(fss->meshSurfNormals)
+ MEM_freeN(fss->meshSurfNormals);
+
+ if(len<7)
+ {
+ return;
+ }
+
+ if(fss->domainNovecgen>0) return;
+
+ // abusing pointer to hold an array of 3d-velocities
+ fss->meshSurfNormals = MEM_callocN(sizeof(float)*3*dm->getNumVerts(dm), "Fluidsim_velocities");
+ // abusing pointer to hold an INT
+ fss->meshSurface = SET_INT_IN_POINTER(totvert);
+
+ velarray = (float *)fss->meshSurfNormals;
+
+ // .bobj.gz , correct filename
+ // 87654321
+ filename[len-6] = 'v';
+ filename[len-5] = 'e';
+ filename[len-4] = 'l';
+
+ gzf = gzopen(filename, "rb");
+ if (!gzf)
+ {
+ MEM_freeN(fss->meshSurfNormals);
+ fss->meshSurfNormals = NULL;
+ return;
+ }
+
+ gzread(gzf, &wri, sizeof( wri ));
+ if(wri != totvert)
+ {
+ MEM_freeN(fss->meshSurfNormals);
+ fss->meshSurfNormals = NULL;
+ return;
+ }
+
+ for(i=0; i<totvert;i++)
+ {
+ for(j=0; j<3; j++)
+ {
+ gzread(gzf, &wrf, sizeof( wrf ));
+ velarray[3*i + j] = wrf;
+ }
+ }
+
+ gzclose(gzf);
+}
+
+void fluid_get_bb(MVert *mvert, int totvert, float obmat[][4],
+ /*RET*/ float start[3], /*RET*/ float size[3] )
+{
+ float bbsx=0.0, bbsy=0.0, bbsz=0.0;
+ float bbex=1.0, bbey=1.0, bbez=1.0;
+ int i;
+ float vec[3];
+
+ VECCOPY(vec, mvert[0].co);
+ Mat4MulVecfl(obmat, vec);
+ bbsx = vec[0]; bbsy = vec[1]; bbsz = vec[2];
+ bbex = vec[0]; bbey = vec[1]; bbez = vec[2];
+
+ for(i = 1; i < totvert; i++) {
+ VECCOPY(vec, mvert[i].co);
+ Mat4MulVecfl(obmat, vec);
+
+ if(vec[0] < bbsx){ bbsx= vec[0]; }
+ if(vec[1] < bbsy){ bbsy= vec[1]; }
+ if(vec[2] < bbsz){ bbsz= vec[2]; }
+ if(vec[0] > bbex){ bbex= vec[0]; }
+ if(vec[1] > bbey){ bbey= vec[1]; }
+ if(vec[2] > bbez){ bbez= vec[2]; }
+ }
+
+ // return values...
+ if(start) {
+ start[0] = bbsx;
+ start[1] = bbsy;
+ start[2] = bbsz;
+ }
+ if(size) {
+ size[0] = bbex-bbsx;
+ size[1] = bbey-bbsy;
+ size[2] = bbez-bbsz;
+ }
+}
+
+//-------------------------------------------------------------------------------
+// old interface
+//-------------------------------------------------------------------------------
+
+
+
+//-------------------------------------------------------------------------------
+// file handling
+//-------------------------------------------------------------------------------
+
+void initElbeemMesh(struct Object *ob,
+ int *numVertices, float **vertices,
+ int *numTriangles, int **triangles,
+ int useGlobalCoords, int modifierIndex)
+{
+ DerivedMesh *dm = NULL;
+ MVert *mvert;
+ MFace *mface;
+ int countTris=0, i, totvert, totface;
+ float *verts;
+ int *tris;
+
+ dm = mesh_create_derived_index_render(ob, CD_MASK_BAREMESH, modifierIndex);
+ //dm = mesh_create_derived_no_deform(ob,NULL);
+
+ mvert = dm->getVertArray(dm);
+ mface = dm->getFaceArray(dm);
+ totvert = dm->getNumVerts(dm);
+ totface = dm->getNumFaces(dm);
+
+ *numVertices = totvert;
+ verts = MEM_callocN( totvert*3*sizeof(float), "elbeemmesh_vertices");
+ for(i=0; i<totvert; i++) {
+ VECCOPY( &verts[i*3], mvert[i].co);
+ if(useGlobalCoords) { Mat4MulVecfl(ob->obmat, &verts[i*3]); }
+ }
+ *vertices = verts;
+
+ for(i=0; i<totface; i++) {
+ countTris++;
+ if(mface[i].v4) { countTris++; }
+ }
+ *numTriangles = countTris;
+ tris = MEM_callocN( countTris*3*sizeof(int), "elbeemmesh_triangles");
+ countTris = 0;
+ for(i=0; i<totface; i++) {
+ int face[4];
+ face[0] = mface[i].v1;
+ face[1] = mface[i].v2;
+ face[2] = mface[i].v3;
+ face[3] = mface[i].v4;
+
+ tris[countTris*3+0] = face[0];
+ tris[countTris*3+1] = face[1];
+ tris[countTris*3+2] = face[2];
+ countTris++;
+ if(face[3]) {
+ tris[countTris*3+0] = face[0];
+ tris[countTris*3+1] = face[2];
+ tris[countTris*3+2] = face[3];
+ countTris++;
+ }
+ }
+ *triangles = tris;
+
+ dm->release(dm);
+}
+
+#endif // DISABLE_ELBEEM
+
diff --git a/source/blender/blenkernel/intern/font.c b/source/blender/blenkernel/intern/font.c
index fb58c076c95..a8a97742c24 100644
--- a/source/blender/blenkernel/intern/font.c
+++ b/source/blender/blenkernel/intern/font.c
@@ -160,41 +160,61 @@ utf8slen(char *src)
return size;
}
-int utf8towchar_(wchar_t *w, char *c)
+
+/* Converts Unicode to wchar
+
+According to RFC 3629 "UTF-8, a transformation format of ISO 10646"
+(http://tools.ietf.org/html/rfc3629), the valid UTF-8 encoding are:
+
+ Char. number range | UTF-8 octet sequence
+ (hexadecimal) | (binary)
+ --------------------+---------------------------------------------
+ 0000 0000-0000 007F | 0xxxxxxx
+ 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
+ 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
+ 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
+
+If the encoding incidated by the first character is incorrect (because the
+1 to 3 following characters do not match 10xxxxxx), the output is a '?' and
+only a single input character is consumed.
+
+*/
+
+int utf8towchar(wchar_t *w, char *c)
{
int len=0;
+
if(w==NULL || c==NULL) return(0);
- //printf("%s\n",c);
- while(*c)
- {
- if(*c & 0x80)
- {
- if(*c & 0x40)
- {
- if(*c & 0x20)
- {
- if(*c & 0x10)
- {
- *w=(c[0] & 0x0f)<<18 | (c[1]&0x1f)<<12 | (c[2]&0x3f)<<6 | (c[3]&0x7f);
- c++;
- }
- else
- *w=(c[0] & 0x1f)<<12 | (c[1]&0x3f)<<6 | (c[2]&0x7f);
- c++;
- }
- else
- *w=(((c[0] &0x3f)<<6) | (c[1]&0x7f));
+
+ while(*c) {
+ if ((*c & 0xe0) == 0xc0) {
+ if((c[1] & 0x80) && (c[1] & 0x40) == 0x00) {
+ *w=((c[0] &0x1f)<<6) | (c[1]&0x3f);
c++;
+ } else {
+ *w = '?';
}
- else
- *w=(c[0] & 0x7f);
+ } else if ((*c & 0xf0) == 0xe0) {
+ if((c[1] & c[2] & 0x80) && ((c[1] | c[2]) & 0x40) == 0x00) {
+ *w=((c[0] & 0x0f)<<12) | ((c[1]&0x3f)<<6) | (c[2]&0x3f);
+ c += 2;
+ } else {
+ *w = '?';
}
- else
- *w=(c[0] & 0x7f);
- c++;
- w++;
- len++;
- }
+ } else if ((*c & 0xf8) == 0xf0) {
+ if((c[1] & c[2] & c[3] & 0x80) && ((c[1] | c[2] | c[3]) & 0x40) == 0x00) {
+ *w=((c[0] & 0x07)<<18) | ((c[1]&0x1f)<<12) | ((c[2]&0x3f)<<6) | (c[3]&0x3f);
+ c += 3;
+ } else {
+ *w = '?';
+ }
+ } else
+ *w=(c[0] & 0x7f);
+
+ c++;
+ w++;
+ len++;
+ }
return len;
}
@@ -443,7 +463,7 @@ static void build_underline(Curve *cu, float x1, float y1, float x2, float y2, i
if (nu2 == NULL) return;
nu2->resolu= cu->resolu;
nu2->bezt = NULL;
- nu2->knotsu = nu2->knotsv = 0;
+ nu2->knotsu = nu2->knotsv = NULL;
nu2->flag= 0;
nu2->charidx = charidx+1000;
if (mat_nr > 0) nu2->mat_nr= mat_nr-1;
@@ -532,7 +552,7 @@ static void buildchar(Curve *cu, unsigned long character, CharInfo *info, float
memcpy(nu2, nu1, sizeof(struct Nurb));
nu2->resolu= cu->resolu;
nu2->bp = 0;
- nu2->knotsu = nu2->knotsv = 0;
+ nu2->knotsu = nu2->knotsv = NULL;
nu2->flag= CU_SMOOTH;
nu2->charidx = charidx;
if (info->mat_nr) {
@@ -664,7 +684,7 @@ struct chartrans *text_to_curve(Object *ob, int mode)
utf8len = utf8slen(cu->str);
tmp = mem = MEM_callocN(((utf8len + 1) * sizeof(wchar_t)), "convertedmem");
- utf8towchar_(mem, cu->str);
+ utf8towchar(mem, cu->str);
// Count the wchar_t string length
slen = wcslen(mem);
diff --git a/source/blender/blenkernel/intern/group.c b/source/blender/blenkernel/intern/group.c
index 201d93220f9..0d2f86bb151 100644
--- a/source/blender/blenkernel/intern/group.c
+++ b/source/blender/blenkernel/intern/group.c
@@ -41,6 +41,7 @@
#include "DNA_object_types.h"
#include "DNA_nla_types.h"
#include "DNA_scene_types.h"
+#include "DNA_particle_types.h"
#include "BLI_blenlib.h"
@@ -77,14 +78,37 @@ void unlink_group(Group *group)
{
Material *ma;
Object *ob;
+ Scene *sce;
+ SceneRenderLayer *srl;
+ ParticleSystem *psys;
for(ma= G.main->mat.first; ma; ma= ma->id.next) {
if(ma->group==group)
ma->group= NULL;
}
+ for(ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if(ma->group==group)
+ ma->group= NULL;
+ }
+ for (sce= G.main->scene.first; sce; sce= sce->id.next) {
+ Base *base= sce->base.first;
+
+ /* ensure objects are not in this group */
+ for(; base; base= base->next) {
+ if(rem_from_group(group, base->object) && find_group(base->object, NULL)==NULL) {
+ base->object->flag &= ~OB_FROMGROUP;
+ base->flag &= ~OB_FROMGROUP;
+ }
+ }
+
+ for(srl= sce->r.layers.first; srl; srl= srl->next) {
+ if (srl->light_override==group)
+ srl->light_override= NULL;
+ }
+ }
+
for(ob= G.main->object.first; ob; ob= ob->id.next) {
bActionStrip *strip;
- PartEff *paf;
if(ob->dup_group==group) {
ob->dup_group= NULL;
@@ -95,13 +119,17 @@ void unlink_group(Group *group)
strip->object= NULL;
}
}
- for(paf= ob->effect.first; paf; paf= paf->next) {
- if(paf->type==EFF_PARTICLE) {
- if(paf->group)
- paf->group= NULL;
- }
+
+ for(psys=ob->particlesystem.first; psys; psys=psys->next){
+ if(psys->part->dup_group==group)
+ psys->part->dup_group= NULL;
+ if(psys->part->eff_group==group)
+ psys->part->eff_group= NULL;
}
}
+
+ /* group stays in library, but no members */
+ free_group(group);
group->id.us= 0;
}
@@ -134,11 +162,11 @@ void add_to_group(Group *group, Object *ob)
}
/* also used for ob==NULL */
-void rem_from_group(Group *group, Object *ob)
+int rem_from_group(Group *group, Object *ob)
{
GroupObject *go, *gon;
-
- if(group==NULL) return;
+ int removed = 0;
+ if(group==NULL) return 0;
go= group->gobject.first;
while(go) {
@@ -146,9 +174,12 @@ void rem_from_group(Group *group, Object *ob)
if(go->ob==ob) {
BLI_remlink(&group->gobject, go);
free_group_object(go);
+ removed = 1;
+ /* should break here since an object being in a group twice cant happen? */
}
go= gon;
}
+ return removed;
}
int object_in_group(Object *ob, Group *group)
@@ -164,9 +195,12 @@ int object_in_group(Object *ob, Group *group)
return 0;
}
-Group *find_group(Object *ob)
+Group *find_group(Object *ob, Group *group)
{
- Group *group= G.main->group.first;
+ if (group)
+ group= group->id.next;
+ else
+ group= G.main->group.first;
while(group) {
if(object_in_group(ob, group))
@@ -188,6 +222,20 @@ void group_tag_recalc(Group *group)
}
}
+int group_is_animated(Object *parent, Group *group)
+{
+ GroupObject *go;
+
+ if(give_timeoffset(parent) != 0.0f || parent->nlastrips.first)
+ return 1;
+
+ for(go= group->gobject.first; go; go= go->next)
+ if(go->ob && go->ob->proxy)
+ return 1;
+
+ return 0;
+}
+
/* only replaces object strips or action when parent nla instructs it */
/* keep checking nla.c though, in case internal structure of strip changes */
static void group_replaces_nla(Object *parent, Object *target, char mode)
@@ -228,7 +276,6 @@ static void group_replaces_nla(Object *parent, Object *target, char mode)
}
}
-
/* puts all group members in local timing system, after this call
you can draw everything, leaves tags in objects to signal it needs further updating */
@@ -238,12 +285,12 @@ void group_handle_recalc_and_update(Object *parent, Group *group)
GroupObject *go;
/* if animated group... */
- if(parent->sf != 0.0f || parent->nlastrips.first) {
+ if(give_timeoffset(parent) != 0.0f || parent->nlastrips.first) {
int cfrao;
/* switch to local time */
cfrao= G.scene->r.cfra;
- G.scene->r.cfra -= (int)parent->sf;
+ G.scene->r.cfra -= (int)give_timeoffset(parent);
/* we need a DAG per group... */
for(go= group->gobject.first; go; go= go->next) {
diff --git a/source/blender/blenkernel/intern/icons.c b/source/blender/blenkernel/intern/icons.c
index f144d2badd1..b9e3c593ddf 100644
--- a/source/blender/blenkernel/intern/icons.c
+++ b/source/blender/blenkernel/intern/icons.c
@@ -48,6 +48,9 @@
#include "BLI_ghash.h"
#include "BKE_icons.h"
+#include "BKE_utildefines.h"
+
+#include "BLO_sys_types.h" // for intptr_t support
#define GS(a) (*((short *)(a)))
@@ -87,7 +90,7 @@ static int get_next_free_id()
return gNextIconId++;
/* now we try to find the smallest icon id not stored in the gIcons hash */
- while (BLI_ghash_lookup(gIcons, (void *)startId) && startId>=gFirstIconId)
+ while (BLI_ghash_lookup(gIcons, SET_INT_IN_POINTER(startId)) && startId>=gFirstIconId)
startId++;
/* if we found a suitable one that isnt used yet, return it */
@@ -216,7 +219,7 @@ void BKE_icon_changed(int id)
if (!id) return;
- icon = BLI_ghash_lookup(gIcons, (void *)id);
+ icon = BLI_ghash_lookup(gIcons, SET_INT_IN_POINTER(id));
if (icon)
{
@@ -258,7 +261,7 @@ int BKE_icon_getid(struct ID* id)
new_icon->drawinfo = 0;
new_icon->drawinfo_free = 0;
- BLI_ghash_insert(gIcons, (void *)id->icon_id, new_icon);
+ BLI_ghash_insert(gIcons, SET_INT_IN_POINTER(id->icon_id), new_icon);
return id->icon_id;
}
@@ -267,7 +270,7 @@ Icon* BKE_icon_get(int icon_id)
{
Icon* icon = 0;
- icon = BLI_ghash_lookup(gIcons, (void*)icon_id);
+ icon = BLI_ghash_lookup(gIcons, SET_INT_IN_POINTER(icon_id));
if (!icon) {
printf("BKE_icon_get: Internal error, no icon for icon ID: %d\n", icon_id);
@@ -281,7 +284,7 @@ void BKE_icon_set(int icon_id, struct Icon* icon)
{
Icon* old_icon = 0;
- old_icon = BLI_ghash_lookup(gIcons, (void*)icon_id);
+ old_icon = BLI_ghash_lookup(gIcons, SET_INT_IN_POINTER(icon_id));
if (old_icon)
{
@@ -289,7 +292,7 @@ void BKE_icon_set(int icon_id, struct Icon* icon)
return;
}
- BLI_ghash_insert(gIcons, (void *)icon_id, icon);
+ BLI_ghash_insert(gIcons, SET_INT_IN_POINTER(icon_id), icon);
}
void BKE_icon_delete(struct ID* id)
@@ -297,6 +300,6 @@ void BKE_icon_delete(struct ID* id)
if (!id->icon_id) return; /* no icon defined for library object */
- BLI_ghash_remove(gIcons, (void*)id->icon_id, 0, icon_free);
+ BLI_ghash_remove(gIcons, SET_INT_IN_POINTER(id->icon_id), 0, icon_free);
id->icon_id = 0;
}
diff --git a/source/blender/blenkernel/intern/idprop.c b/source/blender/blenkernel/intern/idprop.c
index eb633e92cc0..542a1dff651 100644
--- a/source/blender/blenkernel/intern/idprop.c
+++ b/source/blender/blenkernel/intern/idprop.c
@@ -54,7 +54,8 @@ static char idp_size_table[] = {
sizeof(float)*16, /*Matrix type, deprecated*/
0, /*arrays don't have a fixed size*/
sizeof(ListBase), /*Group type*/
- sizeof(void*)
+ sizeof(void*),
+ sizeof(double)
};
@@ -110,6 +111,7 @@ void IDP_ResizeArray(IDProperty *prop, int newlen)
newp->type = prop->type;
newp->flag = prop->flag;
newp->data.val = prop->data.val;
+ newp->data.val2 = prop->data.val2;
return newp;
}
@@ -209,7 +211,8 @@ void IDP_UnlinkID(IDProperty *prop)
IDProperty *IDP_CopyGroup(IDProperty *prop)
{
IDProperty *newp = idp_generic_copy(prop), *link;
-
+ newp->len = prop->len;
+
for (link=prop->data.group.first; link; link=link->next) {
BLI_addtail(&newp->data.group, IDP_CopyProperty(link));
}
@@ -217,6 +220,10 @@ IDProperty *IDP_CopyGroup(IDProperty *prop)
return newp;
}
+/*
+ replaces a property with the same name in a group, or adds
+ it if the propery doesn't exist.
+*/
void IDP_ReplaceInGroup(IDProperty *group, IDProperty *prop)
{
IDProperty *loop;
@@ -224,10 +231,10 @@ void IDP_ReplaceInGroup(IDProperty *group, IDProperty *prop)
if (BSTR_EQ(loop->name, prop->name)) {
if (loop->next) BLI_insertlinkbefore(&group->data.group, loop->next, prop);
else BLI_addtail(&group->data.group, prop);
+
BLI_remlink(&group->data.group, loop);
IDP_FreeProperty(loop);
- MEM_freeN(loop);
- group->len++;
+ MEM_freeN(loop);
return;
}
}
@@ -259,7 +266,7 @@ int IDP_InsertToGroup(IDProperty *group, IDProperty *previous, IDProperty *pnew)
}
group->len++;
-
+
BLI_insertlink(&group->data.group, previous, pnew);
return 1;
}
@@ -314,7 +321,7 @@ void IDP_FreeIterBeforeEnd(void *vself)
This is because all ID Property freeing functions free only direct data (not the ID Property
struct itself), but for Groups the child properties *are* considered
direct data.*/
-void IDP_FreeGroup(IDProperty *prop)
+static void IDP_FreeGroup(IDProperty *prop)
{
IDProperty *loop, *next;
for (loop=prop->data.group.first; loop; loop=next)
@@ -345,6 +352,10 @@ IDProperty *IDP_GetProperties(ID *id, int create_if_needed)
if (create_if_needed) {
id->properties = MEM_callocN(sizeof(IDProperty), "IDProperty");
id->properties->type = IDP_GROUP;
+ /* dont overwite the data's name and type
+ * some functions might need this if they
+ * dont have a real ID, should be named elsewhere - Campbell */
+ /* strcpy(id->name, "top_level_group");*/
}
return id->properties;
}
@@ -363,10 +374,14 @@ IDProperty *IDP_New(int type, IDPropertyTemplate val, char *name)
prop = MEM_callocN(sizeof(IDProperty), "IDProperty float");
*(float*)&prop->data.val = val.f;
break;
+ case IDP_DOUBLE:
+ prop = MEM_callocN(sizeof(IDProperty), "IDProperty float");
+ *(double*)&prop->data.val = val.d;
+ break;
case IDP_ARRAY:
{
- /*for now, we only support float and int arrays*/
- if (val.array.type == IDP_FLOAT || val.array.type == IDP_INT) {
+ /*for now, we only support float and int and double arrays*/
+ if (val.array.type == IDP_FLOAT || val.array.type == IDP_INT || val.array.type == IDP_DOUBLE) {
prop = MEM_callocN(sizeof(IDProperty), "IDProperty array");
prop->len = prop->totallen = val.array.len;
prop->subtype = val.array.type;
@@ -409,10 +424,14 @@ IDProperty *IDP_New(int type, IDPropertyTemplate val, char *name)
prop->type = type;
strncpy(prop->name, name, MAX_IDPROP_NAME);
+
+ /*security null byte*/
+ prop->name[MAX_IDPROP_NAME-1] = 0;
+
return prop;
}
-/*NOTE: this will free all child properties of list arrays and groups!
+/*NOTE: this will free all child properties including list arrays and groups!
Also, note that this does NOT unlink anything! Plus it doesn't free
the actual IDProperty struct either.*/
void IDP_FreeProperty(IDProperty *prop)
@@ -430,7 +449,8 @@ void IDP_FreeProperty(IDProperty *prop)
}
}
-/*Unlinks any IDProperty<->ID linkage that might be going on.*/
+/*Unlinks any IDProperty<->ID linkage that might be going on.
+ note: currently unused.*/
void IDP_UnlinkProperty(IDProperty *prop)
{
switch (prop->type) {
diff --git a/source/blender/blenkernel/intern/image.c b/source/blender/blenkernel/intern/image.c
index a79433fcfa1..de1747e514c 100644
--- a/source/blender/blenkernel/intern/image.c
+++ b/source/blender/blenkernel/intern/image.c
@@ -53,6 +53,7 @@
#include "DNA_packedFile_types.h"
#include "DNA_scene_types.h"
#include "DNA_camera_types.h"
+#include "DNA_sequence_types.h"
#include "DNA_texture_types.h"
#include "DNA_sequence_types.h"
#include "DNA_userdef_types.h"
@@ -81,6 +82,11 @@
/* for stamp drawing to an image */
#include "BMF_Api.h"
+#include "GPU_extensions.h"
+#include "GPU_draw.h"
+
+#include "BLO_sys_types.h" // for intptr_t support
+
/* max int, to indicate we don't store sequences in ibuf */
#define IMA_NO_INDEX 0x7FEFEFEF
@@ -93,32 +99,50 @@
/* used by sequencer and image premul option - IMA_DO_PREMUL */
void converttopremul(struct ImBuf *ibuf)
{
- int x, y, val;
- char *cp;
+ int x, y;
if(ibuf==0) return;
- if(ibuf->depth==24) { /* put alpha at 255 */
-
- cp= (char *)(ibuf->rect);
- for(y=0; y<ibuf->y; y++) {
- for(x=0; x<ibuf->x; x++, cp+=4) {
- cp[3]= 255;
+ if (ibuf->rect) {
+ int val;
+ char *cp;
+ if(ibuf->depth==24) { /* put alpha at 255 */
+ cp= (char *)(ibuf->rect);
+ for(y=0; y<ibuf->y; y++) {
+ for(x=0; x<ibuf->x; x++, cp+=4) {
+ cp[3]= 255;
+ }
+ }
+ } else {
+ cp= (char *)(ibuf->rect);
+ for(y=0; y<ibuf->y; y++) {
+ for(x=0; x<ibuf->x; x++, cp+=4) {
+ val= cp[3];
+ cp[0]= (cp[0]*val)>>8;
+ cp[1]= (cp[1]*val)>>8;
+ cp[2]= (cp[2]*val)>>8;
+ }
}
}
- return;
}
-
- cp= (char *)(ibuf->rect);
- for(y=0; y<ibuf->y; y++) {
- for(x=0; x<ibuf->x; x++, cp+=4) {
- if(cp[3]==0) {
- cp[0]= cp[1]= cp[2]= 0;
+ if (ibuf->rect_float) {
+ float val;
+ float *cp;
+ if(ibuf->depth==24) { /* put alpha at 1.0 */
+ cp= ibuf->rect_float;;
+ for(y=0; y<ibuf->y; y++) {
+ for(x=0; x<ibuf->x; x++, cp+=4) {
+ cp[3]= 1.0;
+ }
}
- else if(cp[3]!=255) {
- val= cp[3];
- cp[0]= (cp[0]*val)>>8;
- cp[1]= (cp[1]*val)>>8;
- cp[2]= (cp[2]*val)>>8;
+ } else {
+ cp= ibuf->rect_float;
+ for(y=0; y<ibuf->y; y++) {
+ for(x=0; x<ibuf->x; x++, cp+=4) {
+ val= cp[3];
+ cp[0]= cp[0]*val;
+ cp[1]= cp[1]*val;
+ cp[2]= cp[2]*val;
+ }
}
}
}
@@ -215,7 +239,7 @@ static void image_free_buffers(Image *ima)
ima->rr= NULL;
}
- //XXX free_realtime_image(ima);
+ GPU_free_image(ima);
ima->ok= IMA_OK;
}
@@ -223,7 +247,6 @@ static void image_free_buffers(Image *ima)
/* called by library too, do not free ima itself */
void free_image(Image *ima)
{
-
image_free_buffers(ima);
if (ima->packedfile) {
freePackedFile(ima->packedfile);
@@ -234,7 +257,6 @@ void free_image(Image *ima)
if (ima->preview) {
BKE_previewimg_free(&ima->preview);
}
-
}
/* only image block itself */
@@ -260,15 +282,19 @@ static Image *image_alloc(const char *name, short source, short type)
/* get the ibuf from an image cache, local use here only */
static ImBuf *image_get_ibuf(Image *ima, int index, int frame)
{
+ /* this function is intended to be thread safe. with IMA_NO_INDEX this
+ * should be OK, but when iterating over the list this is more tricky
+ * */
if(index==IMA_NO_INDEX)
return ima->ibufs.first;
else {
ImBuf *ibuf;
-
+
index= IMA_MAKE_INDEX(frame, index);
for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next)
if(ibuf->index==index)
return ibuf;
+
return NULL;
}
}
@@ -296,19 +322,16 @@ static void image_assign_ibuf(Image *ima, ImBuf *ibuf, int index, int frame)
for(link= ima->ibufs.first; link; link= link->next)
if(link->index>=index)
break;
- /* now we don't want copies? */
- if(link && ibuf->index==link->index) {
- ImBuf *prev= ibuf->prev;
- image_remove_ibuf(ima, link);
- link= prev;
- }
-
+
+ ibuf->index= index;
+
/* this function accepts link==NULL */
BLI_insertlinkbefore(&ima->ibufs, link, ibuf);
-
- ibuf->index= index;
+
+ /* now we don't want copies? */
+ if(link && ibuf->index==link->index)
+ image_remove_ibuf(ima, link);
}
-
}
/* checks if image was already loaded, then returns same image */
@@ -329,7 +352,8 @@ Image *BKE_add_image_file(const char *name)
}
BLI_strncpy(str, name, sizeof(str));
- BLI_convertstringcode(str, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(str, G.sce);
+ BLI_convertstringframe(str, G.scene->r.cfra); /* TODO - should this realy be here? */
/* exists? */
file= open(str, O_BINARY|O_RDONLY);
@@ -340,7 +364,8 @@ Image *BKE_add_image_file(const char *name)
for(ima= G.main->image.first; ima; ima= ima->id.next) {
if(ima->source!=IMA_SRC_VIEWER && ima->source!=IMA_SRC_GENERATED) {
BLI_strncpy(strtest, ima->name, sizeof(ima->name));
- BLI_convertstringcode(strtest, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(strtest, G.sce);
+ BLI_convertstringframe(strtest, G.scene->r.cfra); /* TODO - should this be here? */
if( strcmp(strtest, str)==0 ) {
if(ima->anim==NULL || ima->id.us==0) {
@@ -373,20 +398,27 @@ Image *BKE_add_image_file(const char *name)
return ima;
}
-static ImBuf *add_ibuf_size(int width, int height, char *name, short uvtestgrid, float color[4])
+static ImBuf *add_ibuf_size(int width, int height, char *name, int floatbuf, short uvtestgrid, float color[4])
{
ImBuf *ibuf;
float h=0.0, hoffs=0.0, hue=0.0, s=0.9, v=0.9, r, g, b;
- unsigned char *rect;
+ unsigned char *rect= NULL;
+ float *rect_float= NULL;
int x, y;
int checkerwidth=21, dark=1;
- ibuf= IMB_allocImBuf(width, height, 24, IB_rect, 0);
+ if (floatbuf) {
+ ibuf= IMB_allocImBuf(width, height, 24, IB_rectfloat, 0);
+ rect_float= (float*)ibuf->rect_float;
+ }
+ else {
+ ibuf= IMB_allocImBuf(width, height, 24, IB_rect, 0);
+ rect= (unsigned char*)ibuf->rect;
+ }
+
strcpy(ibuf->name, "Untitled");
ibuf->userflags |= IB_BITMAPDIRTY;
- rect= (unsigned char*)ibuf->rect;
-
if (uvtestgrid) {
/* these two passes could be combined into one, but it's more readable and
* easy to tweak like this, speed isn't really that much of an issue in this situation... */
@@ -395,26 +427,40 @@ static ImBuf *add_ibuf_size(int width, int height, char *name, short uvtestgrid,
for(y=0; y<ibuf->y; y++) {
dark = pow(-1, floor(y / checkerwidth));
- for(x=0; x<ibuf->x; x++, rect+=4) {
+ for(x=0; x<ibuf->x; x++) {
if (x % checkerwidth == 0) dark *= -1;
- if (dark > 0) {
- rect[0] = rect[1] = rect[2] = 64;
- rect[3] = 255;
- } else {
- rect[0] = rect[1] = rect[2] = 150;
- rect[3] = 255;
+ if (floatbuf) {
+ if (dark > 0) {
+ rect_float[0] = rect_float[1] = rect_float[2] = 0.25;
+ rect_float[3] = 1.0;
+ } else {
+ rect_float[0] = rect_float[1] = rect_float[2] = 0.58;
+ rect_float[3] = 1.0;
+ }
+ rect_float+=4;
+ }
+ else {
+ if (dark > 0) {
+ rect[0] = rect[1] = rect[2] = 64;
+ rect[3] = 255;
+ } else {
+ rect[0] = rect[1] = rect[2] = 150;
+ rect[3] = 255;
+ }
+ rect += 4;
}
}
}
/* 2nd pass, colored + */
- rect= (unsigned char*)ibuf->rect;
+ if (floatbuf) rect_float= (float*)ibuf->rect_float;
+ else rect= (unsigned char*)ibuf->rect;
for(y=0; y<ibuf->y; y++) {
hoffs = 0.125 * floor(y / checkerwidth);
- for(x=0; x<ibuf->x; x++, rect+=4) {
+ for(x=0; x<ibuf->x; x++) {
h = 0.125 * floor(x / checkerwidth);
if ((fabs((x % checkerwidth) - (checkerwidth / 2)) < 4) &&
@@ -426,22 +472,44 @@ static ImBuf *add_ibuf_size(int width, int height, char *name, short uvtestgrid,
hue = fmod(fabs(h-hoffs), 1.0);
hsv_to_rgb(hue, s, v, &r, &g, &b);
- rect[0]= (char)(r * 255.0);
- rect[1]= (char)(g * 255.0);
- rect[2]= (char)(b * 255.0);
- rect[3]= 255;
+ if (floatbuf) {
+ rect_float[0]= r;
+ rect_float[1]= g;
+ rect_float[2]= b;
+ rect_float[3]= 1.0;
+ }
+ else {
+ rect[0]= (char)(r * 255.0);
+ rect[1]= (char)(g * 255.0);
+ rect[2]= (char)(b * 255.0);
+ rect[3]= 255;
+ }
}
}
-
+
+ if (floatbuf)
+ rect_float+=4;
+ else
+ rect+=4;
}
}
} else { /* blank image */
for(y=0; y<ibuf->y; y++) {
- for(x=0; x<ibuf->x; x++, rect+=4) {
- rect[0]= (char)(color[0] * 255.0);
- rect[1]= (char)(color[1] * 255.0);
- rect[2]= (char)(color[2] * 255.0);
- rect[3]= (char)(color[3] * 255.0);
+ for(x=0; x<ibuf->x; x++) {
+ if (floatbuf) {
+ rect_float[0]= color[0];
+ rect_float[1]= color[1];
+ rect_float[2]= color[2];
+ rect_float[3]= color[3];
+ rect_float+=4;
+ }
+ else {
+ rect[0]= (char)(color[0] * 255.0);
+ rect[1]= (char)(color[1] * 255.0);
+ rect[2]= (char)(color[2] * 255.0);
+ rect[3]= (char)(color[3] * 255.0);
+ rect+=4;
+ }
}
}
}
@@ -449,7 +517,7 @@ static ImBuf *add_ibuf_size(int width, int height, char *name, short uvtestgrid,
}
/* adds new image block, creates ImBuf and initializes color */
-Image *BKE_add_image_size(int width, int height, char *name, short uvtestgrid, float color[4])
+Image *BKE_add_image_size(int width, int height, char *name, int floatbuf, short uvtestgrid, float color[4])
{
Image *ima;
@@ -464,7 +532,7 @@ Image *BKE_add_image_size(int width, int height, char *name, short uvtestgrid, f
ima->gen_y= height;
ima->gen_type= uvtestgrid;
- ibuf= add_ibuf_size(width, height, name, uvtestgrid, color);
+ ibuf= add_ibuf_size(width, height, name, floatbuf, uvtestgrid, color);
image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
ima->ok= IMA_OK_LOADED;
@@ -515,7 +583,7 @@ void tag_image_time(Image *ima)
ima->lastused = (int)PIL_check_seconds_timer();
}
-void tag_all_images_time()
+static void tag_all_images_time()
{
Image *ima;
int ctime = (int)PIL_check_seconds_timer();
@@ -551,7 +619,7 @@ void free_old_images()
This gives textures a "second chance" to be used before dying.
*/
if(ima->bindcode || ima->repbind) {
- //XXX free_realtime_image(ima);
+ GPU_free_image(ima);
ima->lastused = ctime;
}
/* Otherwise, just kill the buffers */
@@ -563,6 +631,47 @@ void free_old_images()
}
}
+static uintptr_t image_mem_size(Image *ima)
+{
+ ImBuf *ibuf, *ibufm;
+ int level;
+ uintptr_t size = 0;
+
+ size= 0;
+ for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next) {
+ if(ibuf->rect) size += MEM_allocN_len(ibuf->rect);
+ else if(ibuf->rect_float) size += MEM_allocN_len(ibuf->rect_float);
+
+ for(level=0; level<IB_MIPMAP_LEVELS; level++) {
+ ibufm= ibuf->mipmap[level];
+ if(ibufm) {
+ if(ibufm->rect) size += MEM_allocN_len(ibufm->rect);
+ else if(ibufm->rect_float) size += MEM_allocN_len(ibufm->rect_float);
+ }
+ }
+ }
+
+ return size;
+}
+
+void BKE_image_print_memlist(void)
+{
+ Image *ima;
+ uintptr_t size, totsize= 0;
+
+ for(ima= G.main->image.first; ima; ima= ima->id.next)
+ totsize += image_mem_size(ima);
+
+ printf("\ntotal image memory len: %.3lf MB\n", (double)totsize/(double)(1024*1024));
+
+ for(ima= G.main->image.first; ima; ima= ima->id.next) {
+ size= image_mem_size(ima);
+
+ if(size)
+ printf("%s len: %.3f MB\n", ima->id.name+2, (double)size/(double)(1024*1024));
+ }
+}
+
void BKE_image_free_all_textures(void)
{
Tex *tex;
@@ -740,17 +849,13 @@ void BKE_add_image_extension(char *string, int imtype)
if(!BLI_testextensie(string, ".tga"))
extension= ".tga";
}
- else if(ELEM5(imtype, R_MOVIE, R_AVICODEC, R_AVIRAW, R_AVIJPEG, R_JPEG90)) {
- if(!( BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
- extension= ".jpg";
- }
else if(imtype==R_BMP) {
if(!BLI_testextensie(string, ".bmp"))
extension= ".bmp";
}
else if(G.have_libtiff && (imtype==R_TIFF)) {
- if(!BLI_testextensie(string, ".tif"))
- extension= ".tif";
+ if(!BLI_testextensie(string, ".tif") &&
+ !BLI_testextensie(string, ".tiff")) extension= ".tif";
}
#ifdef WITH_OPENEXR
else if( ELEM(imtype, R_OPENEXR, R_MULTILAYER)) {
@@ -766,10 +871,14 @@ void BKE_add_image_extension(char *string, int imtype)
if (!BLI_testextensie(string, ".dpx"))
extension= ".dpx";
}
- else { /* targa default */
+ else if(imtype==R_TARGA) {
if(!BLI_testextensie(string, ".tga"))
extension= ".tga";
}
+ else { // R_MOVIE, R_AVICODEC, R_AVIRAW, R_AVIJPEG, R_JPEG90, R_QUICKTIME etc
+ if(!( BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
+ extension= ".jpg";
+ }
strcat(string, extension);
}
@@ -799,8 +908,13 @@ static void stampdata(StampData *stamp_data, int do_prefix)
#endif /* WIN32 */
if (G.scene->r.stamp & R_STAMP_FILENAME) {
- if (do_prefix) sprintf(stamp_data->file, "File %s", G.sce);
- else sprintf(stamp_data->file, "%s", G.sce);
+ if (G.relbase_valid) {
+ if (do_prefix) sprintf(stamp_data->file, "File %s", G.sce);
+ else sprintf(stamp_data->file, "%s", G.sce);
+ } else {
+ if (do_prefix) strcpy(stamp_data->file, "File <untitled>");
+ else strcpy(stamp_data->file, "<untitled>");
+ }
stamp_data->note[0] = '\0';
} else {
stamp_data->file[0] = '\0';
@@ -877,8 +991,11 @@ static void stampdata(StampData *stamp_data, int do_prefix)
}
if (G.scene->r.stamp & R_STAMP_CAMERA) {
- if (do_prefix) sprintf(stamp_data->camera, "Camera %s", ((Camera *) G.scene->camera)->id.name+2);
- else sprintf(stamp_data->camera, "%s", ((Camera *) G.scene->camera)->id.name+2);
+ if (G.scene->camera) strcpy(text, ((Camera *) G.scene->camera)->id.name+2);
+ else strcpy(text, "<none>");
+
+ if (do_prefix) sprintf(stamp_data->camera, "Camera %s", text);
+ else sprintf(stamp_data->camera, "%s", text);
} else {
stamp_data->camera[0] = '\0';
}
@@ -903,7 +1020,7 @@ static void stampdata(StampData *stamp_data, int do_prefix)
}
}
-void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
+void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height, int channels)
{
struct StampData stamp_data;
@@ -951,7 +1068,7 @@ void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
/* Top left corner */
text_width = BMF_GetStringWidth(font, stamp_data.file);
buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
- BMF_DrawStringBuf(font, stamp_data.file, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
+ BMF_DrawStringBuf(font, stamp_data.file, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
y -= font_height+2; /* Top and bottom 1 pix padding each */
}
@@ -959,7 +1076,7 @@ void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
if (stamp_data.note[0]) {
text_width = BMF_GetStringWidth(font, stamp_data.note);
buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
- BMF_DrawStringBuf(font, stamp_data.note, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
+ BMF_DrawStringBuf(font, stamp_data.note, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
y -= font_height+2; /* Top and bottom 1 pix padding each */
}
@@ -967,7 +1084,7 @@ void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
if (stamp_data.date[0]) {
text_width = BMF_GetStringWidth(font, stamp_data.date);
buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
- BMF_DrawStringBuf(font, stamp_data.date, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
+ BMF_DrawStringBuf(font, stamp_data.date, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
}
/* Bottom left corner, leaving space for timing */
@@ -976,7 +1093,7 @@ void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
y = font_height+2+1; /* 2 for padding in TIME|FRAME fields below and 1 for padding in this one */
text_width = BMF_GetStringWidth(font, stamp_data.marker);
buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
- BMF_DrawStringBuf(font, stamp_data.marker, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
+ BMF_DrawStringBuf(font, stamp_data.marker, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
}
/* Left bottom corner */
@@ -985,7 +1102,7 @@ void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
y = 1;
text_width = BMF_GetStringWidth(font, stamp_data.time);
buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
- BMF_DrawStringBuf(font, stamp_data.time, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
+ BMF_DrawStringBuf(font, stamp_data.time, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
x += text_width+text_pad+2; /* Both sides have 1 pix additional padding each */
}
@@ -995,7 +1112,7 @@ void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
if (!stamp_data.time[0]) x = 1;
y = 1;
buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
- BMF_DrawStringBuf(font, stamp_data.frame, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
+ BMF_DrawStringBuf(font, stamp_data.frame, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
}
if (stamp_data.camera[0]) {
@@ -1004,7 +1121,7 @@ void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
x = (width/2) - (BMF_GetStringWidth(font, stamp_data.camera)/2);
y = 1;
buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
- BMF_DrawStringBuf(font, stamp_data.camera, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
+ BMF_DrawStringBuf(font, stamp_data.camera, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
}
if (stamp_data.scene[0]) {
@@ -1013,7 +1130,7 @@ void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
x = width - (text_width+1+text_pad);
y = 1;
buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
- BMF_DrawStringBuf(font, stamp_data.scene, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
+ BMF_DrawStringBuf(font, stamp_data.scene, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
}
if (stamp_data.strip[0]) {
@@ -1022,7 +1139,7 @@ void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height)
x = width - (text_width+1+text_pad);
y = height - font_height - 1;
buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
- BMF_DrawStringBuf(font, stamp_data.strip, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height);
+ BMF_DrawStringBuf(font, stamp_data.strip, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
}
}
@@ -1070,6 +1187,9 @@ int BKE_write_ibuf(ImBuf *ibuf, char *name, int imtype, int subimtype, int quali
}
else if ((G.have_libtiff) && (imtype==R_TIFF)) {
ibuf->ftype= TIF;
+
+ if(subimtype & R_TIFF_16BIT)
+ ibuf->ftype |= TIF_16BIT;
}
#ifdef WITH_OPENEXR
else if (imtype==R_OPENEXR || imtype==R_MULTILAYER) {
@@ -1121,23 +1241,16 @@ int BKE_write_ibuf(ImBuf *ibuf, char *name, int imtype, int subimtype, int quali
void BKE_makepicstring(char *string, char *base, int frame, int imtype)
{
- short i, len, digits= 4; /* digits in G.scene? */
- char num[10];
-
if (string==NULL) return;
BLI_strncpy(string, base, FILE_MAX - 10); /* weak assumption */
- BLI_convertstringcode(string, G.sce, frame);
-
- len= strlen(string);
-
- i= digits - sprintf(num, "%d", frame);
- for(; i>0; i--){
- string[len]= '0';
- len++;
- }
- string[len]= 0;
- strcat(string, num);
+
+ /* if we dont have any #'s to insert numbers into, use 4 numbers by default */
+ if (strchr(string, '#')==NULL)
+ strcat(string, "####"); /* 4 numbers */
+
+ BLI_convertstringcode(string, G.sce);
+ BLI_convertstringframe(string, frame);
if(G.scene->r.scemode & R_EXTENSION)
BKE_add_image_extension(string, imtype);
@@ -1373,9 +1486,11 @@ static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
BLI_strncpy(name, ima->name, sizeof(name));
if(ima->id.lib)
- BLI_convertstringcode(name, ima->id.lib->filename, frame);
+ BLI_convertstringcode(name, ima->id.lib->filename);
else
- BLI_convertstringcode(name, G.sce, frame);
+ BLI_convertstringcode(name, G.sce);
+
+ BLI_convertstringframe(name, frame); /* TODO - should this be here? */
/* read ibuf */
ibuf = IMB_loadiffname(name, IB_rect|IB_multilayer);
@@ -1391,13 +1506,17 @@ static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
ibuf= NULL;
}
else {
- image_assign_ibuf(ima, ibuf, 0, frame);
image_initialize_after_load(ima, ibuf);
+ image_assign_ibuf(ima, ibuf, 0, frame);
}
#else
- image_assign_ibuf(ima, ibuf, 0, frame);
image_initialize_after_load(ima, ibuf);
+ image_assign_ibuf(ima, ibuf, 0, frame);
#endif
+
+ if(ima->flag & IMA_DO_PREMUL)
+ converttopremul(ibuf);
+
}
else
ima->ok= 0;
@@ -1432,8 +1551,9 @@ static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int f
// if(oldrr) printf("freed previous result %p\n", oldrr);
if(oldrr) RE_FreeRenderResult(oldrr);
}
- else
+ else {
ima->rr= oldrr;
+ }
}
if(ima->rr) {
@@ -1448,8 +1568,8 @@ static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int f
ibuf->mall= IB_rectfloat;
ibuf->channels= rpass->channels;
- image_assign_ibuf(ima, ibuf, iuser->multi_index, frame);
image_initialize_after_load(ima, ibuf);
+ image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:0, frame);
}
// else printf("pass not found\n");
@@ -1475,9 +1595,9 @@ static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
BLI_strncpy(str, ima->name, FILE_MAX);
if(ima->id.lib)
- BLI_convertstringcode(str, ima->id.lib->filename, 0);
+ BLI_convertstringcode(str, ima->id.lib->filename);
else
- BLI_convertstringcode(str, G.sce, 0);
+ BLI_convertstringcode(str, G.sce);
ima->anim = openanim(str, IB_cmap | IB_rect);
@@ -1495,8 +1615,8 @@ static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
ibuf = IMB_anim_absolute(ima->anim, fra);
if(ibuf) {
- image_assign_ibuf(ima, ibuf, 0, frame);
image_initialize_after_load(ima, ibuf);
+ image_assign_ibuf(ima, ibuf, 0, frame);
}
else
ima->ok= 0;
@@ -1515,6 +1635,7 @@ static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
{
struct ImBuf *ibuf;
char str[FILE_MAX];
+ int assign = 0;
/* always ensure clean ima */
image_free_buffers(ima);
@@ -1528,9 +1649,11 @@ static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
/* get the right string */
BLI_strncpy(str, ima->name, sizeof(str));
if(ima->id.lib)
- BLI_convertstringcode(str, ima->id.lib->filename, cfra);
+ BLI_convertstringcode(str, ima->id.lib->filename);
else
- BLI_convertstringcode(str, G.sce, cfra);
+ BLI_convertstringcode(str, G.sce);
+
+ BLI_convertstringframe(str, cfra);
/* read ibuf */
ibuf = IMB_loadiffname(str, IB_rect|IB_multilayer|IB_imginfo);
@@ -1545,8 +1668,8 @@ static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
ibuf= NULL;
}
else {
- image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
image_initialize_after_load(ima, ibuf);
+ assign= 1;
/* check if the image is a font image... */
detectBitmapFont(ibuf);
@@ -1562,6 +1685,9 @@ static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
else
ima->ok= 0;
+ if(assign)
+ image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
+
if(iuser)
iuser->ok= ima->ok;
@@ -1585,12 +1711,13 @@ static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
if(rpass) {
ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
- image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
image_initialize_after_load(ima, ibuf);
ibuf->rect_float= rpass->rect;
ibuf->flags |= IB_rectfloat;
ibuf->channels= rpass->channels;
+
+ image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
}
}
@@ -1609,31 +1736,38 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser)
{
RenderResult *rr= RE_GetResult(RE_GetRender(G.scene->id.name));
- if(rr && iuser) {
+ if(rr) {
RenderResult rres;
float *rectf;
unsigned int *rect;
- int channels= 4, layer= iuser->layer;
+ float dither;
+ int channels, layer, pass;
+
+ channels= 4;
+ layer= (iuser)? iuser->layer: 0;
+ pass= (iuser)? iuser->pass: 0;
/* this gives active layer, composite or seqence result */
RE_GetResultImage(RE_GetRender(G.scene->id.name), &rres);
rect= (unsigned int *)rres.rect32;
rectf= rres.rectf;
-
+ dither= G.scene->r.dither_intensity;
+
/* get compo/seq result by default */
if(rr->rectf && layer==0);
else if(rr->layers.first) {
- RenderLayer *rl= BLI_findlink(&rr->layers, iuser->layer-(rr->rectf?1:0));
+ RenderLayer *rl= BLI_findlink(&rr->layers, layer-(rr->rectf?1:0));
if(rl) {
/* there's no combined pass, is in renderlayer itself */
- if(iuser->pass==0) {
+ if(pass==0) {
rectf= rl->rectf;
}
else {
- RenderPass *rpass= BLI_findlink(&rl->passes, iuser->pass-1);
+ RenderPass *rpass= BLI_findlink(&rl->passes, pass-1);
if(rpass) {
channels= rpass->channels;
rectf= rpass->rect;
+ dither= 0.0f; /* don't dither passes */
}
}
}
@@ -1658,6 +1792,9 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser)
ibuf->rect_float= rectf;
ibuf->flags |= IB_rectfloat;
ibuf->channels= channels;
+ ibuf->zbuf_float= rres.rectz;
+ ibuf->flags |= IB_zbuffloat;
+ ibuf->dither= dither;
ima->ok= IMA_OK_LOADED;
return ibuf;
@@ -1667,118 +1804,171 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser)
return NULL;
}
-/* Checks optional ImageUser and verifies/creates ImBuf. */
-/* returns ibuf */
-ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
+static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
{
- ImBuf *ibuf= NULL;
- float color[] = {0, 0, 0, 1};
+ ImBuf *ibuf = NULL;
+ int frame = 0, index = 0;
- /* quick reject tests */
- if(ima==NULL)
- return NULL;
- if(iuser) {
- if(iuser->ok==0)
- return NULL;
- }
- else if(ima->ok==0)
- return NULL;
-
- BLI_lock_thread(LOCK_IMAGE);
-
- /* handle image source and types */
+ /* see if we already have an appropriate ibuf, with image source and type */
if(ima->source==IMA_SRC_MOVIE) {
- /* source is from single file, use flipbook to store ibuf */
- int frame= iuser?iuser->framenr:ima->lastframe;
-
+ frame= iuser?iuser->framenr:ima->lastframe;
ibuf= image_get_ibuf(ima, 0, frame);
- if(ibuf==NULL)
- ibuf= image_load_movie_file(ima, iuser, frame);
}
else if(ima->source==IMA_SRC_SEQUENCE) {
-
if(ima->type==IMA_TYPE_IMAGE) {
- /* regular files, ibufs in flipbook, allows saving */
- int frame= iuser?iuser->framenr:ima->lastframe;
-
+ frame= iuser?iuser->framenr:ima->lastframe;
ibuf= image_get_ibuf(ima, 0, frame);
- if(ibuf==NULL)
- ibuf= image_load_sequence_file(ima, iuser, frame);
- else
- BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
}
- /* no else; on load the ima type can change */
- if(ima->type==IMA_TYPE_MULTILAYER) {
- /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
- int frame= iuser?iuser->framenr:ima->lastframe;
- int index= iuser?iuser->multi_index:IMA_NO_INDEX;
-
+ else if(ima->type==IMA_TYPE_MULTILAYER) {
+ frame= iuser?iuser->framenr:ima->lastframe;
+ index= iuser?iuser->multi_index:IMA_NO_INDEX;
ibuf= image_get_ibuf(ima, index, frame);
- if(G.rt) printf("seq multi fra %d id %d ibuf %p %s\n", frame, index, ibuf, ima->id.name);
- if(ibuf==NULL)
- ibuf= image_load_sequence_multilayer(ima, iuser, frame);
- else
- BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
}
-
}
else if(ima->source==IMA_SRC_FILE) {
-
- if(ima->type==IMA_TYPE_IMAGE) {
+ if(ima->type==IMA_TYPE_IMAGE)
ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
- if(ibuf==NULL)
- ibuf= image_load_image_file(ima, iuser, G.scene->r.cfra); /* cfra only for '#', this global is OK */
- }
- /* no else; on load the ima type can change */
- if(ima->type==IMA_TYPE_MULTILAYER) {
- /* keeps render result, stores ibufs in listbase, allows saving */
+ else if(ima->type==IMA_TYPE_MULTILAYER)
ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
- if(ibuf==NULL)
- ibuf= image_get_ibuf_multilayer(ima, iuser);
- }
-
}
else if(ima->source == IMA_SRC_GENERATED) {
- /* generated is: ibuf is allocated dynamically */
ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
-
- if(ibuf==NULL) {
- if(ima->type==IMA_TYPE_VERSE) {
- /* todo */
- }
- else { /* always fall back to IMA_TYPE_UV_TEST */
- /* UV testgrid or black or solid etc */
- if(ima->gen_x==0) ima->gen_x= 256;
- if(ima->gen_y==0) ima->gen_y= 256;
- ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, ima->gen_type, color);
- image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
- ima->ok= IMA_OK_LOADED;
- }
- }
}
else if(ima->source == IMA_SRC_VIEWER) {
if(ima->type==IMA_TYPE_R_RESULT) {
- /* always verify entirely */
- ibuf= image_get_render_result(ima, iuser);
+ /* always verify entirely, not that this shouldn't happen
+ * during render anyway */
}
else if(ima->type==IMA_TYPE_COMPOSITE) {
- int frame= iuser?iuser->framenr:0;
-
- /* Composite Viewer, all handled in compositor */
+ frame= iuser?iuser->framenr:0;
ibuf= image_get_ibuf(ima, 0, frame);
- if(ibuf==NULL) {
- /* fake ibuf, will be filled in compositor */
- ibuf= IMB_allocImBuf(256, 256, 32, IB_rect, 0);
- image_assign_ibuf(ima, ibuf, 0, frame);
+ }
+ }
+
+ *frame_r = frame;
+ *index_r = index;
+
+ return ibuf;
+}
+
+/* Checks optional ImageUser and verifies/creates ImBuf. */
+/* returns ibuf */
+ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
+{
+ ImBuf *ibuf= NULL;
+ float color[] = {0, 0, 0, 1};
+ int frame= 0, index= 0;
+
+ /* This function is intended to be thread-safe. It postpones the mutex lock
+ * until it needs to load the image, if the image is already there it
+ * should just get the pointer and return. The reason is that a lot of mutex
+ * locks appears to be very slow on certain multicore macs, causing a render
+ * with image textures to actually slow down as more threads are used.
+ *
+ * Note that all the image loading functions should also make sure they do
+ * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
+ * That means, the last two steps must be, 1) add the ibuf to the list and
+ * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
+
+ /* quick reject tests */
+ if(ima==NULL)
+ return NULL;
+ if(iuser) {
+ if(iuser->ok==0)
+ return NULL;
+ }
+ else if(ima->ok==0)
+ return NULL;
+
+ /* try to get the ibuf without locking */
+ ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
+
+ if(ibuf == NULL) {
+ /* couldn't get ibuf and image is not ok, so let's lock and try to
+ * load the image */
+ BLI_lock_thread(LOCK_IMAGE);
+
+ /* need to check ok flag and loading ibuf again, because the situation
+ * might have changed in the meantime */
+ if(iuser) {
+ if(iuser->ok==0) {
+ BLI_unlock_thread(LOCK_IMAGE);
+ return NULL;
}
}
+ else if(ima->ok==0) {
+ BLI_unlock_thread(LOCK_IMAGE);
+ return NULL;
+ }
+
+ ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
+
+ if(ibuf == NULL) {
+ /* we are sure we have to load the ibuf, using source and type */
+ if(ima->source==IMA_SRC_MOVIE) {
+ /* source is from single file, use flipbook to store ibuf */
+ ibuf= image_load_movie_file(ima, iuser, frame);
+ }
+ else if(ima->source==IMA_SRC_SEQUENCE) {
+ if(ima->type==IMA_TYPE_IMAGE) {
+ /* regular files, ibufs in flipbook, allows saving */
+ ibuf= image_load_sequence_file(ima, iuser, frame);
+ }
+ /* no else; on load the ima type can change */
+ if(ima->type==IMA_TYPE_MULTILAYER) {
+ /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
+ ibuf= image_load_sequence_multilayer(ima, iuser, frame);
+ }
+
+ if(ibuf)
+ BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
+ }
+ else if(ima->source==IMA_SRC_FILE) {
+
+ if(ima->type==IMA_TYPE_IMAGE)
+ ibuf= image_load_image_file(ima, iuser, G.scene->r.cfra); /* cfra only for '#', this global is OK */
+ /* no else; on load the ima type can change */
+ if(ima->type==IMA_TYPE_MULTILAYER)
+ /* keeps render result, stores ibufs in listbase, allows saving */
+ ibuf= image_get_ibuf_multilayer(ima, iuser);
+
+ }
+ else if(ima->source == IMA_SRC_GENERATED) {
+ /* generated is: ibuf is allocated dynamically */
+ if(ima->type==IMA_TYPE_VERSE) {
+ /* todo */
+ }
+ else { /* always fall back to IMA_TYPE_UV_TEST */
+ /* UV testgrid or black or solid etc */
+ if(ima->gen_x==0) ima->gen_x= 256;
+ if(ima->gen_y==0) ima->gen_y= 256;
+ ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 0, ima->gen_type, color);
+ image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
+ ima->ok= IMA_OK_LOADED;
+ }
+ }
+ else if(ima->source == IMA_SRC_VIEWER) {
+ if(ima->type==IMA_TYPE_R_RESULT) {
+ /* always verify entirely */
+ ibuf= image_get_render_result(ima, iuser);
+ }
+ else if(ima->type==IMA_TYPE_COMPOSITE) {
+ /* Composite Viewer, all handled in compositor */
+ /* fake ibuf, will be filled in compositor */
+ ibuf= IMB_allocImBuf(256, 256, 32, IB_rect, 0);
+ image_assign_ibuf(ima, ibuf, 0, frame);
+ }
+ }
+ }
+
+ BLI_unlock_thread(LOCK_IMAGE);
}
+ /* we assuming that if it is not rendering, it's also not multithreaded
+ * (a somewhat weak assumption) */
if(G.rendering==0)
tag_image_time(ima);
- BLI_unlock_thread(LOCK_IMAGE);
-
return ibuf;
}
diff --git a/source/blender/blenkernel/intern/implicit.c b/source/blender/blenkernel/intern/implicit.c
new file mode 100644
index 00000000000..93e35a4db06
--- /dev/null
+++ b/source/blender/blenkernel/intern/implicit.c
@@ -0,0 +1,1709 @@
+/* implicit.c
+*
+*
+* ***** BEGIN GPL LICENSE BLOCK *****
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 2
+* of the License, or (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software Foundation,
+* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*
+* The Original Code is Copyright (C) Blender Foundation
+* All rights reserved.
+*
+* The Original Code is: all of this file.
+*
+* Contributor(s): none yet.
+*
+* ***** END GPL LICENSE BLOCK *****
+*/
+
+#include "MEM_guardedalloc.h"
+
+#include "BKE_cloth.h"
+
+#include "DNA_cloth_types.h"
+#include "DNA_scene_types.h"
+
+#include "BKE_effect.h"
+#include "BKE_global.h"
+#include "BKE_cloth.h"
+#include "BKE_utildefines.h"
+
+#ifdef _WIN32
+#include <windows.h>
+static LARGE_INTEGER _itstart, _itend;
+static LARGE_INTEGER ifreq;
+void itstart(void)
+{
+ static int first = 1;
+ if(first) {
+ QueryPerformanceFrequency(&ifreq);
+ first = 0;
+ }
+ QueryPerformanceCounter(&_itstart);
+}
+void itend(void)
+{
+ QueryPerformanceCounter(&_itend);
+}
+double itval()
+{
+ return ((double)_itend.QuadPart -
+ (double)_itstart.QuadPart)/((double)ifreq.QuadPart);
+}
+#else
+#include <sys/time.h>
+// intrinsics need better compile flag checking
+// #include <xmmintrin.h>
+// #include <pmmintrin.h>
+// #include <pthread.h>
+
+ static struct timeval _itstart, _itend;
+ static struct timezone itz;
+ void itstart(void)
+{
+ gettimeofday(&_itstart, &itz);
+}
+void itend(void)
+{
+ gettimeofday(&_itend,&itz);
+}
+double itval()
+{
+ double t1, t2;
+ t1 = (double)_itstart.tv_sec + (double)_itstart.tv_usec/(1000*1000);
+ t2 = (double)_itend.tv_sec + (double)_itend.tv_usec/(1000*1000);
+ return t2-t1;
+}
+#endif
+
+static float I[3][3] = {{1,0,0},{0,1,0},{0,0,1}};
+static float ZERO[3][3] = {{0,0,0}, {0,0,0}, {0,0,0}};
+
+/*
+#define C99
+#ifdef C99
+#defineDO_INLINE inline
+#else
+#defineDO_INLINE static
+#endif
+*/
+struct Cloth;
+
+//////////////////////////////////////////
+/* fast vector / matrix library, enhancements are welcome :) -dg */
+/////////////////////////////////////////
+
+/* DEFINITIONS */
+typedef float lfVector[3];
+typedef struct fmatrix3x3 {
+ float m[3][3]; /* 3x3 matrix */
+ unsigned int c,r; /* column and row number */
+ int pinned; /* is this vertex allowed to move? */
+ float n1,n2,n3; /* three normal vectors for collision constrains */
+ unsigned int vcount; /* vertex count */
+ unsigned int scount; /* spring count */
+} fmatrix3x3;
+
+///////////////////////////
+// float[3] vector
+///////////////////////////
+/* simple vector code */
+/* STATUS: verified */
+DO_INLINE void mul_fvector_S(float to[3], float from[3], float scalar)
+{
+ to[0] = from[0] * scalar;
+ to[1] = from[1] * scalar;
+ to[2] = from[2] * scalar;
+}
+/* simple cross product */
+/* STATUS: verified */
+DO_INLINE void cross_fvector(float to[3], float vectorA[3], float vectorB[3])
+{
+ to[0] = vectorA[1] * vectorB[2] - vectorA[2] * vectorB[1];
+ to[1] = vectorA[2] * vectorB[0] - vectorA[0] * vectorB[2];
+ to[2] = vectorA[0] * vectorB[1] - vectorA[1] * vectorB[0];
+}
+/* simple v^T * v product ("outer product") */
+/* STATUS: HAS TO BE verified (*should* work) */
+DO_INLINE void mul_fvectorT_fvector(float to[3][3], float vectorA[3], float vectorB[3])
+{
+ mul_fvector_S(to[0], vectorB, vectorA[0]);
+ mul_fvector_S(to[1], vectorB, vectorA[1]);
+ mul_fvector_S(to[2], vectorB, vectorA[2]);
+}
+/* simple v^T * v product with scalar ("outer product") */
+/* STATUS: HAS TO BE verified (*should* work) */
+DO_INLINE void mul_fvectorT_fvectorS(float to[3][3], float vectorA[3], float vectorB[3], float aS)
+{
+ mul_fvectorT_fvector(to, vectorA, vectorB);
+
+ mul_fvector_S(to[0], to[0], aS);
+ mul_fvector_S(to[1], to[1], aS);
+ mul_fvector_S(to[2], to[2], aS);
+}
+
+
+/* printf vector[3] on console: for debug output */
+void print_fvector(float m3[3])
+{
+ printf("%f\n%f\n%f\n\n",m3[0],m3[1],m3[2]);
+}
+
+///////////////////////////
+// long float vector float (*)[3]
+///////////////////////////
+/* print long vector on console: for debug output */
+DO_INLINE void print_lfvector(float (*fLongVector)[3], unsigned int verts)
+{
+ unsigned int i = 0;
+ for(i = 0; i < verts; i++)
+ {
+ print_fvector(fLongVector[i]);
+ }
+}
+/* create long vector */
+DO_INLINE lfVector *create_lfvector(unsigned int verts)
+{
+ // TODO: check if memory allocation was successfull */
+ return (lfVector *)MEM_callocN (verts * sizeof(lfVector), "cloth_implicit_alloc_vector");
+ // return (lfVector *)cloth_aligned_malloc(&MEMORY_BASE, verts * sizeof(lfVector));
+}
+/* delete long vector */
+DO_INLINE void del_lfvector(float (*fLongVector)[3])
+{
+ if (fLongVector != NULL)
+ {
+ MEM_freeN (fLongVector);
+ // cloth_aligned_free(&MEMORY_BASE, fLongVector);
+ }
+}
+/* copy long vector */
+DO_INLINE void cp_lfvector(float (*to)[3], float (*from)[3], unsigned int verts)
+{
+ memcpy(to, from, verts * sizeof(lfVector));
+}
+/* init long vector with float[3] */
+DO_INLINE void init_lfvector(float (*fLongVector)[3], float vector[3], unsigned int verts)
+{
+ unsigned int i = 0;
+ for(i = 0; i < verts; i++)
+ {
+ VECCOPY(fLongVector[i], vector);
+ }
+}
+/* zero long vector with float[3] */
+DO_INLINE void zero_lfvector(float (*to)[3], unsigned int verts)
+{
+ memset(to, 0.0f, verts * sizeof(lfVector));
+}
+/* multiply long vector with scalar*/
+DO_INLINE void mul_lfvectorS(float (*to)[3], float (*fLongVector)[3], float scalar, unsigned int verts)
+{
+ unsigned int i = 0;
+
+ for(i = 0; i < verts; i++)
+ {
+ mul_fvector_S(to[i], fLongVector[i], scalar);
+ }
+}
+/* multiply long vector with scalar*/
+/* A -= B * float */
+DO_INLINE void submul_lfvectorS(float (*to)[3], float (*fLongVector)[3], float scalar, unsigned int verts)
+{
+ unsigned int i = 0;
+ for(i = 0; i < verts; i++)
+ {
+ VECSUBMUL(to[i], fLongVector[i], scalar);
+ }
+}
+/* dot product for big vector */
+DO_INLINE float dot_lfvector(float (*fLongVectorA)[3], float (*fLongVectorB)[3], unsigned int verts)
+{
+ long i = 0;
+ float temp = 0.0;
+// schedule(guided, 2)
+#pragma omp parallel for reduction(+: temp)
+ for(i = 0; i < (long)verts; i++)
+ {
+ temp += INPR(fLongVectorA[i], fLongVectorB[i]);
+ }
+ return temp;
+}
+/* A = B + C --> for big vector */
+DO_INLINE void add_lfvector_lfvector(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], unsigned int verts)
+{
+ unsigned int i = 0;
+
+ for(i = 0; i < verts; i++)
+ {
+ VECADD(to[i], fLongVectorA[i], fLongVectorB[i]);
+ }
+
+}
+/* A = B + C * float --> for big vector */
+DO_INLINE void add_lfvector_lfvectorS(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], float bS, unsigned int verts)
+{
+ unsigned int i = 0;
+
+ for(i = 0; i < verts; i++)
+ {
+ VECADDS(to[i], fLongVectorA[i], fLongVectorB[i], bS);
+
+ }
+}
+/* A = B * float + C * float --> for big vector */
+DO_INLINE void add_lfvectorS_lfvectorS(float (*to)[3], float (*fLongVectorA)[3], float aS, float (*fLongVectorB)[3], float bS, unsigned int verts)
+{
+ unsigned int i = 0;
+
+ for(i = 0; i < verts; i++)
+ {
+ VECADDSS(to[i], fLongVectorA[i], aS, fLongVectorB[i], bS);
+ }
+}
+/* A = B - C * float --> for big vector */
+DO_INLINE void sub_lfvector_lfvectorS(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], float bS, unsigned int verts)
+{
+ unsigned int i = 0;
+ for(i = 0; i < verts; i++)
+ {
+ VECSUBS(to[i], fLongVectorA[i], fLongVectorB[i], bS);
+ }
+
+}
+/* A = B - C --> for big vector */
+DO_INLINE void sub_lfvector_lfvector(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], unsigned int verts)
+{
+ unsigned int i = 0;
+
+ for(i = 0; i < verts; i++)
+ {
+ VECSUB(to[i], fLongVectorA[i], fLongVectorB[i]);
+ }
+
+}
+///////////////////////////
+// 3x3 matrix
+///////////////////////////
+/* printf 3x3 matrix on console: for debug output */
+void print_fmatrix(float m3[3][3])
+{
+ printf("%f\t%f\t%f\n",m3[0][0],m3[0][1],m3[0][2]);
+ printf("%f\t%f\t%f\n",m3[1][0],m3[1][1],m3[1][2]);
+ printf("%f\t%f\t%f\n\n",m3[2][0],m3[2][1],m3[2][2]);
+}
+
+/* copy 3x3 matrix */
+DO_INLINE void cp_fmatrix(float to[3][3], float from[3][3])
+{
+ // memcpy(to, from, sizeof (float) * 9);
+ VECCOPY(to[0], from[0]);
+ VECCOPY(to[1], from[1]);
+ VECCOPY(to[2], from[2]);
+}
+
+/* copy 3x3 matrix */
+DO_INLINE void initdiag_fmatrixS(float to[3][3], float aS)
+{
+ cp_fmatrix(to, ZERO);
+
+ to[0][0] = aS;
+ to[1][1] = aS;
+ to[2][2] = aS;
+}
+
+/* calculate determinant of 3x3 matrix */
+DO_INLINE float det_fmatrix(float m[3][3])
+{
+ return m[0][0]*m[1][1]*m[2][2] + m[1][0]*m[2][1]*m[0][2] + m[0][1]*m[1][2]*m[2][0]
+ -m[0][0]*m[1][2]*m[2][1] - m[0][1]*m[1][0]*m[2][2] - m[2][0]*m[1][1]*m[0][2];
+}
+
+DO_INLINE void inverse_fmatrix(float to[3][3], float from[3][3])
+{
+ unsigned int i, j;
+ float d;
+
+ if((d=det_fmatrix(from))==0)
+ {
+ printf("can't build inverse");
+ exit(0);
+ }
+ for(i=0;i<3;i++)
+ {
+ for(j=0;j<3;j++)
+ {
+ int i1=(i+1)%3;
+ int i2=(i+2)%3;
+ int j1=(j+1)%3;
+ int j2=(j+2)%3;
+ // reverse indexs i&j to take transpose
+ to[j][i] = (from[i1][j1]*from[i2][j2]-from[i1][j2]*from[i2][j1])/d;
+ /*
+ if(i==j)
+ to[i][j] = 1.0f / from[i][j];
+ else
+ to[i][j] = 0;
+ */
+ }
+ }
+
+}
+
+/* 3x3 matrix multiplied by a scalar */
+/* STATUS: verified */
+DO_INLINE void mul_fmatrix_S(float matrix[3][3], float scalar)
+{
+ mul_fvector_S(matrix[0], matrix[0],scalar);
+ mul_fvector_S(matrix[1], matrix[1],scalar);
+ mul_fvector_S(matrix[2], matrix[2],scalar);
+}
+
+/* a vector multiplied by a 3x3 matrix */
+/* STATUS: verified */
+DO_INLINE void mul_fvector_fmatrix(float *to, float *from, float matrix[3][3])
+{
+ to[0] = matrix[0][0]*from[0] + matrix[1][0]*from[1] + matrix[2][0]*from[2];
+ to[1] = matrix[0][1]*from[0] + matrix[1][1]*from[1] + matrix[2][1]*from[2];
+ to[2] = matrix[0][2]*from[0] + matrix[1][2]*from[1] + matrix[2][2]*from[2];
+}
+
+/* 3x3 matrix multiplied by a vector */
+/* STATUS: verified */
+DO_INLINE void mul_fmatrix_fvector(float *to, float matrix[3][3], float *from)
+{
+ to[0] = INPR(matrix[0],from);
+ to[1] = INPR(matrix[1],from);
+ to[2] = INPR(matrix[2],from);
+}
+/* 3x3 matrix multiplied by a 3x3 matrix */
+/* STATUS: verified */
+DO_INLINE void mul_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
+{
+ mul_fvector_fmatrix(to[0], matrixA[0],matrixB);
+ mul_fvector_fmatrix(to[1], matrixA[1],matrixB);
+ mul_fvector_fmatrix(to[2], matrixA[2],matrixB);
+}
+/* 3x3 matrix addition with 3x3 matrix */
+DO_INLINE void add_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
+{
+ VECADD(to[0], matrixA[0], matrixB[0]);
+ VECADD(to[1], matrixA[1], matrixB[1]);
+ VECADD(to[2], matrixA[2], matrixB[2]);
+}
+/* 3x3 matrix add-addition with 3x3 matrix */
+DO_INLINE void addadd_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
+{
+ VECADDADD(to[0], matrixA[0], matrixB[0]);
+ VECADDADD(to[1], matrixA[1], matrixB[1]);
+ VECADDADD(to[2], matrixA[2], matrixB[2]);
+}
+/* 3x3 matrix sub-addition with 3x3 matrix */
+DO_INLINE void addsub_fmatrixS_fmatrixS(float to[3][3], float matrixA[3][3], float aS, float matrixB[3][3], float bS)
+{
+ VECADDSUBSS(to[0], matrixA[0], aS, matrixB[0], bS);
+ VECADDSUBSS(to[1], matrixA[1], aS, matrixB[1], bS);
+ VECADDSUBSS(to[2], matrixA[2], aS, matrixB[2], bS);
+}
+/* A -= B + C (3x3 matrix sub-addition with 3x3 matrix) */
+DO_INLINE void subadd_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
+{
+ VECSUBADD(to[0], matrixA[0], matrixB[0]);
+ VECSUBADD(to[1], matrixA[1], matrixB[1]);
+ VECSUBADD(to[2], matrixA[2], matrixB[2]);
+}
+/* A -= B*x + C*y (3x3 matrix sub-addition with 3x3 matrix) */
+DO_INLINE void subadd_fmatrixS_fmatrixS(float to[3][3], float matrixA[3][3], float aS, float matrixB[3][3], float bS)
+{
+ VECSUBADDSS(to[0], matrixA[0], aS, matrixB[0], bS);
+ VECSUBADDSS(to[1], matrixA[1], aS, matrixB[1], bS);
+ VECSUBADDSS(to[2], matrixA[2], aS, matrixB[2], bS);
+}
+/* A = B - C (3x3 matrix subtraction with 3x3 matrix) */
+DO_INLINE void sub_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
+{
+ VECSUB(to[0], matrixA[0], matrixB[0]);
+ VECSUB(to[1], matrixA[1], matrixB[1]);
+ VECSUB(to[2], matrixA[2], matrixB[2]);
+}
+/* A += B - C (3x3 matrix add-subtraction with 3x3 matrix) */
+DO_INLINE void addsub_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
+{
+ VECADDSUB(to[0], matrixA[0], matrixB[0]);
+ VECADDSUB(to[1], matrixA[1], matrixB[1]);
+ VECADDSUB(to[2], matrixA[2], matrixB[2]);
+}
+/////////////////////////////////////////////////////////////////
+// special functions
+/////////////////////////////////////////////////////////////////
+/* a vector multiplied and added to/by a 3x3 matrix */
+DO_INLINE void muladd_fvector_fmatrix(float to[3], float from[3], float matrix[3][3])
+{
+ to[0] += matrix[0][0]*from[0] + matrix[1][0]*from[1] + matrix[2][0]*from[2];
+ to[1] += matrix[0][1]*from[0] + matrix[1][1]*from[1] + matrix[2][1]*from[2];
+ to[2] += matrix[0][2]*from[0] + matrix[1][2]*from[1] + matrix[2][2]*from[2];
+}
+/* 3x3 matrix multiplied and added to/by a 3x3 matrix and added to another 3x3 matrix */
+DO_INLINE void muladd_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
+{
+ muladd_fvector_fmatrix(to[0], matrixA[0],matrixB);
+ muladd_fvector_fmatrix(to[1], matrixA[1],matrixB);
+ muladd_fvector_fmatrix(to[2], matrixA[2],matrixB);
+}
+/* a vector multiplied and sub'd to/by a 3x3 matrix */
+DO_INLINE void mulsub_fvector_fmatrix(float to[3], float from[3], float matrix[3][3])
+{
+ to[0] -= matrix[0][0]*from[0] + matrix[1][0]*from[1] + matrix[2][0]*from[2];
+ to[1] -= matrix[0][1]*from[0] + matrix[1][1]*from[1] + matrix[2][1]*from[2];
+ to[2] -= matrix[0][2]*from[0] + matrix[1][2]*from[1] + matrix[2][2]*from[2];
+}
+/* 3x3 matrix multiplied and sub'd to/by a 3x3 matrix and added to another 3x3 matrix */
+DO_INLINE void mulsub_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
+{
+ mulsub_fvector_fmatrix(to[0], matrixA[0],matrixB);
+ mulsub_fvector_fmatrix(to[1], matrixA[1],matrixB);
+ mulsub_fvector_fmatrix(to[2], matrixA[2],matrixB);
+}
+/* 3x3 matrix multiplied+added by a vector */
+/* STATUS: verified */
+DO_INLINE void muladd_fmatrix_fvector(float to[3], float matrix[3][3], float from[3])
+{
+ to[0] += INPR(matrix[0],from);
+ to[1] += INPR(matrix[1],from);
+ to[2] += INPR(matrix[2],from);
+}
+/* 3x3 matrix multiplied+sub'ed by a vector */
+DO_INLINE void mulsub_fmatrix_fvector(float to[3], float matrix[3][3], float from[3])
+{
+ to[0] -= INPR(matrix[0],from);
+ to[1] -= INPR(matrix[1],from);
+ to[2] -= INPR(matrix[2],from);
+}
+/////////////////////////////////////////////////////////////////
+
+///////////////////////////
+// SPARSE SYMMETRIC big matrix with 3x3 matrix entries
+///////////////////////////
+/* printf a big matrix on console: for debug output */
+void print_bfmatrix(fmatrix3x3 *m3)
+{
+ unsigned int i = 0;
+
+ for(i = 0; i < m3[0].vcount + m3[0].scount; i++)
+ {
+ print_fmatrix(m3[i].m);
+ }
+}
+/* create big matrix */
+DO_INLINE fmatrix3x3 *create_bfmatrix(unsigned int verts, unsigned int springs)
+{
+ // TODO: check if memory allocation was successfull */
+ fmatrix3x3 *temp = (fmatrix3x3 *)MEM_callocN (sizeof (fmatrix3x3) * (verts + springs), "cloth_implicit_alloc_matrix");
+ temp[0].vcount = verts;
+ temp[0].scount = springs;
+ return temp;
+}
+/* delete big matrix */
+DO_INLINE void del_bfmatrix(fmatrix3x3 *matrix)
+{
+ if (matrix != NULL)
+ {
+ MEM_freeN (matrix);
+ }
+}
+
+/* copy big matrix */
+DO_INLINE void cp_bfmatrix(fmatrix3x3 *to, fmatrix3x3 *from)
+{
+ // TODO bounds checking
+ memcpy(to, from, sizeof(fmatrix3x3) * (from[0].vcount+from[0].scount) );
+}
+
+/* init big matrix */
+// slow in parallel
+DO_INLINE void init_bfmatrix(fmatrix3x3 *matrix, float m3[3][3])
+{
+ unsigned int i;
+
+ for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
+ {
+ cp_fmatrix(matrix[i].m, m3);
+ }
+}
+
+/* init the diagonal of big matrix */
+// slow in parallel
+DO_INLINE void initdiag_bfmatrix(fmatrix3x3 *matrix, float m3[3][3])
+{
+ unsigned int i,j;
+ float tmatrix[3][3] = {{0,0,0},{0,0,0},{0,0,0}};
+
+ for(i = 0; i < matrix[0].vcount; i++)
+ {
+ cp_fmatrix(matrix[i].m, m3);
+ }
+ for(j = matrix[0].vcount; j < matrix[0].vcount+matrix[0].scount; j++)
+ {
+ cp_fmatrix(matrix[j].m, tmatrix);
+ }
+}
+
+/* multiply big matrix with scalar*/
+DO_INLINE void mul_bfmatrix_S(fmatrix3x3 *matrix, float scalar)
+{
+ unsigned int i = 0;
+ for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
+ {
+ mul_fmatrix_S(matrix[i].m, scalar);
+ }
+}
+
+/* SPARSE SYMMETRIC multiply big matrix with long vector*/
+/* STATUS: verified */
+DO_INLINE void mul_bfmatrix_lfvector( float (*to)[3], fmatrix3x3 *from, lfVector *fLongVector)
+{
+ unsigned int i = 0;
+ lfVector *temp = create_lfvector(from[0].vcount);
+
+ zero_lfvector(to, from[0].vcount);
+
+#pragma omp parallel sections private(i)
+ {
+#pragma omp section
+ {
+ for(i = from[0].vcount; i < from[0].vcount+from[0].scount; i++)
+ {
+ muladd_fmatrix_fvector(to[from[i].c], from[i].m, fLongVector[from[i].r]);
+ }
+ }
+#pragma omp section
+ {
+ for(i = 0; i < from[0].vcount+from[0].scount; i++)
+ {
+ muladd_fmatrix_fvector(temp[from[i].r], from[i].m, fLongVector[from[i].c]);
+ }
+ }
+ }
+ add_lfvector_lfvector(to, to, temp, from[0].vcount);
+
+ del_lfvector(temp);
+
+
+}
+
+/* SPARSE SYMMETRIC multiply big matrix with long vector (for diagonal preconditioner) */
+/* STATUS: verified */
+DO_INLINE void mul_prevfmatrix_lfvector( float (*to)[3], fmatrix3x3 *from, lfVector *fLongVector)
+{
+ unsigned int i = 0;
+
+ for(i = 0; i < from[0].vcount; i++)
+ {
+ mul_fmatrix_fvector(to[from[i].r], from[i].m, fLongVector[from[i].c]);
+ }
+}
+
+/* SPARSE SYMMETRIC add big matrix with big matrix: A = B + C*/
+DO_INLINE void add_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmatrix3x3 *matrix)
+{
+ unsigned int i = 0;
+
+ /* process diagonal elements */
+ for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
+ {
+ add_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);
+ }
+
+}
+/* SPARSE SYMMETRIC add big matrix with big matrix: A += B + C */
+DO_INLINE void addadd_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmatrix3x3 *matrix)
+{
+ unsigned int i = 0;
+
+ /* process diagonal elements */
+ for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
+ {
+ addadd_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);
+ }
+
+}
+/* SPARSE SYMMETRIC subadd big matrix with big matrix: A -= B + C */
+DO_INLINE void subadd_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmatrix3x3 *matrix)
+{
+ unsigned int i = 0;
+
+ /* process diagonal elements */
+ for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
+ {
+ subadd_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);
+ }
+
+}
+/* A = B - C (SPARSE SYMMETRIC sub big matrix with big matrix) */
+DO_INLINE void sub_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmatrix3x3 *matrix)
+{
+ unsigned int i = 0;
+
+ /* process diagonal elements */
+ for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
+ {
+ sub_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);
+ }
+
+}
+/* SPARSE SYMMETRIC sub big matrix with big matrix S (special constraint matrix with limited entries) */
+DO_INLINE void sub_bfmatrix_Smatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmatrix3x3 *matrix)
+{
+ unsigned int i = 0;
+
+ /* process diagonal elements */
+ for(i = 0; i < matrix[0].vcount; i++)
+ {
+ sub_fmatrix_fmatrix(to[matrix[i].c].m, from[matrix[i].c].m, matrix[i].m);
+ }
+
+}
+/* A += B - C (SPARSE SYMMETRIC addsub big matrix with big matrix) */
+DO_INLINE void addsub_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmatrix3x3 *matrix)
+{
+ unsigned int i = 0;
+
+ /* process diagonal elements */
+ for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
+ {
+ addsub_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);
+ }
+
+}
+/* SPARSE SYMMETRIC sub big matrix with big matrix*/
+/* A -= B * float + C * float --> for big matrix */
+/* VERIFIED */
+DO_INLINE void subadd_bfmatrixS_bfmatrixS( fmatrix3x3 *to, fmatrix3x3 *from, float aS, fmatrix3x3 *matrix, float bS)
+{
+ unsigned int i = 0;
+
+ /* process diagonal elements */
+ for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
+ {
+ subadd_fmatrixS_fmatrixS(to[i].m, from[i].m, aS, matrix[i].m, bS);
+ }
+
+}
+
+///////////////////////////////////////////////////////////////////
+// simulator start
+///////////////////////////////////////////////////////////////////
+typedef struct Implicit_Data
+{
+ lfVector *X, *V, *Xnew, *Vnew, *olddV, *F, *B, *dV, *z;
+ fmatrix3x3 *A, *dFdV, *dFdX, *S, *P, *Pinv, *bigI, *M;
+} Implicit_Data;
+
+int implicit_init (Object *ob, ClothModifierData *clmd)
+{
+ unsigned int i = 0;
+ unsigned int pinned = 0;
+ Cloth *cloth = NULL;
+ ClothVertex *verts = NULL;
+ ClothSpring *spring = NULL;
+ Implicit_Data *id = NULL;
+ LinkNode *search = NULL;
+
+ if(G.rt > 0)
+ printf("implicit_init\n");
+
+ // init memory guard
+ // MEMORY_BASE.first = MEMORY_BASE.last = NULL;
+
+ cloth = (Cloth *)clmd->clothObject;
+ verts = cloth->verts;
+
+ // create implicit base
+ id = (Implicit_Data *)MEM_callocN (sizeof(Implicit_Data), "implicit vecmat");
+ cloth->implicit = id;
+
+ /* process diagonal elements */
+ id->A = create_bfmatrix(cloth->numverts, cloth->numsprings);
+ id->dFdV = create_bfmatrix(cloth->numverts, cloth->numsprings);
+ id->dFdX = create_bfmatrix(cloth->numverts, cloth->numsprings);
+ id->S = create_bfmatrix(cloth->numverts, 0);
+ id->Pinv = create_bfmatrix(cloth->numverts, cloth->numsprings);
+ id->P = create_bfmatrix(cloth->numverts, cloth->numsprings);
+ id->bigI = create_bfmatrix(cloth->numverts, cloth->numsprings); // TODO 0 springs
+ id->M = create_bfmatrix(cloth->numverts, cloth->numsprings);
+ id->X = create_lfvector(cloth->numverts);
+ id->Xnew = create_lfvector(cloth->numverts);
+ id->V = create_lfvector(cloth->numverts);
+ id->Vnew = create_lfvector(cloth->numverts);
+ id->olddV = create_lfvector(cloth->numverts);
+ zero_lfvector(id->olddV, cloth->numverts);
+ id->F = create_lfvector(cloth->numverts);
+ id->B = create_lfvector(cloth->numverts);
+ id->dV = create_lfvector(cloth->numverts);
+ id->z = create_lfvector(cloth->numverts);
+
+ for(i=0;i<cloth->numverts;i++)
+ {
+ id->A[i].r = id->A[i].c = id->dFdV[i].r = id->dFdV[i].c = id->dFdX[i].r = id->dFdX[i].c = id->P[i].c = id->P[i].r = id->Pinv[i].c = id->Pinv[i].r = id->bigI[i].c = id->bigI[i].r = id->M[i].r = id->M[i].c = i;
+
+ if(verts [i].flags & CLOTH_VERT_FLAG_PINNED)
+ {
+ id->S[pinned].pinned = 1;
+ id->S[pinned].c = id->S[pinned].r = i;
+ pinned++;
+ }
+
+ initdiag_fmatrixS(id->M[i].m, verts[i].mass);
+ }
+
+ // S is special and needs specific vcount and scount
+ id->S[0].vcount = pinned; id->S[0].scount = 0;
+
+ // init springs
+ search = cloth->springs;
+ for(i=0;i<cloth->numsprings;i++)
+ {
+ spring = search->link;
+
+ // dFdV_start[i].r = big_I[i].r = big_zero[i].r =
+ id->A[i+cloth->numverts].r = id->dFdV[i+cloth->numverts].r = id->dFdX[i+cloth->numverts].r =
+ id->P[i+cloth->numverts].r = id->Pinv[i+cloth->numverts].r = id->bigI[i+cloth->numverts].r = id->M[i+cloth->numverts].r = spring->ij;
+
+ // dFdV_start[i].c = big_I[i].c = big_zero[i].c =
+ id->A[i+cloth->numverts].c = id->dFdV[i+cloth->numverts].c = id->dFdX[i+cloth->numverts].c =
+ id->P[i+cloth->numverts].c = id->Pinv[i+cloth->numverts].c = id->bigI[i+cloth->numverts].c = id->M[i+cloth->numverts].c = spring->kl;
+
+ spring->matrix_index = i + cloth->numverts;
+
+ search = search->next;
+ }
+
+ initdiag_bfmatrix(id->bigI, I);
+
+ for(i = 0; i < cloth->numverts; i++)
+ {
+ VECCOPY(id->X[i], verts[i].x);
+ }
+
+ return 1;
+}
+int implicit_free (ClothModifierData *clmd)
+{
+ Implicit_Data *id;
+ Cloth *cloth;
+ cloth = (Cloth *)clmd->clothObject;
+
+ if(cloth)
+ {
+ id = cloth->implicit;
+
+ if(id)
+ {
+ del_bfmatrix(id->A);
+ del_bfmatrix(id->dFdV);
+ del_bfmatrix(id->dFdX);
+ del_bfmatrix(id->S);
+ del_bfmatrix(id->P);
+ del_bfmatrix(id->Pinv);
+ del_bfmatrix(id->bigI);
+ del_bfmatrix(id->M);
+
+ del_lfvector(id->X);
+ del_lfvector(id->Xnew);
+ del_lfvector(id->V);
+ del_lfvector(id->Vnew);
+ del_lfvector(id->olddV);
+ del_lfvector(id->F);
+ del_lfvector(id->B);
+ del_lfvector(id->dV);
+ del_lfvector(id->z);
+
+ MEM_freeN(id);
+ }
+ }
+
+ return 1;
+}
+
+DO_INLINE float fb(float length, float L)
+{
+ float x = length/L;
+ return (-11.541f*pow(x,4)+34.193f*pow(x,3)-39.083f*pow(x,2)+23.116f*x-9.713f);
+}
+
+DO_INLINE float fbderiv(float length, float L)
+{
+ float x = length/L;
+
+ return (-46.164f*pow(x,3)+102.579f*pow(x,2)-78.166f*x+23.116f);
+}
+
+DO_INLINE float fbstar(float length, float L, float kb, float cb)
+{
+ float tempfb = kb * fb(length, L);
+
+ float fbstar = cb * (length - L);
+
+ if(tempfb < fbstar)
+ return fbstar;
+ else
+ return tempfb;
+}
+
+// function to calculae bending spring force (taken from Choi & Co)
+DO_INLINE float fbstar_jacobi(float length, float L, float kb, float cb)
+{
+ float tempfb = kb * fb(length, L);
+ float fbstar = cb * (length - L);
+
+ if(tempfb < fbstar)
+ {
+ return cb;
+ }
+ else
+ {
+ return kb * fbderiv(length, L);
+ }
+}
+
+DO_INLINE void filter(lfVector *V, fmatrix3x3 *S)
+{
+ unsigned int i=0;
+
+ for(i=0;i<S[0].vcount;i++)
+ {
+ mul_fvector_fmatrix(V[S[i].r], V[S[i].r], S[i].m);
+ }
+}
+
+int cg_filtered(lfVector *ldV, fmatrix3x3 *lA, lfVector *lB, lfVector *z, fmatrix3x3 *S)
+{
+ // Solves for unknown X in equation AX=B
+ unsigned int conjgrad_loopcount=0, conjgrad_looplimit=100;
+ float conjgrad_epsilon=0.0001f, conjgrad_lasterror=0;
+ lfVector *q, *d, *tmp, *r;
+ float s, starget, a, s_prev;
+ unsigned int numverts = lA[0].vcount;
+ q = create_lfvector(numverts);
+ d = create_lfvector(numverts);
+ tmp = create_lfvector(numverts);
+ r = create_lfvector(numverts);
+
+ // zero_lfvector(ldV, CLOTHPARTICLES);
+ filter(ldV, S);
+
+ add_lfvector_lfvector(ldV, ldV, z, numverts);
+
+ // r = B - Mul(tmp,A,X); // just use B if X known to be zero
+ cp_lfvector(r, lB, numverts);
+ mul_bfmatrix_lfvector(tmp, lA, ldV);
+ sub_lfvector_lfvector(r, r, tmp, numverts);
+
+ filter(r,S);
+
+ cp_lfvector(d, r, numverts);
+
+ s = dot_lfvector(r, r, numverts);
+ starget = s * sqrt(conjgrad_epsilon);
+
+ while((s>starget && conjgrad_loopcount < conjgrad_looplimit))
+ {
+ // Mul(q,A,d); // q = A*d;
+ mul_bfmatrix_lfvector(q, lA, d);
+
+ filter(q,S);
+
+ a = s/dot_lfvector(d, q, numverts);
+
+ // X = X + d*a;
+ add_lfvector_lfvectorS(ldV, ldV, d, a, numverts);
+
+ // r = r - q*a;
+ sub_lfvector_lfvectorS(r, r, q, a, numverts);
+
+ s_prev = s;
+ s = dot_lfvector(r, r, numverts);
+
+ //d = r+d*(s/s_prev);
+ add_lfvector_lfvectorS(d, r, d, (s/s_prev), numverts);
+
+ filter(d,S);
+
+ conjgrad_loopcount++;
+ }
+ conjgrad_lasterror = s;
+
+ del_lfvector(q);
+ del_lfvector(d);
+ del_lfvector(tmp);
+ del_lfvector(r);
+ // printf("W/O conjgrad_loopcount: %d\n", conjgrad_loopcount);
+
+ return conjgrad_loopcount<conjgrad_looplimit; // true means we reached desired accuracy in given time - ie stable
+}
+
+// block diagonalizer
+DO_INLINE void BuildPPinv(fmatrix3x3 *lA, fmatrix3x3 *P, fmatrix3x3 *Pinv)
+{
+ unsigned int i = 0;
+
+ // Take only the diagonal blocks of A
+// #pragma omp parallel for private(i)
+ for(i = 0; i<lA[0].vcount; i++)
+ {
+ // block diagonalizer
+ cp_fmatrix(P[i].m, lA[i].m);
+ inverse_fmatrix(Pinv[i].m, P[i].m);
+
+ }
+}
+/*
+// version 1.3
+int cg_filtered_pre(lfVector *dv, fmatrix3x3 *lA, lfVector *lB, lfVector *z, fmatrix3x3 *S, fmatrix3x3 *P, fmatrix3x3 *Pinv)
+{
+ unsigned int numverts = lA[0].vcount, iterations = 0, conjgrad_looplimit=100;
+ float delta0 = 0, deltaNew = 0, deltaOld = 0, alpha = 0;
+ float conjgrad_epsilon=0.0001; // 0.2 is dt for steps=5
+ lfVector *r = create_lfvector(numverts);
+ lfVector *p = create_lfvector(numverts);
+ lfVector *s = create_lfvector(numverts);
+ lfVector *h = create_lfvector(numverts);
+
+ BuildPPinv(lA, P, Pinv);
+
+ filter(dv, S);
+ add_lfvector_lfvector(dv, dv, z, numverts);
+
+ mul_bfmatrix_lfvector(r, lA, dv);
+ sub_lfvector_lfvector(r, lB, r, numverts);
+ filter(r, S);
+
+ mul_prevfmatrix_lfvector(p, Pinv, r);
+ filter(p, S);
+
+ deltaNew = dot_lfvector(r, p, numverts);
+
+ delta0 = deltaNew * sqrt(conjgrad_epsilon);
+
+ // itstart();
+
+ while ((deltaNew > delta0) && (iterations < conjgrad_looplimit))
+ {
+ iterations++;
+
+ mul_bfmatrix_lfvector(s, lA, p);
+ filter(s, S);
+
+ alpha = deltaNew / dot_lfvector(p, s, numverts);
+
+ add_lfvector_lfvectorS(dv, dv, p, alpha, numverts);
+
+ add_lfvector_lfvectorS(r, r, s, -alpha, numverts);
+
+ mul_prevfmatrix_lfvector(h, Pinv, r);
+ filter(h, S);
+
+ deltaOld = deltaNew;
+
+ deltaNew = dot_lfvector(r, h, numverts);
+
+ add_lfvector_lfvectorS(p, h, p, deltaNew / deltaOld, numverts);
+
+ filter(p, S);
+
+ }
+
+ // itend();
+ // printf("cg_filtered_pre time: %f\n", (float)itval());
+
+ del_lfvector(h);
+ del_lfvector(s);
+ del_lfvector(p);
+ del_lfvector(r);
+
+ printf("iterations: %d\n", iterations);
+
+ return iterations<conjgrad_looplimit;
+}
+*/
+// version 1.4
+int cg_filtered_pre(lfVector *dv, fmatrix3x3 *lA, lfVector *lB, lfVector *z, fmatrix3x3 *S, fmatrix3x3 *P, fmatrix3x3 *Pinv, fmatrix3x3 *bigI)
+{
+ unsigned int numverts = lA[0].vcount, iterations = 0, conjgrad_looplimit=100;
+ float delta0 = 0, deltaNew = 0, deltaOld = 0, alpha = 0, tol = 0;
+ lfVector *r = create_lfvector(numverts);
+ lfVector *p = create_lfvector(numverts);
+ lfVector *s = create_lfvector(numverts);
+ lfVector *h = create_lfvector(numverts);
+ lfVector *bhat = create_lfvector(numverts);
+ lfVector *btemp = create_lfvector(numverts);
+
+ BuildPPinv(lA, P, Pinv);
+
+ initdiag_bfmatrix(bigI, I);
+ sub_bfmatrix_Smatrix(bigI, bigI, S);
+
+ // x = Sx_0+(I-S)z
+ filter(dv, S);
+ add_lfvector_lfvector(dv, dv, z, numverts);
+
+ // b_hat = S(b-A(I-S)z)
+ mul_bfmatrix_lfvector(r, lA, z);
+ mul_bfmatrix_lfvector(bhat, bigI, r);
+ sub_lfvector_lfvector(bhat, lB, bhat, numverts);
+
+ // r = S(b-Ax)
+ mul_bfmatrix_lfvector(r, lA, dv);
+ sub_lfvector_lfvector(r, lB, r, numverts);
+ filter(r, S);
+
+ // p = SP^-1r
+ mul_prevfmatrix_lfvector(p, Pinv, r);
+ filter(p, S);
+
+ // delta0 = bhat^TP^-1bhat
+ mul_prevfmatrix_lfvector(btemp, Pinv, bhat);
+ delta0 = dot_lfvector(bhat, btemp, numverts);
+
+ // deltaNew = r^TP
+ deltaNew = dot_lfvector(r, p, numverts);
+
+ /*
+ filter(dv, S);
+ add_lfvector_lfvector(dv, dv, z, numverts);
+
+ mul_bfmatrix_lfvector(r, lA, dv);
+ sub_lfvector_lfvector(r, lB, r, numverts);
+ filter(r, S);
+
+ mul_prevfmatrix_lfvector(p, Pinv, r);
+ filter(p, S);
+
+ deltaNew = dot_lfvector(r, p, numverts);
+
+ delta0 = deltaNew * sqrt(conjgrad_epsilon);
+ */
+
+ // itstart();
+
+ tol = (0.01*0.2);
+
+ while ((deltaNew > delta0*tol*tol) && (iterations < conjgrad_looplimit))
+ {
+ iterations++;
+
+ mul_bfmatrix_lfvector(s, lA, p);
+ filter(s, S);
+
+ alpha = deltaNew / dot_lfvector(p, s, numverts);
+
+ add_lfvector_lfvectorS(dv, dv, p, alpha, numverts);
+
+ add_lfvector_lfvectorS(r, r, s, -alpha, numverts);
+
+ mul_prevfmatrix_lfvector(h, Pinv, r);
+ filter(h, S);
+
+ deltaOld = deltaNew;
+
+ deltaNew = dot_lfvector(r, h, numverts);
+
+ add_lfvector_lfvectorS(p, h, p, deltaNew / deltaOld, numverts);
+
+ filter(p, S);
+
+ }
+
+ // itend();
+ // printf("cg_filtered_pre time: %f\n", (float)itval());
+
+ del_lfvector(btemp);
+ del_lfvector(bhat);
+ del_lfvector(h);
+ del_lfvector(s);
+ del_lfvector(p);
+ del_lfvector(r);
+
+ // printf("iterations: %d\n", iterations);
+
+ return iterations<conjgrad_looplimit;
+}
+
+// outer product is NOT cross product!!!
+DO_INLINE void dfdx_spring_type1(float to[3][3], float extent[3], float length, float L, float dot, float k)
+{
+ // dir is unit length direction, rest is spring's restlength, k is spring constant.
+ // return (outerprod(dir,dir)*k + (I - outerprod(dir,dir))*(k - ((k*L)/length)));
+ float temp[3][3];
+ float temp1 = k*(1.0 - (L/length));
+
+ mul_fvectorT_fvectorS(temp, extent, extent, 1.0 / dot);
+ sub_fmatrix_fmatrix(to, I, temp);
+ mul_fmatrix_S(to, temp1);
+
+ mul_fvectorT_fvectorS(temp, extent, extent, k/ dot);
+ add_fmatrix_fmatrix(to, to, temp);
+
+ /*
+ mul_fvectorT_fvector(temp, dir, dir);
+ sub_fmatrix_fmatrix(to, I, temp);
+ mul_fmatrix_S(to, k* (1.0f-(L/length)));
+ mul_fmatrix_S(temp, k);
+ add_fmatrix_fmatrix(to, temp, to);
+ */
+}
+
+DO_INLINE void dfdx_spring_type2(float to[3][3], float dir[3], float length, float L, float k, float cb)
+{
+ // return outerprod(dir,dir)*fbstar_jacobi(length, L, k, cb);
+ mul_fvectorT_fvectorS(to, dir, dir, fbstar_jacobi(length, L, k, cb));
+}
+
+DO_INLINE void dfdv_damp(float to[3][3], float dir[3], float damping)
+{
+ // derivative of force wrt velocity.
+ mul_fvectorT_fvectorS(to, dir, dir, damping);
+
+}
+
+DO_INLINE void dfdx_spring(float to[3][3], float dir[3],float length,float L,float k)
+{
+ // dir is unit length direction, rest is spring's restlength, k is spring constant.
+ //return ( (I-outerprod(dir,dir))*Min(1.0f,rest/length) - I) * -k;
+ mul_fvectorT_fvector(to, dir, dir);
+ sub_fmatrix_fmatrix(to, I, to);
+ mul_fmatrix_S(to, (((L/length)> 1.0f) ? (1.0f): (L/length)));
+ sub_fmatrix_fmatrix(to, to, I);
+ mul_fmatrix_S(to, -k);
+}
+
+// unused atm
+DO_INLINE void dfdx_damp(float to[3][3], float dir[3],float length,const float vel[3],float rest,float damping)
+{
+ // inner spring damping vel is the relative velocity of the endpoints.
+ // return (I-outerprod(dir,dir)) * (-damping * -(dot(dir,vel)/Max(length,rest)));
+ mul_fvectorT_fvector(to, dir, dir);
+ sub_fmatrix_fmatrix(to, I, to);
+ mul_fmatrix_S(to, (-damping * -(INPR(dir,vel)/MAX2(length,rest))));
+
+}
+
+DO_INLINE void cloth_calc_spring_force(ClothModifierData *clmd, ClothSpring *s, lfVector *lF, lfVector *X, lfVector *V, fmatrix3x3 *dFdV, fmatrix3x3 *dFdX, float time)
+{
+ Cloth *cloth = clmd->clothObject;
+ ClothVertex *verts = cloth->verts;
+ float extent[3];
+ float length = 0, dot = 0;
+ float dir[3] = {0,0,0};
+ float vel[3];
+ float k = 0.0f;
+ float L = s->restlen;
+ float cb = clmd->sim_parms->structural;
+
+ float nullf[3] = {0,0,0};
+ float stretch_force[3] = {0,0,0};
+ float bending_force[3] = {0,0,0};
+ float damping_force[3] = {0,0,0};
+ float nulldfdx[3][3]={ {0,0,0}, {0,0,0}, {0,0,0}};
+
+ float scaling = 0.0;
+
+ VECCOPY(s->f, nullf);
+ cp_fmatrix(s->dfdx, nulldfdx);
+ cp_fmatrix(s->dfdv, nulldfdx);
+
+ // calculate elonglation
+ VECSUB(extent, X[s->kl], X[s->ij]);
+ VECSUB(vel, V[s->kl], V[s->ij]);
+ dot = INPR(extent, extent);
+ length = sqrt(dot);
+
+ s->flags &= ~CLOTH_SPRING_FLAG_NEEDED;
+
+ if(length > ALMOST_ZERO)
+ {
+ /*
+ if(length>L)
+ {
+ if((clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED)
+ && ((((length-L)*100.0f/L) > clmd->sim_parms->maxspringlen))) // cut spring!
+ {
+ s->flags |= CSPRING_FLAG_DEACTIVATE;
+ return;
+ }
+ }
+ */
+ mul_fvector_S(dir, extent, 1.0f/length);
+ }
+ else
+ {
+ mul_fvector_S(dir, extent, 0.0f);
+ }
+
+ // calculate force of structural + shear springs
+ if((s->type & CLOTH_SPRING_TYPE_STRUCTURAL) || (s->type & CLOTH_SPRING_TYPE_SHEAR))
+ {
+ if(length > L) // only on elonglation
+ {
+ s->flags |= CLOTH_SPRING_FLAG_NEEDED;
+
+ k = clmd->sim_parms->structural;
+
+ scaling = k + s->stiffness * ABS(clmd->sim_parms->max_struct-k);
+
+ k = scaling / (clmd->sim_parms->avg_spring_len + FLT_EPSILON);
+
+ // TODO: verify, half verified (couldn't see error)
+ mul_fvector_S(stretch_force, dir, k*(length-L));
+
+ VECADD(s->f, s->f, stretch_force);
+
+ // Ascher & Boxman, p.21: Damping only during elonglation
+ // something wrong with it...
+ mul_fvector_S(damping_force, dir, clmd->sim_parms->Cdis * INPR(vel,dir));
+ VECADD(s->f, s->f, damping_force);
+
+ /* VERIFIED */
+ dfdx_spring(s->dfdx, dir, length, L, k);
+
+ /* VERIFIED */
+ dfdv_damp(s->dfdv, dir, clmd->sim_parms->Cdis);
+
+ }
+ }
+ else if(s->type & CLOTH_SPRING_TYPE_GOAL)
+ {
+ float tvect[3];
+
+ s->flags |= CLOTH_SPRING_FLAG_NEEDED;
+
+ // current_position = xold + t * (newposition - xold)
+ VECSUB(tvect, verts[s->ij].xconst, verts[s->ij].xold);
+ mul_fvector_S(tvect, tvect, time);
+ VECADD(tvect, tvect, verts[s->ij].xold);
+
+ VECSUB(extent, X[s->ij], tvect);
+
+ dot = INPR(extent, extent);
+ length = sqrt(dot);
+
+ k = clmd->sim_parms->goalspring;
+
+ scaling = k + s->stiffness * ABS(clmd->sim_parms->max_struct-k);
+
+ k = verts [s->ij].goal * scaling / (clmd->sim_parms->avg_spring_len + FLT_EPSILON);
+
+ VECADDS(s->f, s->f, extent, -k);
+
+ mul_fvector_S(damping_force, dir, clmd->sim_parms->goalfrict * 0.01 * INPR(vel,dir));
+ VECADD(s->f, s->f, damping_force);
+
+ // HERE IS THE PROBLEM!!!!
+ // dfdx_spring(s->dfdx, dir, length, 0.0, k);
+ // dfdv_damp(s->dfdv, dir, MIN2(1.0, (clmd->sim_parms->goalfrict/100.0)));
+ }
+ else // calculate force of bending springs
+ {
+ if(length < L)
+ {
+ s->flags |= CLOTH_SPRING_FLAG_NEEDED;
+
+ k = clmd->sim_parms->bending;
+
+ scaling = k + s->stiffness * ABS(clmd->sim_parms->max_bend-k);
+ cb = k = scaling / (20.0*(clmd->sim_parms->avg_spring_len + FLT_EPSILON));
+
+ mul_fvector_S(bending_force, dir, fbstar(length, L, k, cb));
+ VECADD(s->f, s->f, bending_force);
+
+ dfdx_spring_type2(s->dfdx, dir, length,L, k, cb);
+ }
+ }
+}
+
+DO_INLINE void cloth_apply_spring_force(ClothModifierData *clmd, ClothSpring *s, lfVector *lF, lfVector *X, lfVector *V, fmatrix3x3 *dFdV, fmatrix3x3 *dFdX)
+{
+ if(s->flags & CLOTH_SPRING_FLAG_NEEDED)
+ {
+ if(!(s->type & CLOTH_SPRING_TYPE_BENDING))
+ {
+ sub_fmatrix_fmatrix(dFdV[s->ij].m, dFdV[s->ij].m, s->dfdv);
+ sub_fmatrix_fmatrix(dFdV[s->kl].m, dFdV[s->kl].m, s->dfdv);
+ add_fmatrix_fmatrix(dFdV[s->matrix_index].m, dFdV[s->matrix_index].m, s->dfdv);
+ }
+
+ VECADD(lF[s->ij], lF[s->ij], s->f);
+
+ if(!(s->type & CLOTH_SPRING_TYPE_GOAL))
+ VECSUB(lF[s->kl], lF[s->kl], s->f);
+
+ sub_fmatrix_fmatrix(dFdX[s->kl].m, dFdX[s->kl].m, s->dfdx);
+ sub_fmatrix_fmatrix(dFdX[s->ij].m, dFdX[s->ij].m, s->dfdx);
+ add_fmatrix_fmatrix(dFdX[s->matrix_index].m, dFdX[s->matrix_index].m, s->dfdx);
+ }
+}
+
+
+static void CalcFloat( float *v1, float *v2, float *v3, float *n)
+{
+ float n1[3],n2[3];
+
+ n1[0]= v1[0]-v2[0];
+ n2[0]= v2[0]-v3[0];
+ n1[1]= v1[1]-v2[1];
+ n2[1]= v2[1]-v3[1];
+ n1[2]= v1[2]-v2[2];
+ n2[2]= v2[2]-v3[2];
+ n[0]= n1[1]*n2[2]-n1[2]*n2[1];
+ n[1]= n1[2]*n2[0]-n1[0]*n2[2];
+ n[2]= n1[0]*n2[1]-n1[1]*n2[0];
+}
+
+static void CalcFloat4( float *v1, float *v2, float *v3, float *v4, float *n)
+{
+ /* real cross! */
+ float n1[3],n2[3];
+
+ n1[0]= v1[0]-v3[0];
+ n1[1]= v1[1]-v3[1];
+ n1[2]= v1[2]-v3[2];
+
+ n2[0]= v2[0]-v4[0];
+ n2[1]= v2[1]-v4[1];
+ n2[2]= v2[2]-v4[2];
+
+ n[0]= n1[1]*n2[2]-n1[2]*n2[1];
+ n[1]= n1[2]*n2[0]-n1[0]*n2[2];
+ n[2]= n1[0]*n2[1]-n1[1]*n2[0];
+}
+
+float calculateVertexWindForce(float wind[3], float vertexnormal[3])
+{
+ return (INPR(wind, vertexnormal));
+}
+
+void cloth_calc_force(ClothModifierData *clmd, lfVector *lF, lfVector *lX, lfVector *lV, fmatrix3x3 *dFdV, fmatrix3x3 *dFdX, ListBase *effectors, float time, fmatrix3x3 *M)
+{
+ /* Collect forces and derivatives: F,dFdX,dFdV */
+ Cloth *cloth = clmd->clothObject;
+ int i = 0;
+ float spring_air = clmd->sim_parms->Cvi * 0.01f; /* viscosity of air scaled in percent */
+ float gravity[3];
+ float tm2[3][3] = {{-spring_air,0,0}, {0,-spring_air,0},{0,0,-spring_air}};
+ MFace *mfaces = cloth->mfaces;
+ unsigned int numverts = cloth->numverts;
+ LinkNode *search = cloth->springs;
+ lfVector *winvec;
+
+ VECCOPY(gravity, clmd->sim_parms->gravity);
+ mul_fvector_S(gravity, gravity, 0.001f); /* scale gravity force */
+
+ /* set dFdX jacobi matrix to zero */
+ init_bfmatrix(dFdX, ZERO);
+ /* set dFdX jacobi matrix diagonal entries to -spring_air */
+ initdiag_bfmatrix(dFdV, tm2);
+
+ init_lfvector(lF, gravity, numverts);
+
+ /* multiply lF with mass matrix
+ // force = mass * acceleration (in this case: gravity)
+ */
+ for(i = 0; i < numverts; i++)
+ {
+ float temp[3];
+ VECCOPY(temp, lF[i]);
+ mul_fmatrix_fvector(lF[i], M[i].m, temp);
+ }
+
+ submul_lfvectorS(lF, lV, spring_air, numverts);
+
+ /* handle external forces like wind */
+ if(effectors)
+ {
+ // 0 = force, 1 = normalized force
+ winvec = create_lfvector(cloth->numverts);
+
+ if(!winvec)
+ printf("winvec: out of memory in implicit.c\n");
+
+ // precalculate wind forces
+ for(i = 0; i < cloth->numverts; i++)
+ {
+ float speed[3] = {0.0f, 0.0f,0.0f};
+
+ pdDoEffectors(effectors, lX[i], winvec[i], speed, (float)G.scene->r.cfra, 0.0f, 0);
+ }
+
+ for(i = 0; i < cloth->numfaces; i++)
+ {
+ float trinormal[3]={0,0,0}; // normalized triangle normal
+ float triunnormal[3]={0,0,0}; // not-normalized-triangle normal
+ float tmp[3]={0,0,0};
+ float factor = (mfaces[i].v4) ? 0.25 : 1.0 / 3.0;
+ factor *= 0.02;
+
+ // calculate face normal
+ if(mfaces[i].v4)
+ CalcFloat4(lX[mfaces[i].v1],lX[mfaces[i].v2],lX[mfaces[i].v3],lX[mfaces[i].v4],triunnormal);
+ else
+ CalcFloat(lX[mfaces[i].v1],lX[mfaces[i].v2],lX[mfaces[i].v3],triunnormal);
+
+ VECCOPY(trinormal, triunnormal);
+ Normalize(trinormal);
+
+ // add wind from v1
+ VECCOPY(tmp, trinormal);
+ VecMulf(tmp, calculateVertexWindForce(winvec[mfaces[i].v1], triunnormal));
+ VECADDS(lF[mfaces[i].v1], lF[mfaces[i].v1], tmp, factor);
+
+ // add wind from v2
+ VECCOPY(tmp, trinormal);
+ VecMulf(tmp, calculateVertexWindForce(winvec[mfaces[i].v2], triunnormal));
+ VECADDS(lF[mfaces[i].v2], lF[mfaces[i].v2], tmp, factor);
+
+ // add wind from v3
+ VECCOPY(tmp, trinormal);
+ VecMulf(tmp, calculateVertexWindForce(winvec[mfaces[i].v3], triunnormal));
+ VECADDS(lF[mfaces[i].v3], lF[mfaces[i].v3], tmp, factor);
+
+ // add wind from v4
+ if(mfaces[i].v4)
+ {
+ VECCOPY(tmp, trinormal);
+ VecMulf(tmp, calculateVertexWindForce(winvec[mfaces[i].v4], triunnormal));
+ VECADDS(lF[mfaces[i].v4], lF[mfaces[i].v4], tmp, factor);
+ }
+ }
+ del_lfvector(winvec);
+ }
+
+ // calculate spring forces
+ search = cloth->springs;
+ while(search)
+ {
+ // only handle active springs
+ // if(((clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED) && !(springs[i].flags & CSPRING_FLAG_DEACTIVATE))|| !(clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED)){}
+ cloth_calc_spring_force(clmd, search->link, lF, lX, lV, dFdV, dFdX, time);
+
+ search = search->next;
+ }
+
+ // apply spring forces
+ search = cloth->springs;
+ while(search)
+ {
+ // only handle active springs
+ // if(((clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED) && !(springs[i].flags & CSPRING_FLAG_DEACTIVATE))|| !(clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED))
+ cloth_apply_spring_force(clmd, search->link, lF, lX, lV, dFdV, dFdX);
+ search = search->next;
+ }
+ // printf("\n");
+}
+
+void simulate_implicit_euler(lfVector *Vnew, lfVector *lX, lfVector *lV, lfVector *lF, fmatrix3x3 *dFdV, fmatrix3x3 *dFdX, float dt, fmatrix3x3 *A, lfVector *B, lfVector *dV, fmatrix3x3 *S, lfVector *z, lfVector *olddV, fmatrix3x3 *P, fmatrix3x3 *Pinv, fmatrix3x3 *M, fmatrix3x3 *bigI)
+{
+ unsigned int numverts = dFdV[0].vcount;
+
+ lfVector *dFdXmV = create_lfvector(numverts);
+ zero_lfvector(dV, numverts);
+
+ cp_bfmatrix(A, M);
+
+ subadd_bfmatrixS_bfmatrixS(A, dFdV, dt, dFdX, (dt*dt));
+
+ mul_bfmatrix_lfvector(dFdXmV, dFdX, lV);
+
+ add_lfvectorS_lfvectorS(B, lF, dt, dFdXmV, (dt*dt), numverts);
+
+ itstart();
+
+ cg_filtered(dV, A, B, z, S); /* conjugate gradient algorithm to solve Ax=b */
+ // cg_filtered_pre(dV, A, B, z, S, P, Pinv, bigI);
+
+ itend();
+ // printf("cg_filtered calc time: %f\n", (float)itval());
+
+ cp_lfvector(olddV, dV, numverts);
+
+ // advance velocities
+ add_lfvector_lfvector(Vnew, lV, dV, numverts);
+
+
+ del_lfvector(dFdXmV);
+}
+
+int implicit_solver (Object *ob, float frame, ClothModifierData *clmd, ListBase *effectors)
+{
+ unsigned int i=0;
+ float step=0.0f, tf=clmd->sim_parms->timescale;
+ Cloth *cloth = clmd->clothObject;
+ ClothVertex *verts = cloth->verts;
+ unsigned int numverts = cloth->numverts;
+ float dt = clmd->sim_parms->timescale / clmd->sim_parms->stepsPerFrame;
+ Implicit_Data *id = cloth->implicit;
+ int result = 0;
+
+ if(clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL) /* do goal stuff */
+ {
+ for(i = 0; i < numverts; i++)
+ {
+ // update velocities with constrained velocities from pinned verts
+ if(verts [i].flags & CLOTH_VERT_FLAG_PINNED)
+ {
+ VECSUB(id->V[i], verts[i].xconst, verts[i].xold);
+ // VecMulf(id->V[i], clmd->sim_parms->stepsPerFrame);
+ }
+ }
+ }
+
+ while(step < tf)
+ {
+ // calculate forces
+ effectors= pdInitEffectors(ob,NULL);
+ cloth_calc_force(clmd, id->F, id->X, id->V, id->dFdV, id->dFdX, effectors, step, id->M);
+ if(effectors) pdEndEffectors(effectors);
+
+ // calculate new velocity
+ simulate_implicit_euler(id->Vnew, id->X, id->V, id->F, id->dFdV, id->dFdX, dt, id->A, id->B, id->dV, id->S, id->z, id->olddV, id->P, id->Pinv, id->M, id->bigI);
+
+ // advance positions
+ add_lfvector_lfvectorS(id->Xnew, id->X, id->Vnew, dt, numverts);
+
+ /* move pinned verts to correct position */
+ for(i = 0; i < numverts; i++)
+ {
+ if(clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL)
+ {
+ if(verts [i].flags & CLOTH_VERT_FLAG_PINNED)
+ {
+ float tvect[3] = {.0,.0,.0};
+ VECSUB(tvect, verts[i].xconst, verts[i].xold);
+ mul_fvector_S(tvect, tvect, step+dt);
+ VECADD(tvect, tvect, verts[i].xold);
+ VECCOPY(id->Xnew[i], tvect);
+ }
+ }
+
+ VECCOPY(verts[i].txold, id->X[i]);
+ }
+
+ if(clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_ENABLED)
+ {
+ // collisions
+ // itstart();
+
+ // update verts to current positions
+ for(i = 0; i < numverts; i++)
+ {
+ VECCOPY(verts[i].tx, id->Xnew[i]);
+
+ VECSUB(verts[i].tv, verts[i].tx, verts[i].txold);
+ VECCOPY(verts[i].v, verts[i].tv);
+ }
+
+ // call collision function
+ // TODO: check if "step" or "step+dt" is correct - dg
+ result = cloth_bvh_objcollision(ob, clmd, step, dt);
+
+ // correct velocity again, just to be sure we had to change it due to adaptive collisions
+ for(i = 0; i < numverts; i++)
+ {
+ VECSUB(verts[i].tv, verts[i].tx, id->X[i]);
+ }
+
+ // copy corrected positions back to simulation
+ for(i = 0; i < numverts; i++)
+ {
+ if(result)
+ {
+
+ if((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL) && (verts [i].flags & CLOTH_VERT_FLAG_PINNED))
+ continue;
+
+ VECCOPY(id->Xnew[i], verts[i].tx);
+ VECCOPY(id->Vnew[i], verts[i].tv);
+ VecMulf(id->Vnew[i], clmd->sim_parms->stepsPerFrame);
+ }
+ }
+
+ // X = Xnew;
+ cp_lfvector(id->X, id->Xnew, numverts);
+
+ // if there were collisions, advance the velocity from v_n+1/2 to v_n+1
+
+ if(result)
+ {
+ // V = Vnew;
+ cp_lfvector(id->V, id->Vnew, numverts);
+
+ // calculate
+ effectors= pdInitEffectors(ob,NULL);
+ cloth_calc_force(clmd, id->F, id->X, id->V, id->dFdV, id->dFdX, effectors, step+dt, id->M);
+ if(effectors) pdEndEffectors(effectors);
+
+ simulate_implicit_euler(id->Vnew, id->X, id->V, id->F, id->dFdV, id->dFdX, dt / 2.0f, id->A, id->B, id->dV, id->S, id->z, id->olddV, id->P, id->Pinv, id->M, id->bigI);
+ }
+
+ }
+ else
+ {
+ // X = Xnew;
+ cp_lfvector(id->X, id->Xnew, numverts);
+ }
+
+ // itend();
+ // printf("collision time: %f\n", (float)itval());
+
+ // V = Vnew;
+ cp_lfvector(id->V, id->Vnew, numverts);
+
+ step += dt;
+
+ }
+
+ for(i = 0; i < numverts; i++)
+ {
+ if((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL) && (verts [i].flags & CLOTH_VERT_FLAG_PINNED))
+ {
+ VECCOPY(verts[i].txold, verts[i].xconst); // TODO: test --> should be .x
+ VECCOPY(verts[i].x, verts[i].xconst);
+ VECCOPY(verts[i].v, id->V[i]);
+ }
+ else
+ {
+ VECCOPY(verts[i].txold, id->X[i]);
+ VECCOPY(verts[i].x, id->X[i]);
+ VECCOPY(verts[i].v, id->V[i]);
+ }
+ }
+
+ return 1;
+}
+
+void implicit_set_positions (ClothModifierData *clmd)
+{
+ Cloth *cloth = clmd->clothObject;
+ ClothVertex *verts = cloth->verts;
+ unsigned int numverts = cloth->numverts, i;
+ Implicit_Data *id = cloth->implicit;
+
+ for(i = 0; i < numverts; i++)
+ {
+ VECCOPY(id->X[i], verts[i].x);
+ VECCOPY(id->V[i], verts[i].v);
+ }
+ if(G.rt > 0)
+ printf("implicit_set_positions\n");
+}
+
diff --git a/source/blender/blenkernel/intern/ipo.c b/source/blender/blenkernel/intern/ipo.c
index 78e8f2c5ee0..8407c66d584 100644
--- a/source/blender/blenkernel/intern/ipo.c
+++ b/source/blender/blenkernel/intern/ipo.c
@@ -23,7 +23,7 @@
*
* The Original Code is: all of this file.
*
- * Contributor(s): none yet.
+ * Contributor(s): 2008, Joshua Leung (IPO System cleanup)
*
* ***** END GPL LICENSE BLOCK *****
*/
@@ -72,15 +72,23 @@
#include "BKE_main.h"
#include "BKE_mesh.h"
#include "BKE_object.h"
+
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h" /* for BPY_pydriver_eval() */
+#endif
#define SMALL -1.0e-10
+/* ***************************** Adrcode Blocktype Defines ********************************* */
+
/* This array concept was meant to make sure that defines such as OB_LOC_X
don't have to be enumerated, also for backward compatibility, future changes,
and to enable it all can be accessed with a for-next loop.
+
+ This should whole adrcode system should eventually be replaced by a proper Data API
*/
+
int co_ar[CO_TOTIPO]= {
CO_ENFORCE, CO_HEADTAIL
};
@@ -150,9 +158,9 @@ int wo_ar[WO_TOTIPO]= {
};
int la_ar[LA_TOTIPO]= {
- LA_ENERGY, LA_COL_R, LA_COL_G, LA_COL_B,
+ LA_ENERGY, LA_COL_R, LA_COL_G, LA_COL_B,
LA_DIST, LA_SPOTSI, LA_SPOTBL,
- LA_QUAD1, LA_QUAD2, LA_HALOINT,
+ LA_QUAD1, LA_QUAD2, LA_HALOINT,
MA_MAP1+MAP_OFS_X, MA_MAP1+MAP_OFS_Y, MA_MAP1+MAP_OFS_Z,
MA_MAP1+MAP_SIZE_X, MA_MAP1+MAP_SIZE_Y, MA_MAP1+MAP_SIZE_Z,
@@ -174,460 +182,617 @@ int fluidsim_ar[FLUIDSIM_TOTIPO]= {
FLUIDSIM_VISC, FLUIDSIM_TIME,
FLUIDSIM_GRAV_X , FLUIDSIM_GRAV_Y , FLUIDSIM_GRAV_Z ,
FLUIDSIM_VEL_X , FLUIDSIM_VEL_Y , FLUIDSIM_VEL_Z ,
- FLUIDSIM_ACTIVE
+ FLUIDSIM_ACTIVE,
+ FLUIDSIM_ATTR_FORCE_STR, FLUIDSIM_ATTR_FORCE_RADIUS,
+ FLUIDSIM_VEL_FORCE_STR, FLUIDSIM_VEL_FORCE_RADIUS,
};
int part_ar[PART_TOTIPO]= {
PART_EMIT_FREQ, PART_EMIT_LIFE, PART_EMIT_VEL, PART_EMIT_AVE, PART_EMIT_SIZE,
PART_AVE, PART_SIZE, PART_DRAG, PART_BROWN, PART_DAMP, PART_LENGTH, PART_CLUMP,
PART_GRAV_X, PART_GRAV_Y, PART_GRAV_Z, PART_KINK_AMP, PART_KINK_FREQ, PART_KINK_SHAPE,
- PART_BB_TILT
+ PART_BB_TILT, PART_PD_FSTR, PART_PD_FFALL, PART_PD_FMAXD, PART_PD2_FSTR, PART_PD2_FFALL, PART_PD2_FMAXD
};
+/* ************************** Data-Level Functions ************************* */
+
+/* ---------------------- Freeing --------------------------- */
-float frame_to_float(int cfra) /* see also bsystem_time in object.c */
+/* frees the ipo curve itself too */
+void free_ipo_curve (IpoCurve *icu)
{
- extern float bluroffs; /* bad stuff borrowed from object.c */
- extern float fieldoffs;
- float ctime;
+ if (icu == NULL)
+ return;
- ctime= (float)cfra;
- ctime+= bluroffs+fieldoffs;
- ctime*= G.scene->r.framelen;
+ if (icu->bezt)
+ MEM_freeN(icu->bezt);
+ if (icu->driver)
+ MEM_freeN(icu->driver);
- return ctime;
-}
-
-/* includes ipo curve itself */
-void free_ipo_curve(IpoCurve *icu)
-{
- if(icu->bezt) MEM_freeN(icu->bezt);
- if(icu->bp) MEM_freeN(icu->bp);
- if(icu->driver) MEM_freeN(icu->driver);
MEM_freeN(icu);
}
/* do not free ipo itself */
-void free_ipo(Ipo *ipo)
+void free_ipo (Ipo *ipo)
{
- IpoCurve *icu;
+ IpoCurve *icu, *icn;
+
+ if (ipo == NULL)
+ return;
- while( (icu= ipo->curve.first) ) {
+ for (icu= ipo->curve.first; icu; icu= icn) {
+ icn= icu->next;
+
+ /* must remove the link before freeing, as the curve is freed too */
BLI_remlink(&ipo->curve, icu);
free_ipo_curve(icu);
}
}
+/* ---------------------- Init --------------------------- */
+
/* on adding new ipos, or for empty views */
-void ipo_default_v2d_cur(int blocktype, rctf *cur)
+void ipo_default_v2d_cur (int blocktype, rctf *cur)
{
- if(blocktype==ID_CA) {
- cur->xmin= G.scene->r.sfra;
- cur->xmax= G.scene->r.efra;
- cur->ymin= 0.0;
- cur->ymax= 100.0;
- }
- else if ELEM5(blocktype, ID_MA, ID_CU, ID_WO, ID_LA, ID_CO) {
- cur->xmin= (float)G.scene->r.sfra-0.1;
- cur->xmax= G.scene->r.efra;
- cur->ymin= (float)-0.1;
- cur->ymax= (float)+1.1;
- }
- else if(blocktype==ID_TE) {
- cur->xmin= (float)G.scene->r.sfra-0.1;
- cur->xmax= G.scene->r.efra;
- cur->ymin= (float)-0.1;
- cur->ymax= (float)+1.1;
- }
- else if(blocktype==ID_SEQ) {
- cur->xmin= -5.0;
- cur->xmax= 105.0;
- cur->ymin= (float)-0.1;
- cur->ymax= (float)+1.1;
- }
- else if(blocktype==ID_KE) {
- cur->xmin= (float)G.scene->r.sfra-0.1;
- cur->xmax= G.scene->r.efra;
- cur->ymin= (float)-0.1;
- cur->ymax= (float)+2.1;
- }
- else { /* ID_OB and everything else */
- cur->xmin= G.scene->r.sfra;
- cur->xmax= G.scene->r.efra;
- cur->ymin= -5.0;
- cur->ymax= +5.0;
+ switch (blocktype) {
+ case ID_CA:
+ cur->xmin= (float)G.scene->r.sfra;
+ cur->xmax= (float)G.scene->r.efra;
+ cur->ymin= 0.0f;
+ cur->ymax= 100.0f;
+ break;
+
+ case ID_MA: case ID_WO: case ID_LA:
+ case ID_CU: case ID_CO:
+ cur->xmin= (float)(G.scene->r.sfra - 0.1f);
+ cur->xmax= (float)G.scene->r.efra;
+ cur->ymin= (float)-0.1f;
+ cur->ymax= (float)+1.1f;
+ break;
+
+ case ID_TE:
+ cur->xmin= (float)(G.scene->r.sfra - 0.1f);
+ cur->xmax= (float)G.scene->r.efra;
+ cur->ymin= (float)-0.1f;
+ cur->ymax= (float)+1.1f;
+ break;
+
+ case ID_SEQ:
+ cur->xmin= -5.0f;
+ cur->xmax= 105.0f;
+ cur->ymin= (float)-0.1f;
+ cur->ymax= (float)+1.1f;
+ break;
+
+ case ID_KE:
+ cur->xmin= (float)(G.scene->r.sfra - 0.1f);
+ cur->xmax= (float)G.scene->r.efra;
+ cur->ymin= (float)-0.1f;
+ cur->ymax= (float)+2.1f;
+ break;
+
+ default: /* ID_OB and everything else */
+ cur->xmin= (float)G.scene->r.sfra;
+ cur->xmax= (float)G.scene->r.efra;
+ cur->ymin= -5.0f;
+ cur->ymax= +5.0f;
+ break;
}
}
-
-Ipo *add_ipo(char *name, int idcode)
+/* create a new IPO block (allocates the block) */
+Ipo *add_ipo (char name[], int blocktype)
{
Ipo *ipo;
ipo= alloc_libblock(&G.main->ipo, ID_IP, name);
- ipo->blocktype= idcode;
- ipo_default_v2d_cur(idcode, &ipo->cur);
+ ipo->blocktype= blocktype;
+ ipo_default_v2d_cur(blocktype, &ipo->cur);
return ipo;
}
-Ipo *copy_ipo(Ipo *ipo)
+/* ---------------------- Copy --------------------------- */
+
+/* duplicate an IPO block and all its data */
+Ipo *copy_ipo (Ipo *src)
{
- Ipo *ipon;
+ Ipo *dst;
IpoCurve *icu;
- if(ipo==NULL) return 0;
-
- ipon= copy_libblock(ipo);
+ if (src == NULL)
+ return NULL;
- BLI_duplicatelist(&(ipon->curve), &(ipo->curve));
+ dst= copy_libblock(src);
+ BLI_duplicatelist(&dst->curve, &src->curve);
- for(icu= ipo->curve.first; icu; icu= icu->next) {
+ for (icu= src->curve.first; icu; icu= icu->next) {
icu->bezt= MEM_dupallocN(icu->bezt);
- if(icu->driver) icu->driver= MEM_dupallocN(icu->driver);
+
+ if (icu->driver)
+ icu->driver= MEM_dupallocN(icu->driver);
}
- return ipon;
+ return dst;
}
-/* uses id->newid to match pointers with other copied data */
-void ipo_idnew(Ipo *ipo)
+/* ---------------------- Relink --------------------------- */
+
+/* uses id->newid to match pointers with other copied data
+ * - called after single-user or other such
+ */
+void ipo_idnew (Ipo *ipo)
{
- if(ipo) {
+ if (ipo) {
IpoCurve *icu;
- for(icu= ipo->curve.first; icu; icu= icu->next) {
- if(icu->driver) {
+ for (icu= ipo->curve.first; icu; icu= icu->next) {
+ if (icu->driver)
ID_NEW(icu->driver->ob);
- }
}
}
}
-void make_local_obipo(Ipo *ipo)
+/* --------------------- Find + Check ----------------------- */
+
+/* find the IPO-curve within a given IPO-block with the adrcode of interest */
+IpoCurve *find_ipocurve (Ipo *ipo, int adrcode)
+{
+ if (ipo) {
+ IpoCurve *icu;
+
+ for (icu= ipo->curve.first; icu; icu= icu->next) {
+ if (icu->adrcode == adrcode)
+ return icu;
+ }
+ }
+ return NULL;
+}
+
+/* return whether the given IPO block has a IPO-curve with the given adrcode */
+short has_ipo_code(Ipo *ipo, int adrcode)
+{
+ /* return success of faliure from trying to find such an IPO-curve */
+ return (find_ipocurve(ipo, adrcode) != NULL);
+}
+
+/* ---------------------- Make Local --------------------------- */
+
+
+/* make the given IPO local (for Objects)
+ * - only lib users: do nothing
+ * - only local users: set flag
+ * - mixed: make copy
+ */
+void make_local_obipo (Ipo *src)
{
Object *ob;
- Ipo *ipon;
+ Ipo *dst;
int local=0, lib=0;
- /* - only lib users: do nothing
- * - only local users: set flag
- * - mixed: make copy
- */
-
- ob= G.main->object.first;
- while(ob) {
- if(ob->ipo==ipo) {
- if(ob->id.lib) lib= 1;
+ /* check if only local and/or lib */
+ for (ob= G.main->object.first; ob; ob= ob->id.next) {
+ if (ob->ipo == src) {
+ if (ob->id.lib) lib= 1;
else local= 1;
}
- ob= ob->id.next;
}
- if(local && lib==0) {
- ipo->id.lib= 0;
- ipo->id.flag= LIB_LOCAL;
- new_id(0, (ID *)ipo, 0);
+ /* only local - set flag */
+ if (local && lib==0) {
+ src->id.lib= 0;
+ src->id.flag= LIB_LOCAL;
+ new_id(0, (ID *)src, 0);
}
- else if(local && lib) {
- ipon= copy_ipo(ipo);
- ipon->id.us= 0;
+ /* mixed: make copy */
+ else if (local && lib) {
+ dst= copy_ipo(src);
+ dst->id.us= 0;
- ob= G.main->object.first;
- while(ob) {
- if(ob->ipo==ipo) {
-
- if(ob->id.lib==NULL) {
- ob->ipo= ipon;
- ipon->id.us++;
- ipo->id.us--;
+ for (ob= G.main->object.first; ob; ob= ob->id.next) {
+ if (ob->ipo == src) {
+ if (ob->id.lib == NULL) {
+ ob->ipo= dst;
+ dst->id.us++;
+ src->id.us--;
}
}
- ob= ob->id.next;
}
}
}
-void make_local_matipo(Ipo *ipo)
+/* make the given IPO local (for Materials)
+ * - only lib users: do nothing
+ * - only local users: set flag
+ * - mixed: make copy
+ */
+void make_local_matipo (Ipo *src)
{
Material *ma;
- Ipo *ipon;
+ Ipo *dst;
int local=0, lib=0;
-
- /* - only lib users: do nothing
- * - only local users: set flag
- * - mixed: make copy
- */
- ma= G.main->mat.first;
- while(ma) {
- if(ma->ipo==ipo) {
- if(ma->id.lib) lib= 1;
+ /* check if only local and/or lib */
+ for (ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if (ma->ipo == src) {
+ if (ma->id.lib) lib= 1;
else local= 1;
}
- ma= ma->id.next;
}
- if(local && lib==0) {
- ipo->id.lib= 0;
- ipo->id.flag= LIB_LOCAL;
- new_id(0, (ID *)ipo, 0);
+ /* only local - set flag */
+ if (local && lib==0) {
+ src->id.lib= 0;
+ src->id.flag= LIB_LOCAL;
+ new_id(0, (ID *)src, 0);
}
- else if(local && lib) {
- ipon= copy_ipo(ipo);
- ipon->id.us= 0;
+ /* mixed: make copy */
+ else if (local && lib) {
+ dst= copy_ipo(src);
+ dst->id.us= 0;
- ma= G.main->mat.first;
- while(ma) {
- if(ma->ipo==ipo) {
-
- if(ma->id.lib==NULL) {
- ma->ipo= ipon;
- ipon->id.us++;
- ipo->id.us--;
+ for (ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if (ma->ipo == src) {
+ if (ma->id.lib == NULL) {
+ ma->ipo= dst;
+ dst->id.us++;
+ src->id.us--;
}
}
- ma= ma->id.next;
}
}
}
-void make_local_keyipo(Ipo *ipo)
+/* make the given IPO local (for ShapeKeys)
+ * - only lib users: do nothing
+ * - only local users: set flag
+ * - mixed: make copy
+ */
+void make_local_keyipo (Ipo *src)
{
Key *key;
- Ipo *ipon;
+ Ipo *dst;
int local=0, lib=0;
-
- /* - only lib users: do nothing
- * - only local users: set flag
- * - mixed: make copy
- */
- key= G.main->key.first;
- while(key) {
- if(key->ipo==ipo) {
- if(key->id.lib) lib= 1;
+ /* check if only local and/or lib */
+ for (key= G.main->key.first; key; key= key->id.next) {
+ if (key->ipo == src) {
+ if (key->id.lib) lib= 1;
else local= 1;
}
- key= key->id.next;
}
- if(local && lib==0) {
- ipo->id.lib= 0;
- ipo->id.flag= LIB_LOCAL;
- new_id(0, (ID *)ipo, 0);
+ /* only local - set flag */
+ if (local && lib==0) {
+ src->id.lib= 0;
+ src->id.flag= LIB_LOCAL;
+ new_id(0, (ID *)src, 0);
}
- else if(local && lib) {
- ipon= copy_ipo(ipo);
- ipon->id.us= 0;
+ /* mixed: make copy */
+ else if (local && lib) {
+ dst= copy_ipo(src);
+ dst->id.us= 0;
- key= G.main->key.first;
- while(key) {
- if(key->ipo==ipo) {
-
- if(key->id.lib==NULL) {
- key->ipo= ipon;
- ipon->id.us++;
- ipo->id.us--;
+ for (key= G.main->key.first; key; key= key->id.next) {
+ if (key->ipo == src) {
+ if (key->id.lib == NULL) {
+ key->ipo= dst;
+ dst->id.us++;
+ src->id.us--;
}
}
- key= key->id.next;
}
}
}
-void make_local_ipo(Ipo *ipo)
+/* generic call to make IPO's local */
+void make_local_ipo (Ipo *ipo)
{
-
- if(ipo->id.lib==NULL) return;
- if(ipo->id.us==1) {
+ /* can't touch lib-linked data */
+ if (ipo->id.lib == NULL)
+ return;
+
+ /* with only one user, just set local flag */
+ if (ipo->id.us == 1) {
ipo->id.lib= 0;
ipo->id.flag= LIB_LOCAL;
new_id(0, (ID *)ipo, 0);
return;
}
- if(ipo->blocktype==ID_OB) make_local_obipo(ipo);
- else if(ipo->blocktype==ID_MA) make_local_matipo(ipo);
- else if(ipo->blocktype==ID_KE) make_local_keyipo(ipo);
-
+ /* when more than 1 user, can only make local for certain blocktypes */
+ switch (ipo->blocktype) {
+ case ID_OB:
+ make_local_obipo(ipo);
+ break;
+ case ID_MA:
+ make_local_matipo(ipo);
+ break;
+ case ID_KE:
+ make_local_keyipo(ipo);
+ break;
+ }
}
-IpoCurve *find_ipocurve(Ipo *ipo, int adrcode)
+/* ***************************** Keyframe Column Tools ********************************* */
+
+/* add a BezTriple to a column */
+void add_to_cfra_elem(ListBase *lb, BezTriple *bezt)
{
- if(ipo) {
- IpoCurve *icu;
- for(icu= ipo->curve.first; icu; icu= icu->next) {
- if(icu->adrcode==adrcode) return icu;
+ CfraElem *ce, *cen;
+
+ for (ce= lb->first; ce; ce= ce->next) {
+ /* double key? */
+ if (ce->cfra == bezt->vec[1][0]) {
+ if (bezt->f2 & SELECT) ce->sel= bezt->f2;
+ return;
}
+ /* should key be inserted before this column? */
+ else if (ce->cfra > bezt->vec[1][0]) break;
}
- return NULL;
+
+ /* create a new column */
+ cen= MEM_callocN(sizeof(CfraElem), "add_to_cfra_elem");
+ if (ce) BLI_insertlinkbefore(lb, ce, cen);
+ else BLI_addtail(lb, cen);
+
+ cen->cfra= bezt->vec[1][0];
+ cen->sel= bezt->f2;
}
-void calchandles_ipocurve(IpoCurve *icu)
+/* make a list of keyframe 'columns' in an IPO block */
+void make_cfra_list (Ipo *ipo, ListBase *elems)
{
- BezTriple *bezt, *prev, *next;
+ IpoCurve *icu;
+ BezTriple *bezt;
int a;
+
+ for (icu= ipo->curve.first; icu; icu= icu->next) {
+ if (icu->flag & IPO_VISIBLE) {
+ /* ... removed old checks for adrcode types from here ...
+ * - (was this used for IpoKeys in the past?)
+ */
+
+ bezt= icu->bezt;
+ if (bezt) {
+ for (a=0; a < icu->totvert; a++, bezt++) {
+ add_to_cfra_elem(elems, bezt);
+ }
+ }
+ }
+ }
+}
+
+/* ***************************** Timing Stuff ********************************* */
- a= icu->totvert;
+/* This (evil) function is needed to cope with two legacy Blender rendering features
+ * mblur (motion blur that renders 'subframes' and blurs them together), and fields
+ * rendering. Thus, the use of ugly globals from object.c
+ */
+// BAD... EVIL... JUJU...!!!!
+float frame_to_float (int cfra) /* see also bsystem_time in object.c */
+{
+ extern float bluroffs; /* bad stuff borrowed from object.c */
+ extern float fieldoffs;
+ float ctime;
- /* IPO_CONST doesn't have handles */
- if(a<2 || icu->ipo==IPO_CONST) return;
+ ctime= (float)cfra;
+ ctime+= bluroffs+fieldoffs;
+ ctime*= G.scene->r.framelen;
- bezt= icu->bezt;
- prev= 0;
- next= bezt+1;
+ return ctime;
+}
- while(a--) {
+/* ***************************** IPO Curve Sanity ********************************* */
+/* The functions here are used in various parts of Blender, usually after some editing
+ * of keyframe data has occurred. They ensure that keyframe data is properly ordered and
+ * that the handles are correctly
+ */
- if(bezt->vec[0][0]>bezt->vec[1][0]) bezt->vec[0][0]= bezt->vec[1][0];
- if(bezt->vec[2][0]<bezt->vec[1][0]) bezt->vec[2][0]= bezt->vec[1][0];
+/* This function recalculates the handles of an IPO-Curve
+ * If the BezTriples have been rearranged, sort them first before using this.
+ */
+void calchandles_ipocurve (IpoCurve *icu)
+{
+ BezTriple *bezt, *prev, *next;
+ int a= icu->totvert;
- if(icu->flag & IPO_AUTO_HORIZ)
+ /* Error checking:
+ * - need at least two points
+ * - need bezier keys
+ * - only bezier-interpolation has handles (for now)
+ */
+ if (ELEM(NULL, icu, icu->bezt) || (a < 2) || ELEM(icu->ipo, IPO_CONST, IPO_LIN))
+ return;
+
+ /* get initial pointers */
+ bezt= icu->bezt;
+ prev= NULL;
+ next= (bezt + 1);
+
+ /* loop over all beztriples, adjusting handles */
+ while (a--) {
+ /* clamp timing of handles to be on either side of beztriple */
+ if (bezt->vec[0][0] > bezt->vec[1][0]) bezt->vec[0][0]= bezt->vec[1][0];
+ if (bezt->vec[2][0] < bezt->vec[1][0]) bezt->vec[2][0]= bezt->vec[1][0];
+
+ /* calculate autohandles */
+ if (icu->flag & IPO_AUTO_HORIZ)
calchandleNurb(bezt, prev, next, 2); /* 2==special autohandle && keep extrema horizontal */
else
calchandleNurb(bezt, prev, next, 1); /* 1==special autohandle */
-
- prev= bezt;
- if(a==1) {
- next= 0;
- }
- else next++;
-
+
/* for automatic ease in and out */
- if(bezt->h1==HD_AUTO && bezt->h2==HD_AUTO) {
- if(a==0 || a==icu->totvert-1) {
- if(icu->extrap==IPO_HORIZ) {
+ if ((bezt->h1==HD_AUTO) && (bezt->h2==HD_AUTO)) {
+ /* only do this on first or last beztriple */
+ if ((a==0) || (a==icu->totvert-1)) {
+ /* set both handles to have same horizontal value as keyframe */
+ if (icu->extrap==IPO_HORIZ) {
bezt->vec[0][1]= bezt->vec[2][1]= bezt->vec[1][1];
}
}
}
+ /* advance pointers for next iteration */
+ prev= bezt;
+ if (a == 1) next= NULL;
+ else next++;
bezt++;
}
}
-void testhandles_ipocurve(IpoCurve *icu)
+/* Use when IPO-Curve with handles has changed
+ * It treats all BezTriples with the following rules:
+ * - PHASE 1: do types have to be altered?
+ * -> Auto handles: become aligned when selection status is NOT(000 || 111)
+ * -> Vector handles: become 'nothing' when (one half selected AND other not)
+ * - PHASE 2: recalculate handles
+*/
+void testhandles_ipocurve (IpoCurve *icu)
{
- /* use when something has changed with handles.
- it treats all BezTriples with the following rules:
- PHASE 1: do types have to be altered?
- Auto handles: become aligned when selection status is NOT(000 || 111)
- Vector handles: become 'nothing' when (one half selected AND other not)
- PHASE 2: recalculate handles
- */
- BezTriple *bezt;
- int flag, a;
+ BezTriple *bezt;
+ int a;
- bezt= icu->bezt;
- if(bezt==NULL) return;
+ /* only beztriples have handles (bpoints don't though) */
+ if (ELEM(NULL, icu, icu->bezt))
+ return;
- a= icu->totvert;
- while(a--) {
- flag= 0;
- if(bezt->f1 & SELECT) flag++;
- if(bezt->f2 & SELECT) flag += 2;
- if(bezt->f3 & SELECT) flag += 4;
-
- if( !(flag==0 || flag==7) ) {
- if(bezt->h1==HD_AUTO) { /* auto */
+ /* loop over beztriples */
+ for (a=0, bezt=icu->bezt; a < icu->totvert; a++, bezt++) {
+ short flag= 0;
+
+ /* flag is initialised as selection status
+ * of beztriple control-points (labelled 0,1,2)
+ */
+ if (bezt->f1 & SELECT) flag |= (1<<0); // == 1
+ if (bezt->f2 & SELECT) flag |= (1<<1); // == 2
+ if (bezt->f3 & SELECT) flag |= (1<<2); // == 4
+
+ /* one or two handles selected only */
+ if (ELEM(flag, 0, 7)==0) {
+ /* auto handles become aligned */
+ if (bezt->h1==HD_AUTO)
bezt->h1= HD_ALIGN;
- }
- if(bezt->h2==HD_AUTO) { /* auto */
+ if(bezt->h2==HD_AUTO)
bezt->h2= HD_ALIGN;
+
+ /* vector handles become 'free' when only one half selected */
+ if(bezt->h1==HD_VECT) {
+ /* only left half (1 or 2 or 1+2) */
+ if (flag < 4)
+ bezt->h1= 0;
}
-
- if(bezt->h1==HD_VECT) { /* vector */
- if(flag < 4) bezt->h1= 0;
- }
- if(bezt->h2==HD_VECT) { /* vector */
- if( flag > 3) bezt->h2= 0;
+ if(bezt->h2==HD_VECT) {
+ /* only right half (4 or 2+4) */
+ if (flag > 3)
+ bezt->h2= 0;
}
}
- bezt++;
}
+ /* recalculate handles */
calchandles_ipocurve(icu);
}
-
+/* This function sorts BezTriples so that they are arranged in chronological order,
+ * as tools working on IPO-Curves expect that the BezTriples are in order.
+ */
void sort_time_ipocurve(IpoCurve *icu)
{
- BezTriple *bezt;
- int a, ok= 1;
+ short ok= 1;
- while(ok) {
+ /* keep adjusting order of beztriples until nothing moves (bubble-sort) */
+ while (ok) {
ok= 0;
-
- if(icu->bezt) {
- bezt= icu->bezt;
- a= icu->totvert;
- while(a--) {
- if(a>0) {
- if( bezt->vec[1][0] > (bezt+1)->vec[1][0]) {
+
+ /* currently, will only be needed when there are beztriples */
+ if (icu->bezt) {
+ BezTriple *bezt;
+ int a;
+
+ /* loop over ALL points to adjust position in array and recalculate handles */
+ for (a=0, bezt=icu->bezt; a < icu->totvert; a++, bezt++) {
+ /* check if thee's a next beztriple which we could try to swap with current */
+ if (a < (icu->totvert-1)) {
+ /* swap if one is after the other (and indicate that order has changed) */
+ if (bezt->vec[1][0] > (bezt+1)->vec[1][0]) {
SWAP(BezTriple, *bezt, *(bezt+1));
ok= 1;
}
+
+ /* if either one of both of the points exceeds crosses over the keyframe time... */
+ if ( (bezt->vec[0][0] > bezt->vec[1][0]) && (bezt->vec[2][0] < bezt->vec[1][0]) ) {
+ /* swap handles if they have switched sides for some reason */
+ SWAP(float, bezt->vec[0][0], bezt->vec[2][0]);
+ SWAP(float, bezt->vec[0][1], bezt->vec[2][1]);
+ }
+ else {
+ /* clamp handles */
+ if (bezt->vec[0][0] > bezt->vec[1][0])
+ bezt->vec[0][0]= bezt->vec[1][0];
+ if (bezt->vec[2][0] < bezt->vec[1][0])
+ bezt->vec[2][0]= bezt->vec[1][0];
+ }
}
- if(bezt->vec[0][0]>bezt->vec[1][0] && bezt->vec[2][0]<bezt->vec[1][0]) {
- SWAP(float, bezt->vec[0][0], bezt->vec[2][0]);
- SWAP(float, bezt->vec[0][1], bezt->vec[2][1]);
- }
- else {
- if(bezt->vec[0][0]>bezt->vec[1][0]) bezt->vec[0][0]= bezt->vec[1][0];
- if(bezt->vec[2][0]<bezt->vec[1][0]) bezt->vec[2][0]= bezt->vec[1][0];
- }
- bezt++;
}
}
- else {
-
- }
}
}
-int test_time_ipocurve(IpoCurve *icu)
+/* This function tests if any BezTriples are out of order, thus requiring a sort */
+int test_time_ipocurve (IpoCurve *icu)
{
- BezTriple *bezt;
int a;
- if(icu->bezt) {
- bezt= icu->bezt;
- a= icu->totvert-1;
- while(a--) {
- if( bezt->vec[1][0] > (bezt+1)->vec[1][0]) {
- return 1;
- }
- bezt++;
- }
- }
- else {
+ /* currently, only need to test beztriples */
+ if (icu->bezt) {
+ BezTriple *bezt;
+ /* loop through all beztriples, stopping when one exceeds the one after it */
+ for (a=0, bezt= icu->bezt; a < (icu->totvert - 1); a++, bezt++) {
+ if (bezt->vec[1][0] > (bezt+1)->vec[1][0])
+ return 1;
+ }
}
-
+
+ /* none need any swapping */
return 0;
}
-void correct_bezpart(float *v1, float *v2, float *v3, float *v4)
+/* --------- */
+
+/* The total length of the handles is not allowed to be more
+ * than the horizontal distance between (v1-v4).
+ * This is to prevent curve loops.
+*/
+void correct_bezpart (float *v1, float *v2, float *v3, float *v4)
{
- /* the total length of the handles is not allowed to be more
- * than the horizontal distance between (v1-v4)
- * this to prevent curve loops
- */
float h1[2], h2[2], len1, len2, len, fac;
+ /* calculate handle deltas */
h1[0]= v1[0]-v2[0];
h1[1]= v1[1]-v2[1];
h2[0]= v4[0]-v3[0];
h2[1]= v4[1]-v3[1];
+ /* calculate distances:
+ * - len = span of time between keyframes
+ * - len1 = length of handle of start key
+ * - len2 = length of handle of end key
+ */
len= v4[0]- v1[0];
len1= (float)fabs(h1[0]);
len2= (float)fabs(h2[0]);
- if(len1+len2==0.0) return;
- if(len1+len2 > len) {
+ /* if the handles have no length, no need to do any corrections */
+ if ((len1+len2) == 0.0)
+ return;
+
+ /* the two handles cross over each other, so force them
+ * apart using the proportion they overlap
+ */
+ if ((len1+len2) > len) {
fac= len/(len1+len2);
v2[0]= (v1[0]-fac*h1[0]);
@@ -635,57 +800,86 @@ void correct_bezpart(float *v1, float *v2, float *v3, float *v4)
v3[0]= (v4[0]-fac*h2[0]);
v3[1]= (v4[1]-fac*h2[1]);
-
}
}
-/* *********************** ARITH *********************** */
+#if 0 // TODO: enable when we have per-segment interpolation
+/* This function sets the interpolation mode for an entire Ipo-Curve.
+ * It is primarily used for patching old files, but is also used in the interface
+ * to make sure that all segments of the curve use the same interpolation.
+ */
+void set_interpolation_ipocurve (IpoCurve *icu, short ipo)
+{
+ BezTriple *bezt;
+ int a;
+
+ /* validate arguments */
+ if (icu == NULL) return;
+ if (ELEM3(ipo, IPO_CONST, IPO_LIN, IPO_BEZ)==0) return;
-int findzero(float x, float q0, float q1, float q2, float q3, float *o)
+ /* set interpolation mode for whole curve */
+ icu->ipo= ipo;
+
+ /* set interpolation mode of all beztriples */
+ for (a=0, bezt=icu->bezt; a<icu->totvert; a++, bezt++)
+ bezt->ipo= ipo;
+}
+#endif // TODO: enable when we have per-segment interpolation
+
+/* ***************************** Curve Calculations ********************************* */
+
+/* find root/zero */
+int findzero (float x, float q0, float q1, float q2, float q3, float *o)
{
double c0, c1, c2, c3, a, b, c, p, q, d, t, phi;
int nr= 0;
- c0= q0-x;
- c1= 3*(q1-q0);
- c2= 3*(q0-2*q1+q2);
- c3= q3-q0+3*(q1-q2);
+ c0= q0 - x;
+ c1= 3 * (q1 - q0);
+ c2= 3 * (q0 - 2*q1 + q2);
+ c3= q3 - q0 + 3 * (q1 - q2);
- if(c3!=0.0) {
+ if (c3 != 0.0) {
a= c2/c3;
b= c1/c3;
c= c0/c3;
a= a/3;
-
- p= b/3-a*a;
- q= (2*a*a*a-a*b+c)/2;
- d= q*q+p*p*p;
-
- if(d>0.0) {
+
+ p= b/3 - a*a;
+ q= (2*a*a*a - a*b + c) / 2;
+ d= q*q + p*p*p;
+
+ if (d > 0.0) {
t= sqrt(d);
- o[0]= (float)(Sqrt3d(-q+t)+Sqrt3d(-q-t)-a);
- if(o[0]>= SMALL && o[0]<=1.000001) return 1;
+ o[0]= (float)(Sqrt3d(-q+t) + Sqrt3d(-q-t) - a);
+
+ if ((o[0] >= SMALL) && (o[0] <= 1.000001)) return 1;
else return 0;
}
- else if(d==0.0) {
+ else if (d == 0.0) {
t= Sqrt3d(-q);
- o[0]= (float)(2*t-a);
- if(o[0]>=SMALL && o[0]<=1.000001) nr++;
+ o[0]= (float)(2*t - a);
+
+ if ((o[0] >= SMALL) && (o[0] <= 1.000001)) nr++;
o[nr]= (float)(-t-a);
- if(o[nr]>=SMALL && o[nr]<=1.000001) return nr+1;
+
+ if ((o[nr] >= SMALL) && (o[nr] <= 1.000001)) return nr+1;
else return nr;
}
else {
- phi= acos(-q/sqrt(-(p*p*p)));
+ phi= acos(-q / sqrt(-(p*p*p)));
t= sqrt(-p);
p= cos(phi/3);
- q= sqrt(3-3*p*p);
- o[0]= (float)(2*t*p-a);
- if(o[0]>=SMALL && o[0]<=1.000001) nr++;
- o[nr]= (float)(-t*(p+q)-a);
- if(o[nr]>=SMALL && o[nr]<=1.000001) nr++;
- o[nr]= (float)(-t*(p-q)-a);
- if(o[nr]>=SMALL && o[nr]<=1.000001) return nr+1;
+ q= sqrt(3 - 3*p*p);
+ o[0]= (float)(2*t*p - a);
+
+ if ((o[0] >= SMALL) && (o[0] <= 1.000001)) nr++;
+ o[nr]= (float)(-t * (p + q) - a);
+
+ if ((o[nr] >= SMALL) && (o[nr] <= 1.000001)) nr++;
+ o[nr]= (float)(-t * (p - q) - a);
+
+ if ((o[nr] >= SMALL) && (o[nr] <= 1.000001)) return nr+1;
else return nr;
}
}
@@ -694,83 +888,97 @@ int findzero(float x, float q0, float q1, float q2, float q3, float *o)
b=c1;
c=c0;
- if(a!=0.0) {
- p=b*b-4*a*c;
- if(p>0) {
+ if (a != 0.0) {
+ // discriminant
+ p= b*b - 4*a*c;
+
+ if (p > 0) {
p= sqrt(p);
- o[0]= (float)((-b-p)/(2*a));
- if(o[0]>=SMALL && o[0]<=1.000001) nr++;
+ o[0]= (float)((-b-p) / (2 * a));
+
+ if ((o[0] >= SMALL) && (o[0] <= 1.000001)) nr++;
o[nr]= (float)((-b+p)/(2*a));
- if(o[nr]>=SMALL && o[nr]<=1.000001) return nr+1;
+
+ if ((o[nr] >= SMALL) && (o[nr] <= 1.000001)) return nr+1;
else return nr;
}
- else if(p==0) {
- o[0]= (float)(-b/(2*a));
- if(o[0]>=SMALL && o[0]<=1.000001) return 1;
+ else if (p == 0) {
+ o[0]= (float)(-b / (2 * a));
+ if ((o[0] >= SMALL) && (o[0] <= 1.000001)) return 1;
else return 0;
}
}
- else if(b!=0.0) {
+ else if (b != 0.0) {
o[0]= (float)(-c/b);
- if(o[0]>=SMALL && o[0]<=1.000001) return 1;
+
+ if ((o[0] >= SMALL) && (o[0] <= 1.000001)) return 1;
else return 0;
}
- else if(c==0.0) {
+ else if (c == 0.0) {
o[0]= 0.0;
return 1;
}
+
return 0;
}
}
-void berekeny(float f1, float f2, float f3, float f4, float *o, int b)
+void berekeny (float f1, float f2, float f3, float f4, float *o, int b)
{
float t, c0, c1, c2, c3;
int a;
c0= f1;
- c1= 3.0f*(f2 - f1);
- c2= 3.0f*(f1 - 2.0f*f2 + f3);
- c3= f4 - f1 + 3.0f*(f2-f3);
+ c1= 3.0f * (f2 - f1);
+ c2= 3.0f * (f1 - 2.0f*f2 + f3);
+ c3= f4 - f1 + 3.0f * (f2 - f3);
- for(a=0; a<b; a++) {
+ for (a=0; a < b; a++) {
t= o[a];
- o[a]= c0+t*c1+t*t*c2+t*t*t*c3;
+ o[a]= c0 + t*c1 + t*t*c2 + t*t*t*c3;
}
}
-void berekenx(float *f, float *o, int b)
+void berekenx (float *f, float *o, int b)
{
float t, c0, c1, c2, c3;
int a;
c0= f[0];
- c1= 3*(f[3]-f[0]);
- c2= 3*(f[0]-2*f[3]+f[6]);
- c3= f[9]-f[0]+3*(f[3]-f[6]);
- for(a=0; a<b; a++) {
+ c1= 3 * (f[3] - f[0]);
+ c2= 3 * (f[0] - 2*f[3] + f[6]);
+ c3= f[9] - f[0] + 3 * (f[3] - f[6]);
+
+ for (a=0; a < b; a++) {
t= o[a];
- o[a]= c0+t*c1+t*t*c2+t*t*t*c3;
+ o[a]= c0 + t*c1 + t*t*c2 + t*t*t*c3;
}
}
-/* we need the local transform = current transform - (parent transform + bone transform) */
-/* (local transform is on action channel level) */
-static void posechannel_get_local_transform(bPoseChannel *pchan, float *loc, float *eul, float *size)
+/* ***************************** IPO - Calculations ********************************* */
+
+/* ---------------------- Curve Evaluation --------------------------- */
+
+/* helper function for evaluating drivers:
+ * - we need the local transform = current transform - (parent transform + bone transform)
+ * - (local transform is on action channel level)
+ */
+static void posechannel_get_local_transform (bPoseChannel *pchan, float loc[], float eul[], float size[])
{
- float diff_mat[4][4];
float parmat[4][4], offs_bone[4][4], imat[4][4];
+ float diff_mat[4][4];
+ /* get first the parent + bone transform in parmat */
if (pchan->parent) {
- /* get first the parent + bone transform in parmat */
-
/* bone transform itself */
Mat4CpyMat3(offs_bone, pchan->bone->bone_mat);
+
/* The bone's root offset (is in the parent's coordinate system) */
VECCOPY(offs_bone[3], pchan->bone->head);
+
/* Get the length translation of parent (length along y axis) */
offs_bone[3][1]+= pchan->parent->bone->length;
-
+
Mat4MulSerie(parmat, pchan->parent->pose_mat, offs_bone, NULL, NULL, NULL, NULL, NULL, NULL);
/* invert it */
@@ -779,64 +987,83 @@ static void posechannel_get_local_transform(bPoseChannel *pchan, float *loc, flo
else {
Mat4CpyMat3(offs_bone, pchan->bone->bone_mat);
VECCOPY(offs_bone[3], pchan->bone->head);
-
+
/* invert it */
Mat4Invert(imat, offs_bone);
-
}
/* difference: current transform - (parent transform + bone transform) */
Mat4MulMat4(diff_mat, pchan->pose_mat, imat);
- if(loc)
+ /* extract relevant components */
+ if (loc)
VECCOPY(loc, diff_mat[3]);
- if(eul)
+ if (eul)
Mat4ToEul(diff_mat, eul);
- if(size)
+ if (size)
Mat4ToSize(diff_mat, size);
-
}
-/* has to return a float value */
-static float eval_driver(IpoDriver *driver, float ipotime)
+/* evaluate an IPO-driver to get a 'time' value to use instead of "ipotime"
+ * - "ipotime" is the frame at which IPO-curve is being evaluated
+ * - has to return a float value
+ */
+static float eval_driver (IpoDriver *driver, float ipotime)
{
-
- if(driver->type == IPO_DRIVER_TYPE_PYTHON) {
+#ifndef DISABLE_PYTHON
+ /* currently, drivers are either PyDrivers (evaluating a PyExpression, or Object/Pose-Channel transforms) */
+ if (driver->type == IPO_DRIVER_TYPE_PYTHON) {
/* check for empty or invalid expression */
- if ((driver->name[0] == '\0') ||
- (driver->flag & IPO_DRIVER_FLAG_INVALID))
+ if ( (driver->name[0] == '\0') ||
+ (driver->flag & IPO_DRIVER_FLAG_INVALID) )
+ {
return 0.0f;
- /* this evals the expression and returns its result:
- * (on errors it reports, then returns 0.0f) */
+ }
+
+ /* this evaluates the expression using Python,and returns its result:
+ * - on errors it reports, then returns 0.0f
+ */
return BPY_pydriver_eval(driver);
}
- else {
- Object *ob= driver->ob;
+ else
+#endif /* DISABLE_PYTHON */
+ {
- if(ob==NULL) return 0.0f;
- if(ob->proxy_from)
+ Object *ob= driver->ob;
+
+ /* must have an object to evaluate */
+ if (ob == NULL)
+ return 0.0f;
+
+ /* if a proxy, use the proxy source*/
+ if (ob->proxy_from)
ob= ob->proxy_from;
- if(driver->blocktype==ID_OB) {
- /* depsgraph failure; ob ipos are calculated in where_is_object, this might get called too late */
- if(ob->ipo && ob->ctime!=ipotime) {
+ /* use given object as driver */
+ if (driver->blocktype == ID_OB) {
+ /* depsgraph failure: ob ipos are calculated in where_is_object, this might get called too late */
+ if ((ob->ipo) && (ob->ctime != ipotime)) {
+ /* calculate the value of relevant channel on the Object, but do not write the value
+ * calculated on to the Object but onto "ipotime" instead
+ */
calc_ipo_spec(ob->ipo, driver->adrcode, &ipotime);
return ipotime;
}
- switch(driver->adrcode) {
+ /* return the value of the relevant channel */
+ switch (driver->adrcode) {
case OB_LOC_X:
return ob->loc[0];
case OB_LOC_Y:
return ob->loc[1];
case OB_LOC_Z:
return ob->loc[2];
- case OB_ROT_X:
- return ob->rot[0]/(M_PI_2/9.0);
- case OB_ROT_Y:
- return ob->rot[1]/(M_PI_2/9.0);
- case OB_ROT_Z:
- return ob->rot[2]/(M_PI_2/9.0);
+ case OB_ROT_X: /* hack: euler rotations are divided by 10 deg to fit on same axes as other channels */
+ return (float)( ob->rot[0]/(M_PI_2/9.0) );
+ case OB_ROT_Y: /* hack: euler rotations are divided by 10 deg to fit on same axes as other channels */
+ return (float)( ob->rot[1]/(M_PI_2/9.0) );
+ case OB_ROT_Z: /* hack: euler rotations are divided by 10 deg to fit on same axes as other channels */
+ return (float)( ob->rot[2]/(M_PI_2/9.0) );
case OB_SIZE_X:
return ob->size[0];
case OB_SIZE_Y:
@@ -845,14 +1072,20 @@ static float eval_driver(IpoDriver *driver, float ipotime)
return ob->size[2];
}
}
+
+ /* use given pose-channel as driver */
else { /* ID_AR */
bPoseChannel *pchan= get_pose_channel(ob->pose, driver->name);
- if(pchan && pchan->bone) {
-
- /* rotation difference is not a simple driver (i.e. value drives value), but the angle between 2 bones is driving stuff... which is useful */
- if(driver->adrcode==OB_ROT_DIFF) {
+
+ /* must have at least 1 bone to use */
+ if (pchan && pchan->bone) {
+ /* rotation difference is not a simple driver (i.e. value drives value), but the angle between 2 bones is driving stuff...
+ * - the name of the second pchan is also stored in driver->name, but packed after the other one by DRIVER_NAME_OFFS chars
+ */
+ if (driver->adrcode == OB_ROT_DIFF) {
bPoseChannel *pchan2= get_pose_channel(ob->pose, driver->name+DRIVER_NAME_OFFS);
- if(pchan2 && pchan2->bone) {
+
+ if (pchan2 && pchan2->bone) {
float q1[4], q2[4], quat[4], angle;
Mat4ToQuat(pchan->pose_mat, q1);
@@ -863,27 +1096,33 @@ static float eval_driver(IpoDriver *driver, float ipotime)
angle = 2.0f * (saacos(quat[0]));
angle= ABS(angle);
- return angle>M_PI?2.0f*M_PI-angle:angle;
+ return (angle > M_PI) ? (float)((2.0f * M_PI) - angle) : (float)(angle);
}
}
+
+ /* standard driver */
else {
float loc[3], eul[3], size[3];
+ /* retrieve local transforms to return
+ * - we use eulers here NOT quats, so that Objects can be driven by bones easily
+ * also, this way is more understandable for users
+ */
posechannel_get_local_transform(pchan, loc, eul, size);
-
- switch(driver->adrcode) {
+
+ switch (driver->adrcode) {
case OB_LOC_X:
return loc[0];
case OB_LOC_Y:
return loc[1];
case OB_LOC_Z:
return loc[2];
- case OB_ROT_X:
- return eul[0]/(M_PI_2/9.0);
- case OB_ROT_Y:
- return eul[1]/(M_PI_2/9.0);
- case OB_ROT_Z:
- return eul[2]/(M_PI_2/9.0);
+ case OB_ROT_X: /* hack: euler rotations are divided by 10 deg to fit on same axes as other channels */
+ return (float)( eul[0]/(M_PI_2/9.0) );
+ case OB_ROT_Y: /* hack: euler rotations are divided by 10 deg to fit on same axes as other channels */
+ return (float)( eul[1]/(M_PI_2/9.0) );
+ case OB_ROT_Z: /* hack: euler rotations are divided by 10 deg to fit on same axes as other channels */
+ return (float)( eul[2]/(M_PI_2/9.0) );
case OB_SIZE_X:
return size[0];
case OB_SIZE_Y:
@@ -895,227 +1134,722 @@ static float eval_driver(IpoDriver *driver, float ipotime)
}
}
}
+
+ /* return 0.0f, as couldn't find relevant data to use */
return 0.0f;
}
-float eval_icu(IpoCurve *icu, float ipotime)
+/* evaluate and return the value of the given IPO-curve at the specified frame ("evaltime") */
+float eval_icu(IpoCurve *icu, float evaltime)
{
- BezTriple *bezt, *prevbezt;
- float v1[2], v2[2], v3[2], v4[2], opl[32], dx, fac;
- float cycdx, cycdy, ofs, cycyofs, cvalue = 0.0;
- int a, b;
+ float cvalue = 0.0f;
- cycyofs= 0.0;
-
- if(icu->driver) {
+ /* if there is a driver, evaluate it to find value to use as "evaltime"
+ * - this value will also be returned as the value of the 'curve', if there are no keyframes
+ */
+ if (icu->driver) {
/* ipotime now serves as input for the curve */
- ipotime= cvalue= eval_driver(icu->driver, ipotime);
+ evaltime= cvalue= eval_driver(icu->driver, evaltime);
}
- if(icu->bezt) {
+
+ /* there are keyframes (in the form of BezTriples) which can be interpolated between */
+ if (icu->bezt) {
+ /* get pointers */
+ BezTriple *bezt, *prevbezt, *lastbezt;
+ float v1[2], v2[2], v3[2], v4[2], opl[32], dx, fac;
+ float cycdx, cycdy, ofs, cycyofs= 0.0;
+ int a, b;
+
+ /* get pointers */
+ a= icu->totvert-1;
prevbezt= icu->bezt;
bezt= prevbezt+1;
- a= icu->totvert-1;
+ lastbezt= prevbezt + a;
- /* cyclic? */
- if(icu->extrap & IPO_CYCL) {
- ofs= icu->bezt->vec[1][0];
- cycdx= (icu->bezt+icu->totvert-1)->vec[1][0] - ofs;
- cycdy= (icu->bezt+icu->totvert-1)->vec[1][1] - icu->bezt->vec[1][1];
- if(cycdx!=0.0) {
-
- if(icu->extrap & IPO_DIR) {
- cycyofs= (float)floor((ipotime-ofs)/cycdx);
- cycyofs*= cycdy;
+ /* extrapolation mode is 'cyclic' - find relative place within a cycle */
+ if (icu->extrap & IPO_CYCL) {
+ /* ofs is start frame of cycle */
+ ofs= prevbezt->vec[1][0];
+
+ /* calculate period and amplitude (total height) of a cycle */
+ cycdx= lastbezt->vec[1][0] - prevbezt->vec[1][0];
+ cycdy= lastbezt->vec[1][1] - prevbezt->vec[1][1];
+
+ /* cycle occurs over some period of time (cycdx should be positive all the time) */
+ if (cycdx) {
+ /* check if 'cyclic extrapolation', and thus calculate y-offset for this cycle
+ * - IPO_CYCLX = (IPO_CYCL + IPO_DIR)
+ */
+ if (icu->extrap & IPO_DIR) {
+ cycyofs = (float)floor((evaltime - ofs) / cycdx);
+ cycyofs *= cycdy;
}
-
- ipotime= (float)(fmod(ipotime-ofs, cycdx)+ofs);
- if(ipotime<ofs) ipotime+= cycdx;
+
+ /* calculate where in the cycle we are (overwrite evaltime to reflect this) */
+ evaltime= (float)(fmod(evaltime-ofs, cycdx) + ofs);
+ if (evaltime < ofs) evaltime += cycdx;
}
}
- /* endpoints? */
-
- if(prevbezt->vec[1][0]>=ipotime) {
- if( (icu->extrap & IPO_DIR) && icu->ipo!=IPO_CONST) {
- dx= prevbezt->vec[1][0]-ipotime;
- fac= prevbezt->vec[1][0]-prevbezt->vec[0][0];
- if(fac!=0.0) {
- fac= (prevbezt->vec[1][1]-prevbezt->vec[0][1])/fac;
- cvalue= prevbezt->vec[1][1]-fac*dx;
+ /* evaluation time at or past endpoints? */
+ // TODO: for per-bezt interpolation, replace all icu->ipo with (bezt)->ipo
+ if (prevbezt->vec[1][0] >= evaltime) {
+ /* before or on first keyframe */
+ if ((icu->extrap & IPO_DIR) && (icu->ipo != IPO_CONST)) {
+ /* linear or bezier interpolation */
+ if (icu->ipo==IPO_LIN) {
+ /* Use the next center point instead of our own handle for
+ * linear interpolated extrapolate
+ */
+ if (icu->totvert == 1)
+ cvalue= prevbezt->vec[1][1];
+ else {
+ bezt = prevbezt+1;
+ dx= prevbezt->vec[1][0] - evaltime;
+ fac= bezt->vec[1][0] - prevbezt->vec[1][0];
+
+ /* prevent division by zero */
+ if (fac) {
+ fac= (bezt->vec[1][1] - prevbezt->vec[1][1]) / fac;
+ cvalue= prevbezt->vec[1][1] - (fac * dx);
+ }
+ else
+ cvalue= prevbezt->vec[1][1];
+ }
+ }
+ else {
+ /* Use the first handle (earlier) of first BezTriple to calculate the
+ * gradient and thus the value of the curve at evaltime
+ */
+ dx= prevbezt->vec[1][0] - evaltime;
+ fac= prevbezt->vec[1][0] - prevbezt->vec[0][0];
+
+ /* prevent division by zero */
+ if (fac) {
+ fac= (prevbezt->vec[1][1] - prevbezt->vec[0][1]) / fac;
+ cvalue= prevbezt->vec[1][1] - (fac * dx);
+ }
+ else
+ cvalue= prevbezt->vec[1][1];
}
- else cvalue= prevbezt->vec[1][1];
}
- else cvalue= prevbezt->vec[1][1];
-
- cvalue+= cycyofs;
+ else {
+ /* constant (IPO_HORIZ) extrapolation or constant interpolation,
+ * so just extend first keyframe's value
+ */
+ cvalue= prevbezt->vec[1][1];
+ }
}
- else if( (prevbezt+a)->vec[1][0]<=ipotime) {
- if( (icu->extrap & IPO_DIR) && icu->ipo!=IPO_CONST) {
- prevbezt+= a;
- dx= ipotime-prevbezt->vec[1][0];
- fac= prevbezt->vec[2][0]-prevbezt->vec[1][0];
-
- if(fac!=0) {
- fac= (prevbezt->vec[2][1]-prevbezt->vec[1][1])/fac;
- cvalue= prevbezt->vec[1][1]+fac*dx;
+ else if (lastbezt->vec[1][0] <= evaltime) {
+ /* after or on last keyframe */
+ if( (icu->extrap & IPO_DIR) && (icu->ipo != IPO_CONST)) {
+ /* linear or bezier interpolation */
+ if (icu->ipo==IPO_LIN) {
+ /* Use the next center point instead of our own handle for
+ * linear interpolated extrapolate
+ */
+ if (icu->totvert == 1)
+ cvalue= lastbezt->vec[1][1];
+ else {
+ prevbezt = lastbezt - 1;
+ dx= evaltime - lastbezt->vec[1][0];
+ fac= lastbezt->vec[1][0] - prevbezt->vec[1][0];
+
+ /* prevent division by zero */
+ if (fac) {
+ fac= (lastbezt->vec[1][1] - prevbezt->vec[1][1]) / fac;
+ cvalue= lastbezt->vec[1][1] + (fac * dx);
+ }
+ else
+ cvalue= lastbezt->vec[1][1];
+ }
+ }
+ else {
+ /* Use the gradient of the second handle (later) of last BezTriple to calculate the
+ * gradient and thus the value of the curve at evaltime
+ */
+ dx= evaltime - lastbezt->vec[1][0];
+ fac= lastbezt->vec[2][0] - lastbezt->vec[1][0];
+
+ /* prevent division by zero */
+ if (fac) {
+ fac= (lastbezt->vec[2][1] - lastbezt->vec[1][1]) / fac;
+ cvalue= lastbezt->vec[1][1] + (fac * dx);
+ }
+ else
+ cvalue= lastbezt->vec[1][1];
}
- else cvalue= prevbezt->vec[1][1];
}
- else cvalue= (prevbezt+a)->vec[1][1];
-
- cvalue+= cycyofs;
+ else {
+ /* constant (IPO_HORIZ) extrapolation or constant interpolation,
+ * so just extend last keyframe's value
+ */
+ cvalue= lastbezt->vec[1][1];
+ }
}
else {
- while(a--) {
- if(prevbezt->vec[1][0]<=ipotime && bezt->vec[1][0]>=ipotime) {
- if(icu->ipo==IPO_CONST) {
- cvalue= prevbezt->vec[1][1]+cycyofs;
+ /* evaltime occurs somewhere in the middle of the curve */
+ // TODO: chould be optimised by using a binary search instead???
+ for (a=0; prevbezt && bezt && (a < icu->totvert-1); a++, prevbezt=bezt, bezt++) {
+ /* evaltime occurs within the interval defined by these two keyframes */
+ if ((prevbezt->vec[1][0] <= evaltime) && (bezt->vec[1][0] >= evaltime)) {
+ /* value depends on interpolation mode */
+ if (icu->ipo == IPO_CONST) {
+ /* constant (evaltime not relevant, so no interpolation needed) */
+ cvalue= prevbezt->vec[1][1];
}
- else if(icu->ipo==IPO_LIN) {
- fac= bezt->vec[1][0]-prevbezt->vec[1][0];
- if(fac==0) cvalue= cycyofs+prevbezt->vec[1][1];
- else {
- fac= (ipotime-prevbezt->vec[1][0])/fac;
- cvalue= cycyofs+prevbezt->vec[1][1]+ fac*(bezt->vec[1][1]-prevbezt->vec[1][1]);
+ else if (icu->ipo == IPO_LIN) {
+ /* linear - interpolate between values of the two keyframes */
+ fac= bezt->vec[1][0] - prevbezt->vec[1][0];
+
+ /* prevent division by zero */
+ if (fac) {
+ fac= (evaltime - prevbezt->vec[1][0]) / fac;
+ cvalue= prevbezt->vec[1][1] + (fac * (bezt->vec[1][1] - prevbezt->vec[1][1]));
}
+ else
+ cvalue= prevbezt->vec[1][1];
}
else {
+ /* bezier interpolation */
+ /* v1,v2 are the first keyframe and its 2nd handle */
v1[0]= prevbezt->vec[1][0];
v1[1]= prevbezt->vec[1][1];
v2[0]= prevbezt->vec[2][0];
v2[1]= prevbezt->vec[2][1];
-
+ /* v3,v4 are the last keyframe's 1st handle + the last keyframe */
v3[0]= bezt->vec[0][0];
v3[1]= bezt->vec[0][1];
v4[0]= bezt->vec[1][0];
v4[1]= bezt->vec[1][1];
-
+
+ /* adjust handles so that they don't overlap (forming a loop) */
correct_bezpart(v1, v2, v3, v4);
- b= findzero(ipotime, v1[0], v2[0], v3[0], v4[0], opl);
- if(b) {
+ /* try to get a value for this position - if failure, try another set of points */
+ b= findzero(evaltime, v1[0], v2[0], v3[0], v4[0], opl);
+ if (b) {
berekeny(v1[1], v2[1], v3[1], v4[1], opl, 1);
- cvalue= opl[0]+cycyofs;
+ cvalue= opl[0];
break;
}
}
}
- prevbezt= bezt;
- bezt++;
}
}
+
+ /* apply y-offset (for 'cyclic extrapolation') to calculated value */
+ cvalue+= cycyofs;
}
-
- if(icu->ymin < icu->ymax) {
- if(cvalue < icu->ymin) cvalue= icu->ymin;
- else if(cvalue > icu->ymax) cvalue= icu->ymax;
+
+ /* clamp evaluated value to lie within allowable value range for this channel */
+ if (icu->ymin < icu->ymax) {
+ CLAMP(cvalue, icu->ymin, icu->ymax);
}
+ /* return evaluated value */
return cvalue;
}
-void calc_icu(IpoCurve *icu, float ctime)
+/* ------------------- IPO-Block/Curve Calculation - General API ----------------------- */
+
+/* calculate the value of the given IPO-curve at the current frame, and set its curval */
+void calc_icu (IpoCurve *icu, float ctime)
{
+ /* calculate and set curval (evaluates driver too) */
icu->curval= eval_icu(icu, ctime);
}
-float calc_ipo_time(Ipo *ipo, float ctime)
+/* calculate for the current frame, all IPO-curves in IPO-block that can be evaluated
+ * - icu->curval is set for all IPO-curves which are evaluated!
+ */
+void calc_ipo (Ipo *ipo, float ctime)
{
+ IpoCurve *icu;
+
+ /* if there is no IPO block to evaluate, or whole block is "muted" */
+ if (ipo == NULL) return;
+ if (ipo->muteipo) return;
+
+ /* loop over all curves */
+ for (icu= ipo->curve.first; icu; icu= icu->next) {
+ /* only evaluated curve if allowed to:
+ * - Muted channels should not be evaluated as they shouldn't have any effect
+ * --> user explictly turned them off!
+ * - Drivers should be evaluated at all updates
+ * --> TODO Note: drivers should be separated from standard channels
+ * - IPO_LOCK is not set, as it is set by some internal mechanisms to prevent
+ * IPO-curve from overwriting data (currently only used for IPO-Record).
+ */
+ if ((icu->driver) || (icu->flag & IPO_LOCK)==0) {
+ if ((icu->flag & IPO_MUTE)==0)
+ calc_icu(icu, ctime);
+ }
+ }
+}
- if(ipo && ipo->blocktype==ID_OB) {
- IpoCurve *icu= ipo->curve.first;
+/* ------------------- IPO-Block/Curve Calculation - Special Hacks ----------------------- */
- while(icu) {
- if (icu->adrcode==OB_TIME) {
- calc_icu(icu, ctime);
- return 10.0f*icu->curval;
- }
- icu= icu->next;
- }
+/* Calculate and return the value of the 'Time' Ipo-Curve from an Object,
+ * OR return the current time if not found
+ * - used in object.c -> bsystem_time()
+ */
+float calc_ipo_time (Ipo *ipo, float ctime)
+{
+ /* only Time IPO from Object IPO-blocks are relevant */
+ if ((ipo) && (ipo->blocktype == ID_OB)) {
+ IpoCurve *icu= find_ipocurve(ipo, OB_TIME);
+
+ /* only calculate (and set icu->curval) for time curve */
+ if (icu) {
+ calc_icu(icu, ctime);
+ return (10.0f * icu->curval);
+ }
}
+ /* no appropriate time-curve found */
return ctime;
}
-void calc_ipo(Ipo *ipo, float ctime)
+/* Evaluate the specified channel in the given IPO block on the specified frame (ctime),
+ * writing the value into that channel's icu->curval, but ALSO dumping it in ctime.
+ * - Returns success and modifies ctime!
+ */
+short calc_ipo_spec (Ipo *ipo, int adrcode, float *ctime)
+{
+ IpoCurve *icu= find_ipocurve(ipo, adrcode);
+
+ /* only evaluate if found */
+ if (icu) {
+ /* only calculate if allowed to (not locked and not muted)
+ * - drivers not taken into account, because this may be called when calculating a driver
+ */
+ if ((icu->flag & (IPO_LOCK|IPO_MUTE))==0)
+ calc_icu(icu, *ctime);
+
+ /* value resulting from calculations is written into ctime! */
+ *ctime= icu->curval;
+ return 1;
+ }
+
+ /* couldn't evaluate */
+ return 0;
+}
+
+/* ***************************** IPO - DataAPI ********************************* */
+
+/* --------------------- Flush/Execute IPO Values ----------------------------- */
+
+/* Flush IpoCurve->curvals to the data they affect (defined by ID)
+ * - not for Actions or Constraints! (those have their own special handling)
+ */
+void execute_ipo (ID *id, Ipo *ipo)
{
IpoCurve *icu;
+ void *poin;
+ int type;
- if(ipo==NULL) return;
- if(ipo->muteipo) return;
+ /* don't do anything without an IPO block */
+ if (ipo == NULL)
+ return;
- for(icu= ipo->curve.first; icu; icu= icu->next) {
- if(icu->driver || (icu->flag & IPO_LOCK)==0) {
- if((icu->flag & IPO_MUTE)==0)
- calc_icu(icu, ctime);
+ /* loop over IPO Curves, getting pointer to var to affect, and write into that pointer */
+ for (icu= ipo->curve.first; icu; icu= icu->next) {
+ poin= get_ipo_poin(id, icu, &type);
+ if (poin) write_ipo_poin(poin, type, icu->curval);
+ }
+}
+
+/* Flush Action-Channel IPO data to Pose Channel */
+void execute_action_ipo (bActionChannel *achan, bPoseChannel *pchan)
+{
+ /* only do this if there's an Action Channel and Pose Channel to use */
+ if (achan && achan->ipo && pchan) {
+ IpoCurve *icu;
+
+ /* loop over IPO-curves, getting a pointer to pchan var to write to
+ * - assume for now that only 'float' channels will ever get written into
+ */
+ for (icu= achan->ipo->curve.first; icu; icu= icu->next) {
+ void *poin= get_pchan_ipo_poin(pchan, icu->adrcode);
+ if (poin) write_ipo_poin(poin, IPO_FLOAT, icu->curval);
}
}
}
-/* ************************************** */
-/* DO THE IPO! */
-/* ************************************** */
-void write_ipo_poin(void *poin, int type, float val)
+/* --------------------- Force Calculation + Flush IPO Values ----------------------------- */
+
+/* Calculate values for given IPO block, then flush to all of block's users
+ * - for general usage
+ */
+void do_ipo (Ipo *ipo)
+{
+ if (ipo) {
+ float ctime= frame_to_float(G.scene->r.cfra);
+
+ /* calculate values, then flush to all users of this IPO block */
+ calc_ipo(ipo, ctime);
+ do_ipo_nocalc(ipo);
+ }
+}
+
+/* Calculate values for given Material's IPO block, then flush to given Material only */
+void do_mat_ipo (Material *ma)
{
+ float ctime;
+
+ if (ELEM(NULL, ma, ma->ipo))
+ return;
+
+ ctime= frame_to_float(G.scene->r.cfra);
+ /* if(ob->ipoflag & OB_OFFS_OB) ctime-= ob->sf; */
+
+ /* calculate values for current time, then flush values to given material only */
+ calc_ipo(ma->ipo, ctime);
+ execute_ipo((ID *)ma, ma->ipo);
+}
- switch(type) {
- case IPO_FLOAT:
- *( (float *)poin)= val;
- break;
- case IPO_FLOAT_DEGR:
- *( (float *)poin)= (float)(val*M_PI_2/9.0);
- break;
- case IPO_INT:
- case IPO_INT_BIT:
- case IPO_LONG:
- *( (int *)poin)= (int)val;
- break;
- case IPO_SHORT:
- case IPO_SHORT_BIT:
- *( (short *)poin)= (short)val;
- break;
- case IPO_CHAR:
- case IPO_CHAR_BIT:
- *( (char *)poin)= (char)val;
- break;
+/* Calculate values for given Object's IPO block, then flush to given Object only
+ * - there's also some funky stuff that looks like it's for scene layers
+ */
+void do_ob_ipo (Object *ob)
+{
+ float ctime;
+ unsigned int lay;
+
+ if (ob->ipo == NULL)
+ return;
+
+ /* do not set ob->ctime here: for example when parent in invisible layer */
+ ctime= bsystem_time(ob, (float) G.scene->r.cfra, 0.0);
+
+ /* calculate values of */
+ calc_ipo(ob->ipo, ctime);
+
+ /* Patch: remember localview */
+ lay= ob->lay & 0xFF000000;
+
+ /* flush IPO values to this object only */
+ execute_ipo((ID *)ob, ob->ipo);
+
+ /* hack: for layer animation??? - is this what this is? (Aligorith, 28Sep2008) */
+ ob->lay |= lay;
+ if ((ob->id.name[2]=='S') && (ob->id.name[3]=='C') && (ob->id.name[4]=='E')) {
+ if (strcmp(G.scene->id.name+2, ob->id.name+6)==0) {
+ G.scene->lay= ob->lay;
+ //XXX copy_view3d_lock(0);
+ /* no redraw here! creates too many calls */
+ }
}
}
-float read_ipo_poin(void *poin, int type)
+/* Only execute those IPO-Curves with drivers, on the current frame, for the given Object
+ * - TODO: Drivers should really be made separate from standard anim channels
+ */
+void do_ob_ipodrivers (Object *ob, Ipo *ipo, float ctime)
{
- float val = 0.0;
+ IpoCurve *icu;
+ void *poin;
+ int type;
- switch(type) {
- case IPO_FLOAT:
- val= *( (float *)poin);
+ for (icu= ipo->curve.first; icu; icu= icu->next) {
+ if (icu->driver) {
+ icu->curval= eval_icu(icu, ctime);
+
+ poin= get_ipo_poin((ID *)ob, icu, &type);
+ if (poin) write_ipo_poin(poin, type, icu->curval);
+ }
+ }
+}
+
+/* Special variation to calculate IPO values for Sequence + perform other stuff */
+void do_seq_ipo (Sequence *seq, int cfra)
+{
+ float ctime, div;
+
+ /* seq_ipo has an exception: calc both fields immediately */
+ if (seq->ipo) {
+ if ((seq->flag & SEQ_IPO_FRAME_LOCKED) != 0) {
+ ctime = frame_to_float(cfra);
+ div = 1.0;
+ }
+ else {
+ ctime= frame_to_float(cfra - seq->startdisp);
+ div= (seq->enddisp - seq->startdisp) / 100.0f;
+ if (div == 0.0) return;
+ }
+
+ /* 2nd field */
+ calc_ipo(seq->ipo, (ctime+0.5f)/div);
+ execute_ipo((ID *)seq, seq->ipo);
+ seq->facf1= seq->facf0;
+
+ /* 1st field */
+ calc_ipo(seq->ipo, ctime/div);
+ execute_ipo((ID *)seq, seq->ipo);
+ }
+ else
+ seq->facf1= seq->facf0= 1.0f;
+}
+
+/* --------- */
+
+
+/* exception: it does calc for objects...
+ * now find out why this routine was used anyway!
+ */
+void do_ipo_nocalc (Ipo *ipo)
+{
+ Object *ob;
+ Material *ma;
+ Tex *tex;
+ World *wo;
+ Lamp *la;
+ Camera *ca;
+ bSound *snd;
+
+ if (ipo == NULL)
+ return;
+
+ /* only flush IPO values (without calculating first/again) on
+ * to the datablocks that use the given IPO block
+ */
+ switch (ipo->blocktype) {
+ case ID_OB:
+ for (ob= G.main->object.first; ob; ob= ob->id.next) {
+ if (ob->ipo == ipo) do_ob_ipo(ob);
+ }
break;
- case IPO_FLOAT_DEGR:
- val= *( (float *)poin);
- val = (float)(val/(M_PI_2/9.0));
+ case ID_MA:
+ for (ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if (ma->ipo == ipo) execute_ipo((ID *)ma, ipo);
+ }
break;
- case IPO_INT:
- case IPO_INT_BIT:
- case IPO_LONG:
- val= (float)(*( (int *)poin));
+ case ID_TE:
+ for (tex= G.main->tex.first; tex; tex= tex->id.next) {
+ if (tex->ipo == ipo) execute_ipo((ID *)tex, ipo);
+ }
break;
- case IPO_SHORT:
- case IPO_SHORT_BIT:
- val= *( (short *)poin);
+ case ID_WO:
+ for (wo= G.main->world.first; wo; wo= wo->id.next) {
+ if (wo->ipo == ipo) execute_ipo((ID *)wo, ipo);
+ }
break;
- case IPO_CHAR:
- case IPO_CHAR_BIT:
- val= *( (char *)poin);
+ case ID_LA:
+ for (la= G.main->lamp.first; la; la= la->id.next) {
+ if (la->ipo == ipo) execute_ipo((ID *)la, ipo);
+ }
+ break;
+ case ID_CA:
+ for (ca= G.main->camera.first; ca; ca= ca->id.next) {
+ if (ca->ipo == ipo) execute_ipo((ID *)ca, ipo);
+ }
+ break;
+ case ID_SO:
+ for (snd= G.main->sound.first; snd; snd= snd->id.next) {
+ if (snd->ipo == ipo) execute_ipo((ID *)snd, ipo);
+ }
break;
}
- return val;
}
-static void *give_tex_poin(Tex *tex, int adrcode, int *type )
+/* Executes IPO's for whole database on frame change, in a specified order,
+ * with datablocks being calculated in alphabetical order
+ * - called on scene_update_for_newframe() only
+ */
+void do_all_data_ipos ()
{
- void *poin=0;
+ Material *ma;
+ Tex *tex;
+ World *wo;
+ Ipo *ipo;
+ Lamp *la;
+ Key *key;
+ Camera *ca;
+ bSound *snd;
+ Sequence *seq;
+ Editing *ed;
+ Base *base;
+ float ctime;
+
+ ctime= frame_to_float(G.scene->r.cfra);
+
+ /* this exception cannot be depgraphed yet... what todo with objects in other layers?... */
+ for (base= G.scene->base.first; base; base= base->next) {
+ Object *ob= base->object;
+
+ /* only update layer when an ipo */
+ if (has_ipo_code(ob->ipo, OB_LAY)) {
+ do_ob_ipo(ob);
+ base->lay= ob->lay;
+ }
+ }
+
+ /* layers for the set...*/
+ if (G.scene->set) {
+ for (base= G.scene->set->base.first; base; base= base->next) {
+ Object *ob= base->object;
+
+ if (has_ipo_code(ob->ipo, OB_LAY)) {
+ do_ob_ipo(ob);
+ base->lay= ob->lay;
+ }
+ }
+ }
+
+ /* Calculate all IPO blocks in use, execept those for Objects */
+ for (ipo= G.main->ipo.first; ipo; ipo= ipo->id.next) {
+ if ((ipo->id.us) && (ipo->blocktype != ID_OB)) {
+ calc_ipo(ipo, ctime);
+ }
+ }
- switch(adrcode) {
+ /* Texture Blocks */
+ for (tex= G.main->tex.first; tex; tex= tex->id.next) {
+ if (tex->ipo) execute_ipo((ID *)tex, tex->ipo);
+ }
+
+ /* Material Blocks */
+ for (ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if (ma->ipo) execute_ipo((ID *)ma, ma->ipo);
+ }
+
+ /* World Blocks */
+ for (wo= G.main->world.first; wo; wo= wo->id.next) {
+ if (wo->ipo) execute_ipo((ID *)wo, wo->ipo);
+ }
+
+ /* ShapeKey Blocks */
+ for (key= G.main->key.first; key; key= key->id.next) {
+ if (key->ipo) execute_ipo((ID *)key, key->ipo);
+ }
+
+ /* Lamp Blocks */
+ for (la= G.main->lamp.first; la; la= la->id.next) {
+ if (la->ipo) execute_ipo((ID *)la, la->ipo);
+ }
+
+ /* Camera Blocks */
+ for (ca= G.main->camera.first; ca; ca= ca->id.next) {
+ if (ca->ipo) execute_ipo((ID *)ca, ca->ipo);
+ }
+
+ /* Sound Blocks (Old + Unused) */
+ for (snd= G.main->sound.first; snd; snd= snd->id.next) {
+ if (snd->ipo) execute_ipo((ID *)snd, snd->ipo);
+ }
+
+ /* Sequencer: process FAC Ipos used as volume envelopes */
+ ed= G.scene->ed;
+ if (ed) {
+ for (seq= ed->seqbasep->first; seq; seq= seq->next) {
+ if ( ((seq->type == SEQ_RAM_SOUND) || (seq->type == SEQ_HD_SOUND)) &&
+ (seq->startdisp <= G.scene->r.cfra+2) &&
+ (seq->enddisp>G.scene->r.cfra) &&
+ (seq->ipo) )
+ {
+ do_seq_ipo(seq, G.scene->r.cfra);
+ }
+ }
+ }
+}
+
+
+/* --------------------- Assorted ----------------------------- */
+
+/* clear delta-transforms on all Objects which use the given IPO block */
+void clear_delta_obipo(Ipo *ipo)
+{
+ Object *ob;
+
+ /* only search if there's an IPO */
+ if (ipo == NULL)
+ return;
+
+ /* search through all objects in database */
+ for (ob= G.main->object.first; ob; ob= ob->id.next) {
+ /* can only update if not a library */
+ if (ob->id.lib == NULL) {
+ if (ob->ipo == ipo) {
+ memset(&ob->dloc, 0, 12);
+ memset(&ob->drot, 0, 12);
+ memset(&ob->dsize, 0, 12);
+ }
+ }
+ }
+}
+
+/* ***************************** IPO - DataAPI ********************************* */
+
+// !!!!!!!!!!!!!!!!!!!!!!!!!!!! FIXME - BAD CRUFT WARNING !!!!!!!!!!!!!!!!!!!!!!!
+
+/* These functions here should be replaced eventually by the Data API, as this is
+ * inflexible duplication...
+ */
+
+/* --------------------- Get Pointer API ----------------------------- */
+
+/* get pointer to pose-channel's channel, but set appropriate flags first */
+void *get_pchan_ipo_poin (bPoseChannel *pchan, int adrcode)
+{
+ void *poin= NULL;
+
+ switch (adrcode) {
+ case AC_QUAT_W:
+ poin= &(pchan->quat[0]);
+ pchan->flag |= POSE_ROT;
+ break;
+ case AC_QUAT_X:
+ poin= &(pchan->quat[1]);
+ pchan->flag |= POSE_ROT;
+ break;
+ case AC_QUAT_Y:
+ poin= &(pchan->quat[2]);
+ pchan->flag |= POSE_ROT;
+ break;
+ case AC_QUAT_Z:
+ poin= &(pchan->quat[3]);
+ pchan->flag |= POSE_ROT;
+ break;
+
+ case AC_LOC_X:
+ poin= &(pchan->loc[0]);
+ pchan->flag |= POSE_LOC;
+ break;
+ case AC_LOC_Y:
+ poin= &(pchan->loc[1]);
+ pchan->flag |= POSE_LOC;
+ break;
+ case AC_LOC_Z:
+ poin= &(pchan->loc[2]);
+ pchan->flag |= POSE_LOC;
+ break;
+
+ case AC_SIZE_X:
+ poin= &(pchan->size[0]);
+ pchan->flag |= POSE_SIZE;
+ break;
+ case AC_SIZE_Y:
+ poin= &(pchan->size[1]);
+ pchan->flag |= POSE_SIZE;
+ break;
+ case AC_SIZE_Z:
+ poin= &(pchan->size[2]);
+ pchan->flag |= POSE_SIZE;
+ break;
+ }
+
+ /* return pointer */
+ return poin;
+}
+
+/* get texture channel */
+static void *give_tex_poin (Tex *tex, int adrcode, int *type )
+{
+ void *poin= NULL;
+
+ switch (adrcode) {
case TE_NSIZE:
poin= &(tex->noisesize); break;
case TE_TURB:
@@ -1168,17 +1902,18 @@ static void *give_tex_poin(Tex *tex, int adrcode, int *type )
poin= &(tex->bright); break;
case TE_CONTRA:
poin= &(tex->contrast); break;
-
}
+ /* return pointer */
return poin;
}
-void *give_mtex_poin(MTex *mtex, int adrcode )
+/* get texture-slot/mapping channel */
+void *give_mtex_poin (MTex *mtex, int adrcode)
{
- void *poin=0;
-
- switch(adrcode) {
+ void *poin= NULL;
+
+ switch (adrcode) {
case MAP_OFS_X:
poin= &(mtex->ofs[0]); break;
case MAP_OFS_Y:
@@ -1209,6 +1944,7 @@ void *give_mtex_poin(MTex *mtex, int adrcode )
poin= &(mtex->dispfac); break;
}
+ /* return pointer */
return poin;
}
@@ -1225,1280 +1961,923 @@ void *give_mtex_poin(MTex *mtex, int adrcode )
/* from misc_util: flip the bytes from x */
/* #define GS(x) (((unsigned char *)(x))[0] << 8 | ((unsigned char *)(x))[1]) */
-void *get_ipo_poin(ID *id, IpoCurve *icu, int *type)
+
+/* general function to get pointer to source/destination data */
+void *get_ipo_poin (ID *id, IpoCurve *icu, int *type)
{
void *poin= NULL;
- Object *ob;
- Material *ma;
- MTex *mtex;
- Tex *tex;
- Lamp *la;
- Sequence *seq;
- World *wo;
- ParticleSettings *part;
+ MTex *mtex= NULL;
+ /* most channels will have float data, but those with other types will override this */
*type= IPO_FLOAT;
- if( GS(id->name)==ID_OB) {
-
- ob= (Object *)id;
-
- switch(icu->adrcode) {
- case OB_LOC_X:
- poin= &(ob->loc[0]); break;
- case OB_LOC_Y:
- poin= &(ob->loc[1]); break;
- case OB_LOC_Z:
- poin= &(ob->loc[2]); break;
- case OB_DLOC_X:
- poin= &(ob->dloc[0]); break;
- case OB_DLOC_Y:
- poin= &(ob->dloc[1]); break;
- case OB_DLOC_Z:
- poin= &(ob->dloc[2]); break;
-
- case OB_ROT_X:
- poin= &(ob->rot[0]); *type= IPO_FLOAT_DEGR; break;
- case OB_ROT_Y:
- poin= &(ob->rot[1]); *type= IPO_FLOAT_DEGR; break;
- case OB_ROT_Z:
- poin= &(ob->rot[2]); *type= IPO_FLOAT_DEGR; break;
- case OB_DROT_X:
- poin= &(ob->drot[0]); *type= IPO_FLOAT_DEGR; break;
- case OB_DROT_Y:
- poin= &(ob->drot[1]); *type= IPO_FLOAT_DEGR; break;
- case OB_DROT_Z:
- poin= &(ob->drot[2]); *type= IPO_FLOAT_DEGR; break;
+ /* data is divided into 'blocktypes' based on ID-codes */
+ switch (GS(id->name)) {
+ case ID_OB: /* object channels ----------------------------- */
+ {
+ Object *ob= (Object *)id;
- case OB_SIZE_X:
- poin= &(ob->size[0]); break;
- case OB_SIZE_Y:
- poin= &(ob->size[1]); break;
- case OB_SIZE_Z:
- poin= &(ob->size[2]); break;
- case OB_DSIZE_X:
- poin= &(ob->dsize[0]); break;
- case OB_DSIZE_Y:
- poin= &(ob->dsize[1]); break;
- case OB_DSIZE_Z:
- poin= &(ob->dsize[2]); break;
-
- case OB_LAY:
- poin= &(ob->lay); *type= IPO_INT_BIT; break;
+ switch (icu->adrcode) {
+ case OB_LOC_X:
+ poin= &(ob->loc[0]); break;
+ case OB_LOC_Y:
+ poin= &(ob->loc[1]); break;
+ case OB_LOC_Z:
+ poin= &(ob->loc[2]); break;
+ case OB_DLOC_X:
+ poin= &(ob->dloc[0]); break;
+ case OB_DLOC_Y:
+ poin= &(ob->dloc[1]); break;
+ case OB_DLOC_Z:
+ poin= &(ob->dloc[2]); break;
- case OB_COL_R:
- poin= &(ob->col[0]);
- break;
- case OB_COL_G:
- poin= &(ob->col[1]);
- break;
- case OB_COL_B:
- poin= &(ob->col[2]);
- break;
- case OB_COL_A:
- poin= &(ob->col[3]);
- break;
- case OB_PD_FSTR:
- if(ob->pd) poin= &(ob->pd->f_strength);
- break;
- case OB_PD_FFALL:
- if(ob->pd) poin= &(ob->pd->f_power);
- break;
- case OB_PD_SDAMP:
- if(ob->pd) poin= &(ob->pd->pdef_damp);
- break;
- case OB_PD_RDAMP:
- if(ob->pd) poin= &(ob->pd->pdef_rdamp);
- break;
- case OB_PD_PERM:
- if(ob->pd) poin= &(ob->pd->pdef_perm);
- break;
- case OB_PD_FMAXD:
- if(ob->pd) poin= &(ob->pd->maxdist);
- break;
- }
- }
- else if( GS(id->name)==ID_MA) {
-
- ma= (Material *)id;
-
- switch(icu->adrcode) {
- case MA_COL_R:
- poin= &(ma->r); break;
- case MA_COL_G:
- poin= &(ma->g); break;
- case MA_COL_B:
- poin= &(ma->b); break;
- case MA_SPEC_R:
- poin= &(ma->specr); break;
- case MA_SPEC_G:
- poin= &(ma->specg); break;
- case MA_SPEC_B:
- poin= &(ma->specb); break;
- case MA_MIR_R:
- poin= &(ma->mirr); break;
- case MA_MIR_G:
- poin= &(ma->mirg); break;
- case MA_MIR_B:
- poin= &(ma->mirb); break;
- case MA_REF:
- poin= &(ma->ref); break;
- case MA_ALPHA:
- poin= &(ma->alpha); break;
- case MA_EMIT:
- poin= &(ma->emit); break;
- case MA_AMB:
- poin= &(ma->amb); break;
- case MA_SPEC:
- poin= &(ma->spec); break;
- case MA_HARD:
- poin= &(ma->har); *type= IPO_SHORT; break;
- case MA_SPTR:
- poin= &(ma->spectra); break;
- case MA_IOR:
- poin= &(ma->ang); break;
- case MA_MODE:
- poin= &(ma->mode); *type= IPO_INT_BIT; break;
- case MA_HASIZE:
- poin= &(ma->hasize); break;
- case MA_TRANSLU:
- poin= &(ma->translucency); break;
- case MA_RAYM:
- poin= &(ma->ray_mirror); break;
- case MA_FRESMIR:
- poin= &(ma->fresnel_mir); break;
- case MA_FRESMIRI:
- poin= &(ma->fresnel_mir_i); break;
- case MA_FRESTRA:
- poin= &(ma->fresnel_tra); break;
- case MA_FRESTRAI:
- poin= &(ma->fresnel_tra_i); break;
- case MA_ADD:
- poin= &(ma->add); break;
- }
-
- if(poin==NULL) {
- mtex= 0;
- if(icu->adrcode & MA_MAP1) mtex= ma->mtex[0];
- else if(icu->adrcode & MA_MAP2) mtex= ma->mtex[1];
- else if(icu->adrcode & MA_MAP3) mtex= ma->mtex[2];
- else if(icu->adrcode & MA_MAP4) mtex= ma->mtex[3];
- else if(icu->adrcode & MA_MAP5) mtex= ma->mtex[4];
- else if(icu->adrcode & MA_MAP6) mtex= ma->mtex[5];
- else if(icu->adrcode & MA_MAP7) mtex= ma->mtex[6];
- else if(icu->adrcode & MA_MAP8) mtex= ma->mtex[7];
- else if(icu->adrcode & MA_MAP9) mtex= ma->mtex[8];
- else if(icu->adrcode & MA_MAP10) mtex= ma->mtex[9];
+ case OB_ROT_X:
+ poin= &(ob->rot[0]); *type= IPO_FLOAT_DEGR; break;
+ case OB_ROT_Y:
+ poin= &(ob->rot[1]); *type= IPO_FLOAT_DEGR; break;
+ case OB_ROT_Z:
+ poin= &(ob->rot[2]); *type= IPO_FLOAT_DEGR; break;
+ case OB_DROT_X:
+ poin= &(ob->drot[0]); *type= IPO_FLOAT_DEGR; break;
+ case OB_DROT_Y:
+ poin= &(ob->drot[1]); *type= IPO_FLOAT_DEGR; break;
+ case OB_DROT_Z:
+ poin= &(ob->drot[2]); *type= IPO_FLOAT_DEGR; break;
+
+ case OB_SIZE_X:
+ poin= &(ob->size[0]); break;
+ case OB_SIZE_Y:
+ poin= &(ob->size[1]); break;
+ case OB_SIZE_Z:
+ poin= &(ob->size[2]); break;
+ case OB_DSIZE_X:
+ poin= &(ob->dsize[0]); break;
+ case OB_DSIZE_Y:
+ poin= &(ob->dsize[1]); break;
+ case OB_DSIZE_Z:
+ poin= &(ob->dsize[2]); break;
- if(mtex) {
- poin= give_mtex_poin(mtex, icu->adrcode & (MA_MAP1-1) );
- }
- }
- }
- else if( GS(id->name)==ID_TE) {
- tex= (Tex *)id;
-
- if(tex) poin= give_tex_poin(tex, icu->adrcode, type);
- }
- else if( GS(id->name)==ID_SEQ) {
- seq= (Sequence *)id;
-
- switch(icu->adrcode) {
- case SEQ_FAC1:
- poin= &(seq->facf0); break;
- }
- }
- else if( GS(id->name)==ID_CU) {
-
- poin= &(icu->curval);
-
- }
- else if( GS(id->name)==ID_KE) {
- KeyBlock *kb= ((Key *)id)->block.first;
-
- for(; kb; kb= kb->next)
- if(kb->adrcode==icu->adrcode)
+ case OB_LAY:
+ poin= &(ob->lay); *type= IPO_INT_BIT; break;
+
+ case OB_COL_R:
+ poin= &(ob->col[0]); break;
+ case OB_COL_G:
+ poin= &(ob->col[1]); break;
+ case OB_COL_B:
+ poin= &(ob->col[2]); break;
+ case OB_COL_A:
+ poin= &(ob->col[3]); break;
+
+ case OB_PD_FSTR:
+ if (ob->pd) poin= &(ob->pd->f_strength);
+ break;
+ case OB_PD_FFALL:
+ if (ob->pd) poin= &(ob->pd->f_power);
+ break;
+ case OB_PD_SDAMP:
+ if (ob->pd) poin= &(ob->pd->pdef_damp);
+ break;
+ case OB_PD_RDAMP:
+ if (ob->pd) poin= &(ob->pd->pdef_rdamp);
+ break;
+ case OB_PD_PERM:
+ if (ob->pd) poin= &(ob->pd->pdef_perm);
+ break;
+ case OB_PD_FMAXD:
+ if (ob->pd) poin= &(ob->pd->maxdist);
break;
- if(kb)
- poin= &(kb->curval);
-
- }
- else if(GS(id->name)==ID_WO) {
-
- wo= (World *)id;
-
- switch(icu->adrcode) {
- case WO_HOR_R:
- poin= &(wo->horr); break;
- case WO_HOR_G:
- poin= &(wo->horg); break;
- case WO_HOR_B:
- poin= &(wo->horb); break;
- case WO_ZEN_R:
- poin= &(wo->zenr); break;
- case WO_ZEN_G:
- poin= &(wo->zeng); break;
- case WO_ZEN_B:
- poin= &(wo->zenb); break;
-
- case WO_EXPOS:
- poin= &(wo->exposure); break;
-
- case WO_MISI:
- poin= &(wo->misi); break;
- case WO_MISTDI:
- poin= &(wo->mistdist); break;
- case WO_MISTSTA:
- poin= &(wo->miststa); break;
- case WO_MISTHI:
- poin= &(wo->misthi); break;
-
- case WO_STAR_R:
- poin= &(wo->starr); break;
- case WO_STAR_G:
- poin= &(wo->starg); break;
- case WO_STAR_B:
- poin= &(wo->starb); break;
-
- case WO_STARDIST:
- poin= &(wo->stardist); break;
- case WO_STARSIZE:
- poin= &(wo->starsize); break;
- }
-
- if(poin==NULL) {
- mtex= 0;
- if(icu->adrcode & MA_MAP1) mtex= wo->mtex[0];
- else if(icu->adrcode & MA_MAP2) mtex= wo->mtex[1];
- else if(icu->adrcode & MA_MAP3) mtex= wo->mtex[2];
- else if(icu->adrcode & MA_MAP4) mtex= wo->mtex[3];
- else if(icu->adrcode & MA_MAP5) mtex= wo->mtex[4];
- else if(icu->adrcode & MA_MAP6) mtex= wo->mtex[5];
- else if(icu->adrcode & MA_MAP7) mtex= wo->mtex[6];
- else if(icu->adrcode & MA_MAP8) mtex= wo->mtex[7];
- else if(icu->adrcode & MA_MAP9) mtex= wo->mtex[8];
- else if(icu->adrcode & MA_MAP10) mtex= wo->mtex[9];
-
- if(mtex) {
- poin= give_mtex_poin(mtex, icu->adrcode & (MA_MAP1-1) );
- }
- }
- }
- else if( GS(id->name)==ID_LA) {
-
- la= (Lamp *)id;
-
- switch(icu->adrcode) {
- case LA_ENERGY:
- poin= &(la->energy); break;
- case LA_COL_R:
- poin= &(la->r); break;
- case LA_COL_G:
- poin= &(la->g); break;
- case LA_COL_B:
- poin= &(la->b); break;
- case LA_DIST:
- poin= &(la->dist); break;
- case LA_SPOTSI:
- poin= &(la->spotsize); break;
- case LA_SPOTBL:
- poin= &(la->spotblend); break;
- case LA_QUAD1:
- poin= &(la->att1); break;
- case LA_QUAD2:
- poin= &(la->att2); break;
- case LA_HALOINT:
- poin= &(la->haint); break;
- }
-
- if(poin==NULL) {
- mtex= 0;
- if(icu->adrcode & MA_MAP1) mtex= la->mtex[0];
- else if(icu->adrcode & MA_MAP2) mtex= la->mtex[1];
- else if(icu->adrcode & MA_MAP3) mtex= la->mtex[2];
- else if(icu->adrcode & MA_MAP4) mtex= la->mtex[3];
- else if(icu->adrcode & MA_MAP5) mtex= la->mtex[4];
- else if(icu->adrcode & MA_MAP6) mtex= la->mtex[5];
- else if(icu->adrcode & MA_MAP7) mtex= la->mtex[6];
- else if(icu->adrcode & MA_MAP8) mtex= la->mtex[7];
- else if(icu->adrcode & MA_MAP9) mtex= la->mtex[8];
- else if(icu->adrcode & MA_MAP10) mtex= la->mtex[9];
-
- if(mtex) {
- poin= give_mtex_poin(mtex, icu->adrcode & (MA_MAP1-1) );
}
}
- }
- else if(GS(id->name)==ID_CA) {
- Camera *ca= (Camera *)id;
-
- /* yafray: aperture & focal distance params */
- switch(icu->adrcode) {
- case CAM_LENS:
- if(ca->type==CAM_ORTHO)
- poin= &(ca->ortho_scale);
- else
- poin= &(ca->lens);
break;
- case CAM_STA:
- poin= &(ca->clipsta); break;
- case CAM_END:
- poin= &(ca->clipend); break;
- case CAM_YF_APERT:
- poin= &(ca->YF_aperture); break;
- case CAM_YF_FDIST:
- poin= &(ca->YF_dofdist); break;
- case CAM_SHIFT_X:
- poin= &(ca->shiftx); break;
- case CAM_SHIFT_Y:
- poin= &(ca->shifty); break;
- }
- }
- else if(GS(id->name)==ID_SO) {
- bSound *snd= (bSound *)id;
-
- switch(icu->adrcode) {
- case SND_VOLUME:
- poin= &(snd->volume); break;
- case SND_PITCH:
- poin= &(snd->pitch); break;
- case SND_PANNING:
- poin= &(snd->panning); break;
- case SND_ATTEN:
- poin= &(snd->attenuation); break;
- }
- }
- else if( GS(id->name)==ID_PA) {
-
- part= (ParticleSettings *)id;
-
- switch(icu->adrcode) {
- case PART_EMIT_FREQ:
- case PART_EMIT_LIFE:
- case PART_EMIT_VEL:
- case PART_EMIT_AVE:
- case PART_EMIT_SIZE:
- poin= NULL; break;
- case PART_CLUMP:
- poin= &(part->clumpfac); break;
- case PART_AVE:
- poin= &(part->avefac); break;
- case PART_SIZE:
- poin= &(part->size); break;
- case PART_DRAG:
- poin= &(part->dragfac); break;
- case PART_BROWN:
- poin= &(part->brownfac); break;
- case PART_DAMP:
- poin= &(part->dampfac); break;
- case PART_LENGTH:
- poin= &(part->length); break;
- case PART_GRAV_X:
- poin= &(part->acc[0]); break;
- case PART_GRAV_Y:
- poin= &(part->acc[1]); break;
- case PART_GRAV_Z:
- poin= &(part->acc[2]); break;
- case PART_KINK_AMP:
- poin= &(part->kink_amp); break;
- case PART_KINK_FREQ:
- poin= &(part->kink_freq); break;
- case PART_KINK_SHAPE:
- poin= &(part->kink_shape); break;
- case PART_BB_TILT:
- poin= &(part->bb_tilt); break;
- }
- }
-
- return poin;
-}
-
-void set_icu_vars(IpoCurve *icu)
-{
- /* defaults. 0.0 for y-extents makes these ignored */
- icu->ymin= icu->ymax= 0.0;
- icu->ipo= IPO_BEZ;
-
- if(icu->blocktype==ID_OB) {
-
- if(icu->adrcode==OB_LAY) {
- icu->ipo= IPO_CONST;
- icu->vartype= IPO_BITS;
- }
-
- }
- else if(icu->blocktype==ID_MA) {
-
- if(icu->adrcode < MA_MAP1) {
- switch(icu->adrcode) {
- case MA_HASIZE:
- icu->ymax= 10000.0; break;
- case MA_HARD:
- icu->ymax= 511.0; break;
+ case ID_MA: /* material channels ----------------------------- */
+ {
+ Material *ma= (Material *)id;
+
+ switch (icu->adrcode) {
+ case MA_COL_R:
+ poin= &(ma->r); break;
+ case MA_COL_G:
+ poin= &(ma->g); break;
+ case MA_COL_B:
+ poin= &(ma->b); break;
+ case MA_SPEC_R:
+ poin= &(ma->specr); break;
+ case MA_SPEC_G:
+ poin= &(ma->specg); break;
+ case MA_SPEC_B:
+ poin= &(ma->specb); break;
+ case MA_MIR_R:
+ poin= &(ma->mirr); break;
+ case MA_MIR_G:
+ poin= &(ma->mirg); break;
+ case MA_MIR_B:
+ poin= &(ma->mirb); break;
+ case MA_REF:
+ poin= &(ma->ref); break;
+ case MA_ALPHA:
+ poin= &(ma->alpha); break;
+ case MA_EMIT:
+ poin= &(ma->emit); break;
+ case MA_AMB:
+ poin= &(ma->amb); break;
case MA_SPEC:
- icu->ymax= 2.0; break;
+ poin= &(ma->spec); break;
+ case MA_HARD:
+ poin= &(ma->har); *type= IPO_SHORT; break;
+ case MA_SPTR:
+ poin= &(ma->spectra); break;
+ case MA_IOR:
+ poin= &(ma->ang); break;
case MA_MODE:
- icu->ipo= IPO_CONST;
- icu->vartype= IPO_BITS; break;
- case MA_RAYM:
- icu->ymax= 1.0; break;
+ poin= &(ma->mode); *type= IPO_INT_BIT; break; // evil... dumping bitflags directly to user!
+ case MA_HASIZE:
+ poin= &(ma->hasize); break;
case MA_TRANSLU:
- icu->ymax= 1.0; break;
- case MA_IOR:
- icu->ymin= 1.0;
- icu->ymax= 3.0; break;
+ poin= &(ma->translucency); break;
+ case MA_RAYM:
+ poin= &(ma->ray_mirror); break;
case MA_FRESMIR:
- icu->ymax= 5.0; break;
+ poin= &(ma->fresnel_mir); break;
case MA_FRESMIRI:
- icu->ymin= 1.0;
- icu->ymax= 5.0; break;
+ poin= &(ma->fresnel_mir_i); break;
case MA_FRESTRA:
- icu->ymax= 5.0; break;
+ poin= &(ma->fresnel_tra); break;
case MA_FRESTRAI:
- icu->ymin= 1.0;
- icu->ymax= 5.0; break;
+ poin= &(ma->fresnel_tra_i); break;
case MA_ADD:
- icu->ymax= 1.0; break;
- default:
- icu->ymax= 1.0; break;
+ poin= &(ma->add); break;
+ }
+
+ if (poin == NULL) {
+ if (icu->adrcode & MA_MAP1) mtex= ma->mtex[0];
+ else if (icu->adrcode & MA_MAP2) mtex= ma->mtex[1];
+ else if (icu->adrcode & MA_MAP3) mtex= ma->mtex[2];
+ else if (icu->adrcode & MA_MAP4) mtex= ma->mtex[3];
+ else if (icu->adrcode & MA_MAP5) mtex= ma->mtex[4];
+ else if (icu->adrcode & MA_MAP6) mtex= ma->mtex[5];
+ else if (icu->adrcode & MA_MAP7) mtex= ma->mtex[6];
+ else if (icu->adrcode & MA_MAP8) mtex= ma->mtex[7];
+ else if (icu->adrcode & MA_MAP9) mtex= ma->mtex[8];
+ else if (icu->adrcode & MA_MAP10) mtex= ma->mtex[9];
+ else if (icu->adrcode & MA_MAP12) mtex= ma->mtex[11];
+ else if (icu->adrcode & MA_MAP11) mtex= ma->mtex[10];
+ else if (icu->adrcode & MA_MAP13) mtex= ma->mtex[12];
+ else if (icu->adrcode & MA_MAP14) mtex= ma->mtex[13];
+ else if (icu->adrcode & MA_MAP15) mtex= ma->mtex[14];
+ else if (icu->adrcode & MA_MAP16) mtex= ma->mtex[15];
+ else if (icu->adrcode & MA_MAP17) mtex= ma->mtex[16];
+ else if (icu->adrcode & MA_MAP18) mtex= ma->mtex[17];
+
+ if (mtex)
+ poin= give_mtex_poin(mtex, (icu->adrcode & (MA_MAP1-1)));
}
}
- else {
- switch(icu->adrcode & (MA_MAP1-1)) {
- case MAP_OFS_X:
- case MAP_OFS_Y:
- case MAP_OFS_Z:
- case MAP_SIZE_X:
- case MAP_SIZE_Y:
- case MAP_SIZE_Z:
- icu->ymax= 1000.0;
- icu->ymin= -1000.0;
+ break;
+ case ID_TE: /* texture channels ----------------------------- */
+ {
+ Tex *tex= (Tex *)id;
- break;
- case MAP_R:
- case MAP_G:
- case MAP_B:
- case MAP_DVAR:
- case MAP_COLF:
- case MAP_VARF:
- case MAP_DISP:
- icu->ymax= 1.0;
- break;
- case MAP_NORF:
- icu->ymax= 25.0;
- break;
+ if (tex)
+ poin= give_tex_poin(tex, icu->adrcode, type);
+ }
+ break;
+ case ID_SEQ: /* sequence channels ----------------------------- */
+ {
+ Sequence *seq= (Sequence *)id;
+
+ switch (icu->adrcode) {
+ case SEQ_FAC1:
+ poin= &(seq->facf0); break;
}
}
- }
- else if(icu->blocktype==ID_TE) {
- switch(icu->adrcode & (MA_MAP1-1)) {
- case TE_NSIZE:
- icu->ymin= 0.0001;
- icu->ymax= 2.0; break;
- case TE_NDEPTH:
- icu->vartype= IPO_SHORT;
- icu->ipo= IPO_CONST;
- icu->ymax= 6.0; break;
- case TE_NTYPE:
- icu->vartype= IPO_SHORT;
- icu->ipo= IPO_CONST;
- icu->ymax= 1.0; break;
- case TE_TURB:
- icu->ymax= 200.0; break;
- case TE_VNW1:
- case TE_VNW2:
- case TE_VNW3:
- case TE_VNW4:
- icu->ymax= 2.0;
- icu->ymin= -2.0; break;
- case TE_VNMEXP:
- icu->ymax= 10.0;
- icu->ymin= 0.01; break;
- case TE_VN_DISTM:
- icu->vartype= IPO_SHORT;
- icu->ipo= IPO_CONST;
- icu->ymax= 6.0; break;
- case TE_VN_COLT:
- icu->vartype= IPO_SHORT;
- icu->ipo= IPO_CONST;
- icu->ymax= 3.0; break;
- case TE_ISCA:
- icu->ymax= 10.0;
- icu->ymin= 0.01; break;
- case TE_DISTA:
- icu->ymax= 10.0; break;
- case TE_MG_TYP:
- icu->vartype= IPO_SHORT;
- icu->ipo= IPO_CONST;
- icu->ymax= 6.0; break;
- case TE_MGH:
- icu->ymin= 0.0001;
- icu->ymax= 2.0; break;
- case TE_MG_LAC:
- case TE_MG_OFF:
- case TE_MG_GAIN:
- icu->ymax= 6.0; break;
- case TE_MG_OCT:
- icu->ymax= 8.0; break;
- case TE_N_BAS1:
- case TE_N_BAS2:
- icu->vartype= IPO_SHORT;
- icu->ipo= IPO_CONST;
- icu->ymax= 8.0; break;
- case TE_COL_R:
- icu->ymax= 0.0; break;
- case TE_COL_G:
- icu->ymax= 2.0; break;
- case TE_COL_B:
- icu->ymax= 2.0; break;
- case TE_BRIGHT:
- icu->ymax= 2.0; break;
- case TE_CONTRA:
- icu->ymax= 5.0; break;
-
+ break;
+ case ID_CU: /* curve channels ----------------------------- */
+ {
+ poin= &(icu->curval);
}
- }
- else if(icu->blocktype==ID_SEQ) {
-
- icu->ymax= 1.0;
-
- }
- else if(icu->blocktype==ID_CU) {
-
- icu->ymax= 1.0;
-
- }
- else if(icu->blocktype==ID_WO) {
-
- if(icu->adrcode < MA_MAP1) {
- switch(icu->adrcode) {
+ break;
+ case ID_KE: /* shapekey channels ----------------------------- */
+ {
+ Key *key= (Key *)id;
+ KeyBlock *kb;
+
+ for(kb= key->block.first; kb; kb= kb->next) {
+ if (kb->adrcode == icu->adrcode)
+ break;
+ }
+
+ if (kb)
+ poin= &(kb->curval);
+ }
+ break;
+ case ID_WO: /* world channels ----------------------------- */
+ {
+ World *wo= (World *)id;
+
+ switch (icu->adrcode) {
+ case WO_HOR_R:
+ poin= &(wo->horr); break;
+ case WO_HOR_G:
+ poin= &(wo->horg); break;
+ case WO_HOR_B:
+ poin= &(wo->horb); break;
+ case WO_ZEN_R:
+ poin= &(wo->zenr); break;
+ case WO_ZEN_G:
+ poin= &(wo->zeng); break;
+ case WO_ZEN_B:
+ poin= &(wo->zenb); break;
+
case WO_EXPOS:
- icu->ymax= 5.0; break;
+ poin= &(wo->exposure); break;
+
+ case WO_MISI:
+ poin= &(wo->misi); break;
case WO_MISTDI:
+ poin= &(wo->mistdist); break;
case WO_MISTSTA:
+ poin= &(wo->miststa); break;
case WO_MISTHI:
+ poin= &(wo->misthi); break;
+
+ case WO_STAR_R:
+ poin= &(wo->starr); break;
+ case WO_STAR_G:
+ poin= &(wo->starg); break;
+ case WO_STAR_B:
+ poin= &(wo->starb); break;
+
case WO_STARDIST:
+ poin= &(wo->stardist); break;
case WO_STARSIZE:
- break;
-
- default:
- icu->ymax= 1.0;
- break;
+ poin= &(wo->starsize); break;
}
- }
- else {
- switch(icu->adrcode & (MA_MAP1-1)) {
- case MAP_OFS_X:
- case MAP_OFS_Y:
- case MAP_OFS_Z:
- case MAP_SIZE_X:
- case MAP_SIZE_Y:
- case MAP_SIZE_Z:
- icu->ymax= 100.0;
- icu->ymin= -100.0;
- break;
- case MAP_R:
- case MAP_G:
- case MAP_B:
- case MAP_DVAR:
- case MAP_COLF:
- case MAP_NORF:
- case MAP_VARF:
- case MAP_DISP:
- icu->ymax= 1.0;
+ if (poin == NULL) {
+ if (icu->adrcode & MA_MAP1) mtex= wo->mtex[0];
+ else if (icu->adrcode & MA_MAP2) mtex= wo->mtex[1];
+ else if (icu->adrcode & MA_MAP3) mtex= wo->mtex[2];
+ else if (icu->adrcode & MA_MAP4) mtex= wo->mtex[3];
+ else if (icu->adrcode & MA_MAP5) mtex= wo->mtex[4];
+ else if (icu->adrcode & MA_MAP6) mtex= wo->mtex[5];
+ else if (icu->adrcode & MA_MAP7) mtex= wo->mtex[6];
+ else if (icu->adrcode & MA_MAP8) mtex= wo->mtex[7];
+ else if (icu->adrcode & MA_MAP9) mtex= wo->mtex[8];
+ else if (icu->adrcode & MA_MAP10) mtex= wo->mtex[9];
+ else if (icu->adrcode & MA_MAP11) mtex= wo->mtex[10];
+ else if (icu->adrcode & MA_MAP12) mtex= wo->mtex[11];
+ else if (icu->adrcode & MA_MAP13) mtex= wo->mtex[12];
+ else if (icu->adrcode & MA_MAP14) mtex= wo->mtex[13];
+ else if (icu->adrcode & MA_MAP15) mtex= wo->mtex[14];
+ else if (icu->adrcode & MA_MAP16) mtex= wo->mtex[15];
+ else if (icu->adrcode & MA_MAP17) mtex= wo->mtex[16];
+ else if (icu->adrcode & MA_MAP18) mtex= wo->mtex[17];
+
+ if (mtex)
+ poin= give_mtex_poin(mtex, (icu->adrcode & (MA_MAP1-1)));
}
}
- }
- else if(icu->blocktype==ID_LA) {
- if(icu->adrcode < MA_MAP1) {
- switch(icu->adrcode) {
+ break;
+ case ID_LA: /* lamp channels ----------------------------- */
+ {
+ Lamp *la= (Lamp *)id;
+
+ switch (icu->adrcode) {
case LA_ENERGY:
- case LA_DIST:
- break;
-
+ poin= &(la->energy); break;
case LA_COL_R:
+ poin= &(la->r); break;
case LA_COL_G:
+ poin= &(la->g); break;
case LA_COL_B:
+ poin= &(la->b); break;
+ case LA_DIST:
+ poin= &(la->dist); break;
+ case LA_SPOTSI:
+ poin= &(la->spotsize); break;
case LA_SPOTBL:
+ poin= &(la->spotblend); break;
case LA_QUAD1:
+ poin= &(la->att1); break;
case LA_QUAD2:
- icu->ymax= 1.0; break;
- case LA_SPOTSI:
- icu->ymax= 180.0; break;
+ poin= &(la->att2); break;
case LA_HALOINT:
- icu->ymax= 5.0; break;
+ poin= &(la->haint); break;
+ }
+
+ if (poin == NULL) {
+ if (icu->adrcode & MA_MAP1) mtex= la->mtex[0];
+ else if (icu->adrcode & MA_MAP2) mtex= la->mtex[1];
+ else if (icu->adrcode & MA_MAP3) mtex= la->mtex[2];
+ else if (icu->adrcode & MA_MAP4) mtex= la->mtex[3];
+ else if (icu->adrcode & MA_MAP5) mtex= la->mtex[4];
+ else if (icu->adrcode & MA_MAP6) mtex= la->mtex[5];
+ else if (icu->adrcode & MA_MAP7) mtex= la->mtex[6];
+ else if (icu->adrcode & MA_MAP8) mtex= la->mtex[7];
+ else if (icu->adrcode & MA_MAP9) mtex= la->mtex[8];
+ else if (icu->adrcode & MA_MAP10) mtex= la->mtex[9];
+ else if (icu->adrcode & MA_MAP11) mtex= la->mtex[10];
+ else if (icu->adrcode & MA_MAP12) mtex= la->mtex[11];
+ else if (icu->adrcode & MA_MAP13) mtex= la->mtex[12];
+ else if (icu->adrcode & MA_MAP14) mtex= la->mtex[13];
+ else if (icu->adrcode & MA_MAP15) mtex= la->mtex[14];
+ else if (icu->adrcode & MA_MAP16) mtex= la->mtex[15];
+ else if (icu->adrcode & MA_MAP17) mtex= la->mtex[16];
+ else if (icu->adrcode & MA_MAP18) mtex= la->mtex[17];
+
+ if (mtex)
+ poin= give_mtex_poin(mtex, (icu->adrcode & (MA_MAP1-1)));
}
}
- else {
- switch(icu->adrcode & (MA_MAP1-1)) {
- case MAP_OFS_X:
- case MAP_OFS_Y:
- case MAP_OFS_Z:
- case MAP_SIZE_X:
- case MAP_SIZE_Y:
- case MAP_SIZE_Z:
- icu->ymax= 100.0;
- icu->ymin= -100.0;
+ break;
+ case ID_CA: /* camera channels ----------------------------- */
+ {
+ Camera *ca= (Camera *)id;
+
+ switch (icu->adrcode) {
+ case CAM_LENS:
+ if (ca->type == CAM_ORTHO)
+ poin= &(ca->ortho_scale);
+ else
+ poin= &(ca->lens);
break;
- case MAP_R:
- case MAP_G:
- case MAP_B:
- case MAP_DVAR:
- case MAP_COLF:
- case MAP_NORF:
- case MAP_VARF:
- case MAP_DISP:
- icu->ymax= 1.0;
+ case CAM_STA:
+ poin= &(ca->clipsta); break;
+ case CAM_END:
+ poin= &(ca->clipend); break;
+
+ case CAM_YF_APERT:
+ poin= &(ca->YF_aperture); break;
+ case CAM_YF_FDIST:
+ poin= &(ca->YF_dofdist); break;
+
+ case CAM_SHIFT_X:
+ poin= &(ca->shiftx); break;
+ case CAM_SHIFT_Y:
+ poin= &(ca->shifty); break;
}
}
- }
- else if(icu->blocktype==ID_CA) {
-
- /* yafray: aperture & focal distance params */
- switch(icu->adrcode) {
- case CAM_LENS:
- icu->ymin= 5.0;
- icu->ymax= 1000.0;
- break;
- case CAM_STA:
- icu->ymin= 0.001f;
- break;
- case CAM_END:
- icu->ymin= 0.1f;
- break;
- case CAM_YF_APERT:
- icu->ymin = 0.0;
- icu->ymax = 2.0;
- break;
- case CAM_YF_FDIST:
- icu->ymin = 0.0;
- icu->ymax = 5000.0;
break;
+ case ID_SO: /* sound channels ----------------------------- */
+ {
+ bSound *snd= (bSound *)id;
- case CAM_SHIFT_X:
- case CAM_SHIFT_Y:
- icu->ymin= -2.0f;
- icu->ymax= 2.0f;
- break;
+ switch (icu->adrcode) {
+ case SND_VOLUME:
+ poin= &(snd->volume); break;
+ case SND_PITCH:
+ poin= &(snd->pitch); break;
+ case SND_PANNING:
+ poin= &(snd->panning); break;
+ case SND_ATTEN:
+ poin= &(snd->attenuation); break;
+ }
}
- }
- else if(icu->blocktype==ID_SO) {
-
- switch(icu->adrcode) {
- case SND_VOLUME:
- icu->ymin= 0.0;
- icu->ymax= 1.0;
- break;
- case SND_PITCH:
- icu->ymin= -12.0;
- icu->ymin= 12.0;
- break;
- case SND_PANNING:
- icu->ymin= 0.0;
- icu->ymax= 1.0;
- break;
- case SND_ATTEN:
- icu->ymin= 0.0;
- icu->ymin= 1.0;
break;
+ case ID_PA: /* particle channels ----------------------------- */
+ {
+ ParticleSettings *part= (ParticleSettings *)id;
+
+ switch (icu->adrcode) {
+ case PART_EMIT_FREQ:
+ case PART_EMIT_LIFE:
+ case PART_EMIT_VEL:
+ case PART_EMIT_AVE:
+ case PART_EMIT_SIZE:
+ poin= NULL;
+ break;
+
+ case PART_CLUMP:
+ poin= &(part->clumpfac); break;
+ case PART_AVE:
+ poin= &(part->avefac); break;
+ case PART_SIZE:
+ poin= &(part->size); break;
+ case PART_DRAG:
+ poin= &(part->dragfac); break;
+ case PART_BROWN:
+ poin= &(part->brownfac); break;
+ case PART_DAMP:
+ poin= &(part->dampfac); break;
+ case PART_LENGTH:
+ poin= &(part->length); break;
+ case PART_GRAV_X:
+ poin= &(part->acc[0]); break;
+ case PART_GRAV_Y:
+ poin= &(part->acc[1]); break;
+ case PART_GRAV_Z:
+ poin= &(part->acc[2]); break;
+ case PART_KINK_AMP:
+ poin= &(part->kink_amp); break;
+ case PART_KINK_FREQ:
+ poin= &(part->kink_freq); break;
+ case PART_KINK_SHAPE:
+ poin= &(part->kink_shape); break;
+ case PART_BB_TILT:
+ poin= &(part->bb_tilt); break;
+
+ case PART_PD_FSTR:
+ if (part->pd) poin= &(part->pd->f_strength);
+ break;
+ case PART_PD_FFALL:
+ if (part->pd) poin= &(part->pd->f_power);
+ break;
+ case PART_PD_FMAXD:
+ if (part->pd) poin= &(part->pd->maxdist);
+ break;
+ case PART_PD2_FSTR:
+ if (part->pd2) poin= &(part->pd2->f_strength);
+ break;
+ case PART_PD2_FFALL:
+ if (part->pd2) poin= &(part->pd2->f_power);
+ break;
+ case PART_PD2_FMAXD:
+ if (part->pd2) poin= &(part->pd2->maxdist);
+ break;
+ }
}
- }
- else if(icu->blocktype==ID_PA){
-
- switch(icu->adrcode) {
- case PART_EMIT_LIFE:
- case PART_SIZE:
- case PART_KINK_FREQ:
- case PART_EMIT_VEL:
- case PART_EMIT_AVE:
- case PART_EMIT_SIZE:
- icu->ymin= 0.0;
break;
- case PART_CLUMP:
- case PART_DRAG:
- case PART_DAMP:
- case PART_LENGTH:
- icu->ymin= 0.0;
- icu->ymax= 1.0;
- break;
- case PART_KINK_SHAPE:
- icu->ymin= -0.999;
- icu->ymax= 0.999;
- }
- }
- else if(icu->blocktype==ID_CO) {
- icu->ymin= 0.0;
- icu->ymax= 1.0f;
}
-
- /* by default, slider limits will be icu->ymin and icu->ymax */
- icu->slide_min= icu->ymin;
- icu->slide_max= icu->ymax;
-}
-/* not for actions or constraints! */
-void execute_ipo(ID *id, Ipo *ipo)
-{
- IpoCurve *icu;
- void *poin;
- int type;
-
- if(ipo==NULL) return;
-
- for(icu= ipo->curve.first; icu; icu= icu->next) {
- poin= get_ipo_poin(id, icu, &type);
- if(poin) write_ipo_poin(poin, type, icu->curval);
- }
+ /* return pointer */
+ return poin;
}
-void *get_pchan_ipo_poin(bPoseChannel *pchan, int adrcode)
+/* --------------------- IPO-Curve Limits ----------------------------- */
+
+/* set limits for IPO-curve
+ * Note: must be synced with UI and PyAPI
+ */
+void set_icu_vars (IpoCurve *icu)
{
- void *poin= NULL;
+ /* defaults. 0.0 for y-extents makes these ignored */
+ icu->ymin= icu->ymax= 0.0;
+ icu->ipo= IPO_BEZ;
- switch (adrcode) {
- case AC_QUAT_W:
- poin= &(pchan->quat[0]);
- pchan->flag |= POSE_ROT;
+ switch (icu->blocktype) {
+ case ID_OB: /* object channels ----------------------------- */
+ {
+ if (icu->adrcode == OB_LAY) {
+ icu->ipo= IPO_CONST;
+ icu->vartype= IPO_BITS;
+ }
+ }
break;
- case AC_QUAT_X:
- poin= &(pchan->quat[1]);
- pchan->flag |= POSE_ROT;
+ case ID_MA: /* material channels ----------------------------- */
+ {
+ if (icu->adrcode < MA_MAP1) {
+ switch (icu->adrcode) {
+ case MA_HASIZE:
+ icu->ymax= 10000.0; break;
+ case MA_HARD:
+ icu->ymax= 511.0; break;
+ case MA_SPEC:
+ icu->ymax= 2.0; break;
+ case MA_MODE:
+ icu->ipo= IPO_CONST;
+ icu->vartype= IPO_BITS; break;
+ case MA_RAYM:
+ icu->ymax= 1.0; break;
+ case MA_TRANSLU:
+ icu->ymax= 1.0; break;
+ case MA_IOR:
+ icu->ymin= 1.0;
+ icu->ymax= 3.0; break;
+ case MA_FRESMIR:
+ icu->ymax= 5.0; break;
+ case MA_FRESMIRI:
+ icu->ymin= 1.0;
+ icu->ymax= 5.0; break;
+ case MA_FRESTRA:
+ icu->ymax= 5.0; break;
+ case MA_FRESTRAI:
+ icu->ymin= 1.0;
+ icu->ymax= 5.0; break;
+ case MA_ADD:
+ icu->ymax= 1.0; break;
+ case MA_EMIT:
+ icu->ymax= 2.0; break;
+ default:
+ icu->ymax= 1.0; break;
+ }
+ }
+ else {
+ switch (icu->adrcode & (MA_MAP1-1)) {
+ case MAP_OFS_X:
+ case MAP_OFS_Y:
+ case MAP_OFS_Z:
+ case MAP_SIZE_X:
+ case MAP_SIZE_Y:
+ case MAP_SIZE_Z:
+ icu->ymax= 1000.0;
+ icu->ymin= -1000.0;
+ break;
+ case MAP_R:
+ case MAP_G:
+ case MAP_B:
+ case MAP_DVAR:
+ case MAP_COLF:
+ case MAP_VARF:
+ case MAP_DISP:
+ icu->ymax= 1.0;
+ break;
+ case MAP_NORF:
+ icu->ymax= 25.0;
+ break;
+ }
+ }
+ }
break;
- case AC_QUAT_Y:
- poin= &(pchan->quat[2]);
- pchan->flag |= POSE_ROT;
+ case ID_TE: /* texture channels ----------------------------- */
+ {
+ switch (icu->adrcode & (MA_MAP1-1)) {
+ case TE_NSIZE:
+ icu->ymin= 0.0001f;
+ icu->ymax= 2.0f;
+ break;
+ case TE_NDEPTH:
+ icu->vartype= IPO_SHORT;
+ icu->ipo= IPO_CONST;
+ icu->ymax= 6.0f;
+ break;
+ case TE_NTYPE:
+ icu->vartype= IPO_SHORT;
+ icu->ipo= IPO_CONST;
+ icu->ymax= 1.0f;
+ break;
+ case TE_TURB:
+ icu->ymax= 200.0f;
+ break;
+ case TE_VNW1:
+ case TE_VNW2:
+ case TE_VNW3:
+ case TE_VNW4:
+ icu->ymax= 2.0f;
+ icu->ymin= -2.0f;
+ break;
+ case TE_VNMEXP:
+ icu->ymax= 10.0f;
+ icu->ymin= 0.01f;
+ break;
+ case TE_VN_DISTM:
+ icu->vartype= IPO_SHORT;
+ icu->ipo= IPO_CONST;
+ icu->ymax= 6.0f;
+ break;
+ case TE_VN_COLT:
+ icu->vartype= IPO_SHORT;
+ icu->ipo= IPO_CONST;
+ icu->ymax= 3.0f;
+ break;
+ case TE_ISCA:
+ icu->ymax= 10.0f;
+ icu->ymin= 0.01f;
+ break;
+ case TE_DISTA:
+ icu->ymax= 10.0f;
+ break;
+ case TE_MG_TYP:
+ icu->vartype= IPO_SHORT;
+ icu->ipo= IPO_CONST;
+ icu->ymax= 6.0f;
+ break;
+ case TE_MGH:
+ icu->ymin= 0.0001f;
+ icu->ymax= 2.0f;
+ break;
+ case TE_MG_LAC:
+ case TE_MG_OFF:
+ case TE_MG_GAIN:
+ icu->ymax= 6.0f; break;
+ case TE_MG_OCT:
+ icu->ymax= 8.0f; break;
+ case TE_N_BAS1:
+ case TE_N_BAS2:
+ icu->vartype= IPO_SHORT;
+ icu->ipo= IPO_CONST;
+ icu->ymax= 8.0f;
+ break;
+ case TE_COL_R:
+ icu->ymax= 0.0f; break;
+ case TE_COL_G:
+ icu->ymax= 2.0f; break;
+ case TE_COL_B:
+ icu->ymax= 2.0f; break;
+ case TE_BRIGHT:
+ icu->ymax= 2.0f; break;
+ case TE_CONTRA:
+ icu->ymax= 5.0f; break;
+ }
+ }
break;
- case AC_QUAT_Z:
- poin= &(pchan->quat[3]);
- pchan->flag |= POSE_ROT;
+ case ID_SEQ: /* sequence channels ----------------------------- */
+ {
+ icu->ymax= 1.0f;
+ }
break;
- case AC_LOC_X:
- poin= &(pchan->loc[0]);
- pchan->flag |= POSE_LOC;
+ case ID_CU: /* curve channels ----------------------------- */
+ {
+ icu->ymax= 1.0f;
+ }
break;
- case AC_LOC_Y:
- poin= &(pchan->loc[1]);
- pchan->flag |= POSE_LOC;
+ case ID_WO: /* world channels ----------------------------- */
+ {
+ if (icu->adrcode < MA_MAP1) {
+ switch (icu->adrcode) {
+ case WO_EXPOS:
+ icu->ymax= 5.0f; break;
+
+ case WO_MISTDI:
+ case WO_MISTSTA:
+ case WO_MISTHI:
+ case WO_STARDIST:
+ case WO_STARSIZE:
+ break;
+
+ default:
+ icu->ymax= 1.0f;
+ break;
+ }
+ }
+ else {
+ switch (icu->adrcode & (MA_MAP1-1)) {
+ case MAP_OFS_X:
+ case MAP_OFS_Y:
+ case MAP_OFS_Z:
+ case MAP_SIZE_X:
+ case MAP_SIZE_Y:
+ case MAP_SIZE_Z:
+ icu->ymax= 100.0f;
+ icu->ymin= -100.0f;
+ break;
+ case MAP_R:
+ case MAP_G:
+ case MAP_B:
+ case MAP_DVAR:
+ case MAP_COLF:
+ case MAP_NORF:
+ case MAP_VARF:
+ case MAP_DISP:
+ icu->ymax= 1.0f;
+ }
+ }
+ }
break;
- case AC_LOC_Z:
- poin= &(pchan->loc[2]);
- pchan->flag |= POSE_LOC;
- break;
- case AC_SIZE_X:
- poin= &(pchan->size[0]);
- pchan->flag |= POSE_SIZE;
+ case ID_LA: /* lamp channels ----------------------------- */
+ {
+ if (icu->adrcode < MA_MAP1) {
+ switch (icu->adrcode) {
+ case LA_ENERGY:
+ case LA_DIST:
+ break;
+
+ case LA_COL_R:
+ case LA_COL_G:
+ case LA_COL_B:
+ case LA_SPOTBL:
+ case LA_QUAD1:
+ case LA_QUAD2:
+ icu->ymax= 1.0f; break;
+
+ case LA_SPOTSI:
+ icu->ymax= 180.0f; break;
+
+ case LA_HALOINT:
+ icu->ymax= 5.0f; break;
+ }
+ }
+ else {
+ switch (icu->adrcode & (MA_MAP1-1)) {
+ case MAP_OFS_X:
+ case MAP_OFS_Y:
+ case MAP_OFS_Z:
+ case MAP_SIZE_X:
+ case MAP_SIZE_Y:
+ case MAP_SIZE_Z:
+ icu->ymax= 100.0f;
+ icu->ymin= -100.0f;
+ break;
+ case MAP_R:
+ case MAP_G:
+ case MAP_B:
+ case MAP_DVAR:
+ case MAP_COLF:
+ case MAP_NORF:
+ case MAP_VARF:
+ case MAP_DISP:
+ icu->ymax= 1.0f;
+ }
+ }
+ }
break;
- case AC_SIZE_Y:
- poin= &(pchan->size[1]);
- pchan->flag |= POSE_SIZE;
+ case ID_CA: /* camera channels ----------------------------- */
+ {
+ switch (icu->adrcode) {
+ case CAM_LENS:
+ icu->ymin= 1.0f;
+ icu->ymax= 1000.0f;
+ break;
+ case CAM_STA:
+ icu->ymin= 0.001f;
+ break;
+ case CAM_END:
+ icu->ymin= 0.1f;
+ break;
+
+ case CAM_YF_APERT:
+ icu->ymin = 0.0f;
+ icu->ymax = 2.0f;
+ break;
+ case CAM_YF_FDIST:
+ icu->ymin = 0.0f;
+ icu->ymax = 5000.0f;
+ break;
+
+ case CAM_SHIFT_X:
+ case CAM_SHIFT_Y:
+ icu->ymin= -2.0f;
+ icu->ymax= 2.0f;
+ break;
+ }
+ }
break;
- case AC_SIZE_Z:
- poin= &(pchan->size[2]);
- pchan->flag |= POSE_SIZE;
+ case ID_SO: /* sound channels ----------------------------- */
+ {
+ switch (icu->adrcode) {
+ case SND_VOLUME:
+ icu->ymin= 0.0f;
+ icu->ymax= 1.0f;
+ break;
+ case SND_PITCH:
+ icu->ymin= -12.0f;
+ icu->ymin= 12.0f;
+ break;
+ case SND_PANNING:
+ icu->ymin= 0.0f;
+ icu->ymax= 1.0f;
+ break;
+ case SND_ATTEN:
+ icu->ymin= 0.0f;
+ icu->ymin= 1.0f;
+ break;
+ }
+ }
break;
- }
- return poin;
-}
-
-void execute_action_ipo(bActionChannel *achan, bPoseChannel *pchan)
-{
-
- if(achan && achan->ipo) {
- IpoCurve *icu;
- for(icu= achan->ipo->curve.first; icu; icu= icu->next) {
- void *poin= get_pchan_ipo_poin(pchan, icu->adrcode);
- if(poin) {
- write_ipo_poin(poin, IPO_FLOAT, icu->curval);
- //printf("execute_action_ipo wrote_ipo_poin: %f\n", icu->curval);
- //printf("%s has poin %p value %f\n", achan->name, poin, icu->curval);
+ case ID_PA: /* particle channels ----------------------------- */
+ {
+ switch (icu->adrcode) {
+ case PART_EMIT_LIFE:
+ case PART_SIZE:
+ case PART_KINK_FREQ:
+ case PART_EMIT_VEL:
+ case PART_EMIT_AVE:
+ case PART_EMIT_SIZE:
+ icu->ymin= 0.0f;
+ break;
+ case PART_CLUMP:
+ icu->ymin= -1.0f;
+ icu->ymax= 1.0f;
+ break;
+ case PART_DRAG:
+ case PART_DAMP:
+ case PART_LENGTH:
+ icu->ymin= 0.0f;
+ icu->ymax= 1.0f;
+ break;
+ case PART_KINK_SHAPE:
+ icu->ymin= -0.999f;
+ icu->ymax= 0.999f;
+ break;
}
}
+ break;
+ case ID_CO: /* constraint channels ----------------------------- */
+ {
+ icu->ymin= 0.0f;
+ icu->ymax= 1.0f;
+ }
+ break;
}
+
+ /* by default, slider limits will be icu->ymin and icu->ymax */
+ icu->slide_min= icu->ymin;
+ icu->slide_max= icu->ymax;
}
-/* exception: it does calc for objects...
- * now find out why this routine was used anyway!
- */
-void do_ipo_nocalc(Ipo *ipo)
+/* --------------------- Pointer I/O API ----------------------------- */
+
+/* write the given value directly into the given pointer */
+void write_ipo_poin (void *poin, int type, float val)
{
- Object *ob;
- Material *ma;
- Tex *tex;
- World *wo;
- Lamp *la;
- Camera *ca;
- bSound *snd;
-
- if(ipo==NULL) return;
-
- switch(ipo->blocktype) {
- case ID_OB:
- ob= G.main->object.first;
- while(ob) {
- if(ob->ipo==ipo) {
- do_ob_ipo(ob);
- /* execute_ipo((ID *)ob, ipo); */
- }
- ob= ob->id.next;
- }
- break;
- case ID_MA:
- ma= G.main->mat.first;
- while(ma) {
- if(ma->ipo==ipo) execute_ipo((ID *)ma, ipo);
- ma= ma->id.next;
- }
- break;
- case ID_TE:
- tex= G.main->tex.first;
- while(tex) {
- if(tex->ipo==ipo) execute_ipo((ID *)tex, ipo);
- tex=tex->id.next;
- }
+ /* Note: we only support a limited number of types, with the value
+ * to set needing to be cast to the appropriate type first
+ * -> (float to integer conversions could be slow)
+ */
+ switch(type) {
+ case IPO_FLOAT:
+ *((float *)poin)= val;
break;
- case ID_WO:
- wo= G.main->world.first;
- while(wo) {
- if(wo->ipo==ipo) execute_ipo((ID *)wo, ipo);
- wo= wo->id.next;
- }
+
+ case IPO_FLOAT_DEGR: /* special hack for rotation so that it fits on same axis as other transforms */
+ *((float *)poin)= (float)(val * M_PI_2 / 9.0);
break;
- case ID_LA:
- la= G.main->lamp.first;
- while(la) {
- if(la->ipo==ipo) execute_ipo((ID *)la, ipo);
- la= la->id.next;
- }
+
+ case IPO_INT:
+ case IPO_INT_BIT: // fixme... directly revealing bitflag combinations is evil!
+ case IPO_LONG:
+ *((int *)poin)= (int)val;
break;
- case ID_CA:
- ca= G.main->camera.first;
- while(ca) {
- if(ca->ipo==ipo) execute_ipo((ID *)ca, ipo);
- ca= ca->id.next;
- }
+
+ case IPO_SHORT:
+ case IPO_SHORT_BIT: // fixme... directly revealing bitflag combinations is evil!
+ *((short *)poin)= (short)val;
break;
- case ID_SO:
- snd= G.main->sound.first;
- while(snd) {
- if(snd->ipo==ipo) execute_ipo((ID *)snd, ipo);
- snd= snd->id.next;
- }
+
+ case IPO_CHAR:
+ case IPO_CHAR_BIT: // fixme... directly revealing bitflag combinations is evil!
+ *((char *)poin)= (char)val;
break;
}
}
-void do_ipo(Ipo *ipo)
-{
- if(ipo) {
- float ctime= frame_to_float(G.scene->r.cfra);
- calc_ipo(ipo, ctime);
-
- do_ipo_nocalc(ipo);
- }
-}
-
-
-
-void do_mat_ipo(Material *ma)
-{
- float ctime;
-
- if(ma==NULL || ma->ipo==NULL) return;
-
- ctime= frame_to_float(G.scene->r.cfra);
- /* if(ob->ipoflag & OB_OFFS_OB) ctime-= ob->sf; */
-
- calc_ipo(ma->ipo, ctime);
-
- execute_ipo((ID *)ma, ma->ipo);
-}
-
-void do_ob_ipo(Object *ob)
-{
- float ctime;
- unsigned int lay;
-
- if(ob->ipo==NULL) return;
-
- /* do not set ob->ctime here: for example when parent in invisible layer */
-
- ctime= bsystem_time(ob, (float) G.scene->r.cfra, 0.0);
-
- calc_ipo(ob->ipo, ctime);
-
- /* Patch: remember localview */
- lay= ob->lay & 0xFF000000;
-
- execute_ipo((ID *)ob, ob->ipo);
-
- ob->lay |= lay;
- if(ob->id.name[2]=='S' && ob->id.name[3]=='C' && ob->id.name[4]=='E') {
- if(strcmp(G.scene->id.name+2, ob->id.name+6)==0) {
- G.scene->lay= ob->lay;
- //XXX copy_view3d_lock(0);
- /* no redraw here! creates too many calls */
- }
- }
-}
-
-void do_ob_ipodrivers(Object *ob, Ipo *ipo, float ctime)
+/* read the value from the pointer that was obtained */
+float read_ipo_poin (void *poin, int type)
{
- IpoCurve *icu;
- void *poin;
- int type;
-
- for(icu= ipo->curve.first; icu; icu= icu->next) {
- if(icu->driver) {
- icu->curval= eval_icu(icu, ctime);
- poin= get_ipo_poin((ID *)ob, icu, &type);
- if(poin) write_ipo_poin(poin, type, icu->curval);
- }
- }
-}
-
-void do_seq_ipo(Sequence *seq, int cfra)
-{
- float ctime, div;
-
- /* seq_ipo has an exception: calc both fields immediately */
+ float val = 0.0;
- if(seq->ipo) {
- if((seq->flag & SEQ_IPO_FRAME_LOCKED) != 0) {
- ctime = frame_to_float(cfra);
- div = 1.0;
- } else {
- ctime= frame_to_float(cfra - seq->startdisp);
- div= (seq->enddisp - seq->startdisp)/100.0f;
- if(div==0.0) return;
- }
+ /* Note: we only support a limited number of types, with the value
+ * to set needing to be cast to the appropriate type first
+ * -> (int to float conversions may loose accuracy in rare cases)
+ */
+ switch (type) {
+ case IPO_FLOAT:
+ val= *((float *)poin);
+ break;
- /* 2nd field */
- calc_ipo(seq->ipo, (ctime+0.5f)/div);
- execute_ipo((ID *)seq, seq->ipo);
- seq->facf1= seq->facf0;
-
- /* 1st field */
- calc_ipo(seq->ipo, ctime/div);
- execute_ipo((ID *)seq, seq->ipo);
-
- }
- else seq->facf1= seq->facf0= 1.0f;
-}
-
-int has_ipo_code(Ipo *ipo, int code)
-{
- IpoCurve *icu;
-
- if(ipo==NULL) return 0;
-
- for(icu= ipo->curve.first; icu; icu= icu->next) {
- if(icu->adrcode==code) return 1;
- }
- return 0;
-}
-
-void do_all_data_ipos()
-{
- Material *ma;
- Tex *tex;
- World *wo;
- Ipo *ipo;
- Lamp *la;
- Key *key;
- Camera *ca;
- bSound *snd;
- Sequence *seq;
- Editing *ed;
- Base *base;
- float ctime;
-
- ctime= frame_to_float(G.scene->r.cfra);
-
- /* this exception cannot be depgraphed yet... what todo with objects in other layers?... */
- for(base= G.scene->base.first; base; base= base->next) {
- /* only update layer when an ipo */
- if( has_ipo_code(base->object->ipo, OB_LAY) ) {
- do_ob_ipo(base->object);
- base->lay= base->object->lay;
- }
- }
-
- /* layers for the set...*/
- if(G.scene->set) {
- for(base= G.scene->set->base.first; base; base= base->next) {
- if( has_ipo_code(base->object->ipo, OB_LAY) ) {
- do_ob_ipo(base->object);
- base->lay= base->object->lay;
- }
- }
- }
-
-
- ipo= G.main->ipo.first;
- while(ipo) {
- if(ipo->id.us && ipo->blocktype!=ID_OB) {
- calc_ipo(ipo, ctime);
- }
- ipo= ipo->id.next;
- }
-
- for(tex= G.main->tex.first; tex; tex= tex->id.next) {
- if(tex->ipo) execute_ipo((ID *)tex, tex->ipo);
- }
-
- for(ma= G.main->mat.first; ma; ma= ma->id.next) {
- if(ma->ipo) execute_ipo((ID *)ma, ma->ipo);
- }
-
- for(wo= G.main->world.first; wo; wo= wo->id.next) {
- if(wo->ipo) execute_ipo((ID *)wo, wo->ipo);
- }
-
- for(key= G.main->key.first; key; key= key->id.next) {
- if(key->ipo) execute_ipo((ID *)key, key->ipo);
- }
-
- la= G.main->lamp.first;
- while(la) {
- if(la->ipo) execute_ipo((ID *)la, la->ipo);
- la= la->id.next;
- }
-
- ca= G.main->camera.first;
- while(ca) {
- if(ca->ipo) execute_ipo((ID *)ca, ca->ipo);
- ca= ca->id.next;
- }
-
- snd= G.main->sound.first;
- while(snd) {
- if(snd->ipo) execute_ipo((ID *)snd, snd->ipo);
- snd= snd->id.next;
- }
-
- /* process FAC Ipos used as volume envelopes */
- ed= G.scene->ed;
- if (ed) {
- seq= ed->seqbasep->first;
- while(seq) {
- if ((seq->type == SEQ_RAM_SOUND
- || seq->type == SEQ_HD_SOUND) && (seq->ipo) &&
- (seq->startdisp<=G.scene->r.cfra+2) &&
- (seq->enddisp>G.scene->r.cfra))
- do_seq_ipo(seq, G.scene->r.cfra);
- seq= seq->next;
- }
- }
-
-}
-
-
-int calc_ipo_spec(Ipo *ipo, int adrcode, float *ctime)
-{
- IpoCurve *icu;
-
- if(ipo==NULL) return 0;
-
- for(icu= ipo->curve.first; icu; icu= icu->next) {
- if(icu->adrcode == adrcode) {
- if(icu->flag & IPO_LOCK);
- else calc_icu(icu, *ctime);
-
- *ctime= icu->curval;
- return 1;
- }
- }
-
- return 0;
-}
-
-
-/* ************************** */
-
-void clear_delta_obipo(Ipo *ipo)
-{
- Object *ob;
+ case IPO_FLOAT_DEGR: /* special hack for rotation so that it fits on same axis as other transforms */
+ val= *( (float *)poin);
+ val = (float)(val / (M_PI_2/9.0));
+ break;
- if(ipo==NULL) return;
+ case IPO_INT:
+ case IPO_INT_BIT: // fixme... directly revealing bitflag combinations is evil!
+ case IPO_LONG:
+ val= (float)( *((int *)poin) );
+ break;
+
+ case IPO_SHORT:
+ case IPO_SHORT_BIT: // fixme... directly revealing bitflag combinations is evil!
+ val= *((short *)poin);
+ break;
- ob= G.main->object.first;
- while(ob) {
- if(ob->id.lib==NULL) {
- if(ob->ipo==ipo) {
- memset(&ob->dloc, 0, 12);
- memset(&ob->drot, 0, 12);
- memset(&ob->dsize, 0, 12);
- }
- }
- ob= ob->id.next;
+ case IPO_CHAR:
+ case IPO_CHAR_BIT: // fixme... directly revealing bitflag combinations is evil
+ val= *((char *)poin);
+ break;
}
-}
-
-void add_to_cfra_elem(ListBase *lb, BezTriple *bezt)
-{
- CfraElem *ce, *cen;
-
- ce= lb->first;
- while(ce) {
-
- if( ce->cfra==bezt->vec[1][0] ) {
- /* do because of double keys */
- if(bezt->f2 & SELECT) ce->sel= bezt->f2;
- return;
- }
- else if(ce->cfra > bezt->vec[1][0]) break;
-
- ce= ce->next;
- }
- cen= MEM_callocN(sizeof(CfraElem), "add_to_cfra_elem");
- if(ce) BLI_insertlinkbefore(lb, ce, cen);
- else BLI_addtail(lb, cen);
-
- cen->cfra= bezt->vec[1][0];
- cen->sel= bezt->f2;
+ /* return value */
+ return val;
}
+// !!!!!!!!!!!!!!!!!!!!!!!!!!!! FIXME - BAD CRUFT WARNING !!!!!!!!!!!!!!!!!!!!!!!
-void make_cfra_list(Ipo *ipo, ListBase *elems)
-{
- IpoCurve *icu;
- BezTriple *bezt;
- int a;
-
- if(ipo->blocktype==ID_OB) {
- for(icu= ipo->curve.first; icu; icu= icu->next) {
- if(icu->flag & IPO_VISIBLE) {
- switch(icu->adrcode) {
- case OB_DLOC_X:
- case OB_DLOC_Y:
- case OB_DLOC_Z:
- case OB_DROT_X:
- case OB_DROT_Y:
- case OB_DROT_Z:
- case OB_DSIZE_X:
- case OB_DSIZE_Y:
- case OB_DSIZE_Z:
-
- case OB_LOC_X:
- case OB_LOC_Y:
- case OB_LOC_Z:
- case OB_ROT_X:
- case OB_ROT_Y:
- case OB_ROT_Z:
- case OB_SIZE_X:
- case OB_SIZE_Y:
- case OB_SIZE_Z:
- case OB_PD_FSTR:
- case OB_PD_FFALL:
- case OB_PD_SDAMP:
- case OB_PD_RDAMP:
- case OB_PD_PERM:
- case OB_PD_FMAXD:
- bezt= icu->bezt;
- if(bezt) {
- a= icu->totvert;
- while(a--) {
- add_to_cfra_elem(elems, bezt);
- bezt++;
- }
- }
- break;
- }
- }
- }
- }
- else if(ipo->blocktype==ID_AC) {
- for(icu= ipo->curve.first; icu; icu= icu->next) {
- if(icu->flag & IPO_VISIBLE) {
- switch(icu->adrcode) {
- case AC_LOC_X:
- case AC_LOC_Y:
- case AC_LOC_Z:
- case AC_SIZE_X:
- case AC_SIZE_Y:
- case AC_SIZE_Z:
- case AC_QUAT_W:
- case AC_QUAT_X:
- case AC_QUAT_Y:
- case AC_QUAT_Z:
- bezt= icu->bezt;
- if(bezt) {
- a= icu->totvert;
- while(a--) {
- add_to_cfra_elem(elems, bezt);
- bezt++;
- }
- }
- break;
- }
- }
- }
- }
- else {
- for(icu= ipo->curve.first; icu; icu= icu->next) {
- if(icu->flag & IPO_VISIBLE) {
- bezt= icu->bezt;
- if(bezt) {
- a= icu->totvert;
- while(a--) {
- add_to_cfra_elem(elems, bezt);
- bezt++;
- }
- }
- }
- }
- }
-
- /* what's the point of this little block of code? */
-#if 0
- if(ipo->showkey==0) {
- /* deselect all keys */
- ce= elems->first;
- while(ce) {
- ce->sel= 0;
- ce= ce->next;
- }
- }
-#endif
-}
-
-/* *********************** INTERFACE FOR KETSJI ********** */
-
+/* ***************************** IPO <--> GameEngine Interface ********************************* */
-int IPO_GetChannels(Ipo *ipo, IPO_Channel *channels)
+/* channels is max 32 items, allocated by calling function */
+short IPO_GetChannels (Ipo *ipo, IPO_Channel *channels)
{
- /* channels is max 32 items, allocated by calling function */
-
IpoCurve *icu;
- int total=0;
+ int total = 0;
- if(ipo==NULL) return 0;
+ /* don't do anything with no IPO-block */
+ if (ipo == NULL)
+ return 0;
- for(icu= ipo->curve.first; icu; icu= icu->next) {
+ /* store the IPO-curve's adrcode in the relevant channel slot */
+ for (icu=ipo->curve.first; (icu) && (total < 31); icu=icu->next, total++)
channels[total]= icu->adrcode;
- total++;
- if(total>31) break;
- }
+ /* return the number of channels stored */
return total;
}
-
-
/* Get the float value for channel 'channel' at time 'ctime' */
-
-float IPO_GetFloatValue(Ipo *ipo, IPO_Channel channel, float ctime)
+float IPO_GetFloatValue (Ipo *ipo, IPO_Channel channel, float ctime)
{
- if(ipo==NULL) return 0;
+ /* don't evaluate if no IPO to use */
+ if (ipo == NULL)
+ return 0;
+ /* only calculate the specified channel */
calc_ipo_spec(ipo, channel, &ctime);
- if (OB_ROT_X <= channel && channel <= OB_DROT_Z) {
+ /* unapply rotation hack, as gameengine doesn't use it */
+ if ((OB_ROT_X <= channel) && (channel <= OB_DROT_Z))
ctime *= (float)(M_PI_2/9.0);
- }
+ /* return the value of this channel */
return ctime;
}
diff --git a/source/blender/blenkernel/intern/key.c b/source/blender/blenkernel/intern/key.c
index dd5adac29b0..a34da4377b1 100644
--- a/source/blender/blenkernel/intern/key.c
+++ b/source/blender/blenkernel/intern/key.c
@@ -281,10 +281,10 @@ void set_four_ipo(float d, float *data, int type)
}
else if(type==KEY_BSPLINE) {
- data[0]= -0.1666f*d3 +0.5f*d2 -0.5f*d +0.16666f;
- data[1]= 0.5f*d3 -d2 +0.6666f;
- data[2]= -0.5f*d3 +0.5f*d2 +0.5f*d +0.1666f;
- data[3]= 0.1666f*d3 ;
+ data[0]= -0.16666666f*d3 +0.5f*d2 -0.5f*d +0.16666666f;
+ data[1]= 0.5f*d3 -d2 +0.6666666f;
+ data[2]= -0.5f*d3 +0.5f*d2 +0.5f*d +0.16666666f;
+ data[3]= 0.16666666f*d3 ;
}
}
}
@@ -310,10 +310,10 @@ void set_afgeleide_four_ipo(float d, float *data, int type)
}
else if(type==KEY_BSPLINE) {
- data[0]= -0.1666f*3.0f*d2 +d -0.5f;
+ data[0]= -0.16666666f*3.0f*d2 +d -0.5f;
data[1]= 1.5f*d2 -2.0f*d;
data[2]= -1.5f*d2 +d +0.5f;
- data[3]= 0.1666f*3.0f*d2 ;
+ data[3]= 0.16666666f*3.0f*d2 ;
}
}
}
@@ -539,26 +539,26 @@ static void cp_key(int start, int end, int tot, char *poin, Key *key, KeyBlock *
case IPO_FLOAT:
if(weights) {
- memcpy(poin, kref, 4*cp[0]);
+ memcpy(poin, kref, sizeof(float)*cp[0]);
if(*weights!=0.0f)
rel_flerp(cp[0], (float *)poin, (float *)kref, (float *)k1, *weights);
weights++;
}
else
- memcpy(poin, k1, 4*cp[0]);
+ memcpy(poin, k1, sizeof(float)*cp[0]);
poin+= ofsp[0];
break;
case IPO_BPOINT:
- memcpy(poin, k1, 3*4);
- memcpy(poin+16, k1+12, 4);
+ memcpy(poin, k1, 3*sizeof(float));
+ memcpy(poin+4*sizeof(float), k1+3*sizeof(float), sizeof(float));
poin+= ofsp[0];
break;
case IPO_BEZTRIPLE:
- memcpy(poin, k1, 4*12);
+ memcpy(poin, k1, sizeof(float)*10);
poin+= ofsp[0];
break;
@@ -627,7 +627,7 @@ void cp_cu_key(Curve *cu, KeyBlock *kb, int start, int end)
}
-static void do_rel_key(int start, int end, int tot, char *basispoin, Key *key, int mode)
+void do_rel_key(int start, int end, int tot, char *basispoin, Key *key, int mode)
{
KeyBlock *kb;
int *ofsp, ofs[3], elemsize, b;
diff --git a/source/blender/blenkernel/intern/lattice.c b/source/blender/blenkernel/intern/lattice.c
index aaacba97d35..3f9143bb405 100644
--- a/source/blender/blenkernel/intern/lattice.c
+++ b/source/blender/blenkernel/intern/lattice.c
@@ -514,7 +514,7 @@ static int where_on_path_deform(Object *ob, float ctime, float *vec, float *dir)
/* co: local coord, result local too */
/* returns quaternion for rotation, using cd->no_rot_axis */
/* axis is using another define!!! */
-static float *calc_curve_deform(Object *par, float *co, short axis, CurveDeform *cd)
+static int calc_curve_deform(Object *par, float *co, short axis, CurveDeform *cd, float *quatp)
{
Curve *cu= par->data;
float fac, loc[4], dir[3], cent[3];
@@ -544,7 +544,7 @@ static float *calc_curve_deform(Object *par, float *co, short axis, CurveDeform
/* to be sure, mostly after file load */
if(cu->path==NULL) {
makeDispListCurveTypes(par, 0);
- if(cu->path==NULL) return NULL; // happens on append...
+ if(cu->path==NULL) return 0; // happens on append...
}
/* options */
@@ -570,14 +570,13 @@ static float *calc_curve_deform(Object *par, float *co, short axis, CurveDeform
}
if( where_on_path_deform(par, fac, loc, dir)) { /* returns OK */
- float q[4], mat[3][3];
- float *quat;
+ float q[4], mat[3][3], quat[4];
if(cd->no_rot_axis) /* set by caller */
dir[cd->no_rot_axis-1]= 0.0f;
/* -1 for compatibility with old track defines */
- quat= vectoquat(dir, axis-1, upflag); /* gives static quat */
+ vectoquat(dir, axis-1, upflag, quat);
/* the tilt */
if(loc[3]!=0.0) {
@@ -597,18 +596,26 @@ static float *calc_curve_deform(Object *par, float *co, short axis, CurveDeform
/* translation */
VECADD(co, cent, loc);
- return quat;
+ if(quatp)
+ QUATCOPY(quatp, quat);
+
+ return 1;
}
- return NULL;
+ return 0;
}
void curve_deform_verts(Object *cuOb, Object *target, DerivedMesh *dm, float (*vertexCos)[3], int numVerts, char *vgroup, short defaxis)
{
- Curve *cu = cuOb->data;
- int a, flag = cu->flag;
+ Curve *cu;
+ int a, flag;
CurveDeform cd;
int use_vgroups;
-
+
+ if(cuOb->type != OB_CURVE)
+ return;
+
+ cu = cuOb->data;
+ flag = cu->flag;
cu->flag |= (CU_PATH|CU_FOLLOW); // needed for path & bevlist
init_curve_deform(cuOb, target, &cd, (cu->flag & CU_STRETCH)==0);
@@ -663,7 +670,7 @@ void curve_deform_verts(Object *cuOb, Object *target, DerivedMesh *dm, float (*v
for(j = 0; j < dvert->totweight; j++) {
if(dvert->dw[j].def_nr == index) {
VECCOPY(vec, vertexCos[a]);
- calc_curve_deform(cuOb, vec, defaxis, &cd);
+ calc_curve_deform(cuOb, vec, defaxis, &cd, NULL);
VecLerpf(vertexCos[a], vertexCos[a], vec,
dvert->dw[j].weight);
Mat4MulVecfl(cd.objectspace, vertexCos[a]);
@@ -681,7 +688,7 @@ void curve_deform_verts(Object *cuOb, Object *target, DerivedMesh *dm, float (*v
}
for(a = 0; a < numVerts; a++) {
- calc_curve_deform(cuOb, vertexCos[a], defaxis, &cd);
+ calc_curve_deform(cuOb, vertexCos[a], defaxis, &cd, NULL);
Mat4MulVecfl(cd.objectspace, vertexCos[a]);
}
}
@@ -694,8 +701,13 @@ void curve_deform_verts(Object *cuOb, Object *target, DerivedMesh *dm, float (*v
void curve_deform_vector(Object *cuOb, Object *target, float *orco, float *vec, float mat[][3], int no_rot_axis)
{
CurveDeform cd;
- float *quat;
+ float quat[4];
+ if(cuOb->type != OB_CURVE) {
+ Mat3One(mat);
+ return;
+ }
+
init_curve_deform(cuOb, target, &cd, 0); /* 0 no dloc */
cd.no_rot_axis= no_rot_axis; /* option to only rotate for XY, for example */
@@ -704,8 +716,7 @@ void curve_deform_vector(Object *cuOb, Object *target, float *orco, float *vec,
Mat4MulVecfl(cd.curvespace, vec);
- quat= calc_curve_deform(cuOb, vec, target->trackflag+1, &cd);
- if(quat) {
+ if(calc_curve_deform(cuOb, vec, target->trackflag+1, &cd, quat)) {
float qmat[3][3];
QuatToMat3(quat, qmat);
@@ -724,6 +735,9 @@ void lattice_deform_verts(Object *laOb, Object *target, DerivedMesh *dm,
int a;
int use_vgroups;
+ if(laOb->type != OB_LATTICE)
+ return;
+
init_latt_deform(laOb, target);
/* check whether to use vertex groups (only possible if target is a Mesh)
@@ -899,7 +913,10 @@ void lattice_calc_modifiers(Object *ob)
mti->deformVerts(md, ob, NULL, vertexCos, numVerts);
}
- if (vertexCos) {
+ /* always displist to make this work like derivedmesh */
+ if (!vertexCos) vertexCos = lattice_getVertexCos(ob, &numVerts);
+
+ {
DispList *dl = MEM_callocN(sizeof(*dl), "lt_dl");
dl->type = DL_VERTS;
dl->parts = 1;
@@ -909,3 +926,15 @@ void lattice_calc_modifiers(Object *ob)
BLI_addtail(&ob->disp, dl);
}
}
+
+struct MDeformVert* lattice_get_deform_verts(struct Object *oblatt)
+{
+ if(oblatt->type == OB_LATTICE)
+ {
+ Lattice *lt = (oblatt==G.obedit)?editLatt:(Lattice*)oblatt->data;
+ return lt->dvert;
+ }
+
+ return NULL;
+}
+
diff --git a/source/blender/blenkernel/intern/library.c b/source/blender/blenkernel/intern/library.c
index f0dd3d1ec4b..3acc10e8022 100644
--- a/source/blender/blenkernel/intern/library.c
+++ b/source/blender/blenkernel/intern/library.c
@@ -76,6 +76,7 @@
#include "DNA_effect_types.h"
#include "DNA_brush_types.h"
#include "DNA_particle_types.h"
+#include "DNA_space_types.h"
#include "DNA_windowmanager_types.h"
#include "BLI_blenlib.h"
@@ -111,8 +112,6 @@
#include "BKE_idprop.h"
#include "BKE_particle.h"
-//XXX #include "BPI_script.h"
-
#define MAX_IDPUP 60 /* was 24 */
/* ************* general ************************ */
@@ -226,49 +225,51 @@ void flag_all_listbases_ids(short flag, short value)
/* note: MAX_LIBARRAY define should match this code */
int set_listbasepointers(Main *main, ListBase **lb)
{
+ int a = 0;
+
/* BACKWARDS! also watch order of free-ing! (mesh<->mat) */
- lb[0]= &(main->ipo);
- lb[1]= &(main->key);
- lb[2]= &(main->image);
- lb[3]= &(main->tex);
- lb[4]= &(main->mat);
- lb[5]= &(main->vfont);
+ lb[a++]= &(main->ipo);
+ lb[a++]= &(main->key);
+ lb[a++]= &(main->nodetree);
+ lb[a++]= &(main->image);
+ lb[a++]= &(main->tex);
+ lb[a++]= &(main->mat);
+ lb[a++]= &(main->vfont);
/* Important!: When adding a new object type,
* the specific data should be inserted here
*/
- lb[6]= &(main->armature);
- lb[7]= &(main->action);
+ lb[a++]= &(main->armature);
+ lb[a++]= &(main->action);
- lb[8]= &(main->mesh);
- lb[9]= &(main->curve);
- lb[10]= &(main->mball);
+ lb[a++]= &(main->mesh);
+ lb[a++]= &(main->curve);
+ lb[a++]= &(main->mball);
- lb[11]= &(main->wave);
- lb[12]= &(main->latt);
- lb[13]= &(main->lamp);
- lb[14]= &(main->camera);
+ lb[a++]= &(main->wave);
+ lb[a++]= &(main->latt);
+ lb[a++]= &(main->lamp);
+ lb[a++]= &(main->camera);
- lb[15]= &(main->text);
- lb[16]= &(main->sound);
- lb[17]= &(main->group);
- lb[18]= &(main->nodetree);
- lb[19]= &(main->brush);
- lb[20]= &(main->script);
- lb[21]= &(main->particle);
+ lb[a++]= &(main->text);
+ lb[a++]= &(main->sound);
+ lb[a++]= &(main->group);
+ lb[a++]= &(main->brush);
+ lb[a++]= &(main->script);
+ lb[a++]= &(main->particle);
- lb[22]= &(main->world);
- lb[23]= &(main->screen);
- lb[24]= &(main->object);
- lb[25]= &(main->scene);
- lb[26]= &(main->library);
- lb[27]= &(main->wm);
+ lb[a++]= &(main->world);
+ lb[a++]= &(main->screen);
+ lb[a++]= &(main->object);
+ lb[a++]= &(main->scene);
+ lb[a++]= &(main->library);
+ lb[a++]= &(main->wm);
- lb[28]= NULL;
+ lb[a]= NULL;
- return 28;
+ return a;
}
/* *********** ALLOC AND FREE *****************
@@ -411,6 +412,10 @@ void *copy_libblock(void *rt)
lb= wich_libbase(G.main, GS(id->name));
idn= alloc_libblock(lb, GS(id->name), id->name+2);
+ if(idn==NULL) {
+ printf("ERROR: Illegal ID name for %s (Crashing now)\n", id->name);
+ }
+
idn_len= MEM_allocN_len(idn);
if(idn_len - sizeof(ID) > 0) {
cp= (char *)id;
@@ -951,7 +956,7 @@ int new_id(ListBase *lb, ID *id, const char *tname)
}
/* if result > 21, strncpy don't put the final '\0' to name. */
- if( result > 21 ) name[21]= 0;
+ if( result >= 21 ) name[21]= 0;
result = check_for_dupid( lb, id, name );
strcpy( id->name+2, name );
@@ -991,7 +996,7 @@ static void image_fix_relative_path(Image *ima)
{
if(ima->id.lib==NULL) return;
if(strncmp(ima->name, "//", 2)==0) {
- BLI_convertstringcode(ima->name, ima->id.lib->filename, 0);
+ BLI_convertstringcode(ima->name, ima->id.lib->filename);
BLI_makestringcode(G.sce, ima->name);
}
}
@@ -1008,7 +1013,7 @@ static void lib_indirect_test_id(ID *id)
Object *ob= (Object *)id;
bActionStrip *strip;
Mesh *me;
- PartEff *paf;
+
int a;
for (strip=ob->nlastrips.first; strip; strip=strip->next){
@@ -1020,10 +1025,6 @@ static void lib_indirect_test_id(ID *id)
for(a=0; a<ob->totcol; a++) {
LIBTAG(ob->mat[a]);
}
-
- paf = give_parteff(ob);
- if (paf)
- LIBTAG(paf->group);
LIBTAG(ob->dup_group);
LIBTAG(ob->proxy);
diff --git a/source/blender/blenkernel/intern/material.c b/source/blender/blenkernel/intern/material.c
index baaa5becd44..95534deae66 100644
--- a/source/blender/blenkernel/intern/material.c
+++ b/source/blender/blenkernel/intern/material.c
@@ -58,7 +58,11 @@
#include "BKE_node.h"
#include "BKE_utildefines.h"
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h"
+#endif
+
+#include "GPU_material.h"
/* used in UI and render */
Material defmaterial;
@@ -75,7 +79,9 @@ void free_material(Material *ma)
MTex *mtex;
int a;
+#ifndef DISABLE_PYTHON
BPY_free_scriptlink(&ma->scriptlink);
+#endif
for(a=0; a<MAX_MTEX; a++) {
mtex= ma->mtex[a];
@@ -95,6 +101,9 @@ void free_material(Material *ma)
ntreeFreeTree(ma->nodetree);
MEM_freeN(ma->nodetree);
}
+
+ if(ma->gpumaterial.first)
+ GPU_material_free(ma);
}
void init_material(Material *ma)
@@ -195,8 +204,10 @@ Material *copy_material(Material *ma)
id_us_plus((ID *)man->mtex[a]->tex);
}
}
-
+
+#ifndef DISABLE_PYTHON
BPY_copy_scriptlink(&ma->scriptlink);
+#endif
if(ma->ramp_col) man->ramp_col= MEM_dupallocN(ma->ramp_col);
if(ma->ramp_spec) man->ramp_spec= MEM_dupallocN(ma->ramp_spec);
@@ -206,6 +217,8 @@ Material *copy_material(Material *ma)
if(ma->nodetree) {
man->nodetree= ntreeCopyTree(ma->nodetree, 0); /* 0 == full new tree */
}
+
+ man->gpumaterial.first= man->gpumaterial.last= NULL;
return man;
}
@@ -629,9 +642,7 @@ static void do_init_render_material(Material *ma, int r_mode, float *amb)
if(ma->flarec==0) ma->flarec= 1;
- /* add all texcoflags from mtex */
- ma->texco= 0;
- ma->mapto= 0;
+ /* add all texcoflags from mtex, texco and mapto were cleared in advance */
for(a=0; a<MAX_MTEX; a++) {
/* separate tex switching */
@@ -726,6 +737,16 @@ void init_render_materials(int r_mode, float *amb)
{
Material *ma;
+ /* clear these flags before going over materials, to make sure they
+ * are cleared only once, otherwise node materials contained in other
+ * node materials can go wrong */
+ for(ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if(ma->id.us) {
+ ma->texco= 0;
+ ma->mapto= 0;
+ }
+ }
+
/* two steps, first initialize, then or the flags for layers */
for(ma= G.main->mat.first; ma; ma= ma->id.next) {
/* is_used flag comes back in convertblender.c */
diff --git a/source/blender/blenkernel/intern/mball.c b/source/blender/blenkernel/intern/mball.c
index a2a1c5dcfa6..d84ad0a5215 100644
--- a/source/blender/blenkernel/intern/mball.c
+++ b/source/blender/blenkernel/intern/mball.c
@@ -229,14 +229,14 @@ void tex_space_mball(Object *ob)
boundbox_set_from_min_max(bb, min, max);
}
-void make_orco_mball(Object *ob)
+float *make_orco_mball(Object *ob)
{
BoundBox *bb;
DispList *dl;
- float *data;
+ float *data, *orco, *orcodata;
float loc[3], size[3];
int a;
-
+
/* restore size and loc */
bb= ob->bb;
loc[0]= (bb->vec[0][0]+bb->vec[4][0])/2.0f;
@@ -247,15 +247,21 @@ void make_orco_mball(Object *ob)
size[2]= bb->vec[1][2]-loc[2];
dl= ob->disp.first;
+ orcodata= MEM_mallocN(sizeof(float)*3*dl->nr, "MballOrco");
+
data= dl->verts;
+ orco= orcodata;
a= dl->nr;
while(a--) {
- data[0]= (data[0]-loc[0])/size[0];
- data[1]= (data[1]-loc[1])/size[1];
- data[2]= (data[2]-loc[2])/size[2];
+ orco[0]= (data[0]-loc[0])/size[0];
+ orco[1]= (data[1]-loc[1])/size[1];
+ orco[2]= (data[2]-loc[2])/size[2];
data+= 3;
+ orco+= 3;
}
+
+ return orcodata;
}
/** \brief Test, if Object *ob is basic MetaBall.
*
@@ -369,7 +375,7 @@ Object *find_basis_mball(Object *basis)
#define RTF 7 /* right top far corner */
/* the LBN corner of cube (i, j, k), corresponds with location
- * (start.x+(i-0.5)*size, start.y+(j-0.5)*size, start.z+(k-0.5)*size) */
+ * (i-0.5)*size, (j-0.5)*size, (k-0.5)*size) */
#define HASHBIT (5)
#define HASHSIZE (size_t)(1<<(3*HASHBIT)) /*! < hash table size (32768) */
@@ -830,11 +836,11 @@ CORNER *setcorner (PROCESS* p, int i, int j, int k)
c = (CORNER *) new_pgn_element(sizeof(CORNER));
c->i = i;
- c->x = p->start.x+((float)i-0.5f)*p->size;
+ c->x = ((float)i-0.5f)*p->size;
c->j = j;
- c->y = p->start.y+((float)j-0.5f)*p->size;
+ c->y = ((float)j-0.5f)*p->size;
c->k = k;
- c->z = p->start.z+((float)k-0.5f)*p->size;
+ c->z = ((float)k-0.5f)*p->size;
c->value = p->function(c->x, c->y, c->z);
c->next = p->corners[index];
@@ -1208,8 +1214,8 @@ void converge (MB_POINT *p1, MB_POINT *p2, float v1, float v2,
p->y = neg.y;
p->z = neg.z;
while (1) {
- p->x = 0.5f*(pos.x + neg.x);
if (i++ == RES) return;
+ p->x = 0.5f*(pos.x + neg.x);
if ((function(p->x,p->y,p->z)) > 0.0) pos.x = p->x; else neg.x = p->x;
}
}
@@ -1218,8 +1224,8 @@ void converge (MB_POINT *p1, MB_POINT *p2, float v1, float v2,
p->x = neg.x;
p->z = neg.z;
while (1) {
- p->y = 0.5f*(pos.y + neg.y);
if (i++ == RES) return;
+ p->y = 0.5f*(pos.y + neg.y);
if ((function(p->x,p->y,p->z)) > 0.0) pos.y = p->y; else neg.y = p->y;
}
}
@@ -1228,8 +1234,8 @@ void converge (MB_POINT *p1, MB_POINT *p2, float v1, float v2,
p->x = neg.x;
p->y = neg.y;
while (1) {
- p->z = 0.5f*(pos.z + neg.z);
if (i++ == RES) return;
+ p->z = 0.5f*(pos.z + neg.z);
if ((function(p->x,p->y,p->z)) > 0.0) pos.z = p->z; else neg.z = p->z;
}
}
@@ -1294,6 +1300,8 @@ void find_first_points(PROCESS *mbproc, MetaBall *mb, int a)
int index[3]={1,0,-1};
float f =0.0f;
float in_v, out_v;
+ MB_POINT workp;
+ float tmp_v, workp_v, max_len, len, dx, dy, dz, nx, ny, nz, MAXN;
ml = mainb[a];
@@ -1354,24 +1362,50 @@ void find_first_points(PROCESS *mbproc, MetaBall *mb, int a)
out_v = mbproc->function(out.x, out.y, out.z);
- /* find "first point" on Implicit Surface of MetaElemnt ml */
- converge(&in, &out, in_v, out_v, mbproc->function, &mbproc->start, mb, 0);
-
- /* indexes of CUBE, which includes "first point" */
- c_i= (int)floor(mbproc->start.x/mbproc->size );
- c_j= (int)floor(mbproc->start.y/mbproc->size );
- c_k= (int)floor(mbproc->start.z/mbproc->size );
-
- mbproc->start.x= mbproc->start.y= mbproc->start.z= 0.0;
-
- /* add CUBE (with indexes c_i, c_j, c_k) to the stack,
- * this cube includes found point of Implicit Surface */
- if (ml->flag & MB_NEGATIVE)
- add_cube(mbproc, c_i, c_j, c_k, 2);
- else
- add_cube(mbproc, c_i, c_j, c_k, 1);
-
+ /* find "first points" on Implicit Surface of MetaElemnt ml */
+ workp.x = in.x;
+ workp.y = in.y;
+ workp.z = in.z;
+ workp_v = in_v;
+ max_len = sqrt((out.x-in.x)*(out.x-in.x) + (out.y-in.y)*(out.y-in.y) + (out.z-in.z)*(out.z-in.z));
+
+ nx = abs((out.x - in.x)/mbproc->size);
+ ny = abs((out.y - in.y)/mbproc->size);
+ nz = abs((out.z - in.z)/mbproc->size);
+ MAXN = MAX3(nx,ny,nz);
+ if(MAXN!=0.0f) {
+ dx = (out.x - in.x)/MAXN;
+ dy = (out.y - in.y)/MAXN;
+ dz = (out.z - in.z)/MAXN;
+
+ len = 0.0;
+ while(len<=max_len) {
+ workp.x += dx;
+ workp.y += dy;
+ workp.z += dz;
+ /* compute value of implicite function */
+ tmp_v = mbproc->function(workp.x, workp.y, workp.z);
+ /* add cube to the stack, when value of implicite function crosses zero value */
+ if((tmp_v<0.0 && workp_v>=0.0)||(tmp_v>0.0 && workp_v<=0.0)) {
+
+ /* indexes of CUBE, which includes "first point" */
+ c_i= (int)floor(workp.x/mbproc->size);
+ c_j= (int)floor(workp.y/mbproc->size);
+ c_k= (int)floor(workp.z/mbproc->size);
+
+ /* add CUBE (with indexes c_i, c_j, c_k) to the stack,
+ * this cube includes found point of Implicit Surface */
+ if (ml->flag & MB_NEGATIVE)
+ add_cube(mbproc, c_i, c_j, c_k, 2);
+ else
+ add_cube(mbproc, c_i, c_j, c_k, 1);
+ }
+ len = sqrt((workp.x-in.x)*(workp.x-in.x) + (workp.y-in.y)*(workp.y-in.y) + (workp.z-in.z)*(workp.z-in.z));
+ workp_v = tmp_v;
+
+ }
+ }
}
}
}
@@ -1677,15 +1711,13 @@ void fill_metaball_octal_node(octal_node *node, MetaElem *ml, short i)
* +------+------+
*
*/
-void subdivide_metaball_octal_node(octal_node *node, float *size, short depth)
+void subdivide_metaball_octal_node(octal_node *node, float size_x, float size_y, float size_z, short depth)
{
MetaElem *ml;
ml_pointer *ml_p;
float x,y,z;
int a,i;
- if(depth==0) return;
-
/* create new nodes */
for(a=0;a<8;a++){
node->nodes[a]= MEM_mallocN(sizeof(octal_node),"octal_node");
@@ -1699,45 +1731,71 @@ void subdivide_metaball_octal_node(octal_node *node, float *size, short depth)
node->nodes[a]->pos= 0;
}
- size[0]/=2; size[1]/=2; size[2]/=2;
+ size_x /= 2;
+ size_y /= 2;
+ size_z /= 2;
/* center of node */
- node->x= x= node->x_min + size[0];
- node->y= y= node->y_min + size[1];
- node->z= z= node->z_min + size[2];
+ node->x = x = node->x_min + size_x;
+ node->y = y = node->y_min + size_y;
+ node->z = z = node->z_min + size_z;
/* setting up of border points of new nodes */
- node->nodes[0]->x_min= node->x_min;
- node->nodes[0]->y_min= node->y_min;
- node->nodes[0]->z_min= node->z_min;
-
- node->nodes[1]->x_min= x;
- node->nodes[1]->y_min= node->y_min;
- node->nodes[1]->z_min= node->z_min;
-
- node->nodes[2]->x_min= x;
- node->nodes[2]->y_min= y;
- node->nodes[2]->z_min= node->z_min;
-
- node->nodes[3]->x_min= node->x_min;
- node->nodes[3]->y_min= y;
- node->nodes[3]->z_min= node->z_min;
-
- node->nodes[4]->x_min= node->x_min;
- node->nodes[4]->y_min= node->y_min;
- node->nodes[4]->z_min= z;
-
- node->nodes[5]->x_min= x;
- node->nodes[5]->y_min= node->y_min;
- node->nodes[5]->z_min= z;
-
- node->nodes[6]->x_min= x;
- node->nodes[6]->y_min= y;
- node->nodes[6]->z_min= z;
-
- node->nodes[7]->x_min= node->x_min;
- node->nodes[7]->y_min= y;
- node->nodes[7]->z_min= z;
+ node->nodes[0]->x_min = node->x_min;
+ node->nodes[0]->y_min = node->y_min;
+ node->nodes[0]->z_min = node->z_min;
+ node->nodes[0]->x = node->nodes[0]->x_min + size_x/2;
+ node->nodes[0]->y = node->nodes[0]->y_min + size_y/2;
+ node->nodes[0]->z = node->nodes[0]->z_min + size_z/2;
+
+ node->nodes[1]->x_min = x;
+ node->nodes[1]->y_min = node->y_min;
+ node->nodes[1]->z_min = node->z_min;
+ node->nodes[1]->x = node->nodes[1]->x_min + size_x/2;
+ node->nodes[1]->y = node->nodes[1]->y_min + size_y/2;
+ node->nodes[1]->z = node->nodes[1]->z_min + size_z/2;
+
+ node->nodes[2]->x_min = x;
+ node->nodes[2]->y_min = y;
+ node->nodes[2]->z_min = node->z_min;
+ node->nodes[2]->x = node->nodes[2]->x_min + size_x/2;
+ node->nodes[2]->y = node->nodes[2]->y_min + size_y/2;
+ node->nodes[2]->z = node->nodes[2]->z_min + size_z/2;
+
+ node->nodes[3]->x_min = node->x_min;
+ node->nodes[3]->y_min = y;
+ node->nodes[3]->z_min = node->z_min;
+ node->nodes[3]->x = node->nodes[3]->x_min + size_x/2;
+ node->nodes[3]->y = node->nodes[3]->y_min + size_y/2;
+ node->nodes[3]->z = node->nodes[3]->z_min + size_z/2;
+
+ node->nodes[4]->x_min = node->x_min;
+ node->nodes[4]->y_min = node->y_min;
+ node->nodes[4]->z_min = z;
+ node->nodes[4]->x = node->nodes[4]->x_min + size_x/2;
+ node->nodes[4]->y = node->nodes[4]->y_min + size_y/2;
+ node->nodes[4]->z = node->nodes[4]->z_min + size_z/2;
+
+ node->nodes[5]->x_min = x;
+ node->nodes[5]->y_min = node->y_min;
+ node->nodes[5]->z_min = z;
+ node->nodes[5]->x = node->nodes[5]->x_min + size_x/2;
+ node->nodes[5]->y = node->nodes[5]->y_min + size_y/2;
+ node->nodes[5]->z = node->nodes[5]->z_min + size_z/2;
+
+ node->nodes[6]->x_min = x;
+ node->nodes[6]->y_min = y;
+ node->nodes[6]->z_min = z;
+ node->nodes[6]->x = node->nodes[6]->x_min + size_x/2;
+ node->nodes[6]->y = node->nodes[6]->y_min + size_y/2;
+ node->nodes[6]->z = node->nodes[6]->z_min + size_z/2;
+
+ node->nodes[7]->x_min = node->x_min;
+ node->nodes[7]->y_min = y;
+ node->nodes[7]->z_min = z;
+ node->nodes[7]->x = node->nodes[7]->x_min + size_x/2;
+ node->nodes[7]->y = node->nodes[7]->y_min + size_y/2;
+ node->nodes[7]->z = node->nodes[7]->z_min + size_z/2;
ml_p= node->elems.first;
@@ -1904,7 +1962,7 @@ void subdivide_metaball_octal_node(octal_node *node, float *size, short depth)
if(depth>0){
for(a=0;a<8;a++){
if(node->nodes[a]->count > 0) /* if node is not empty, then it is subdivided */
- subdivide_metaball_octal_node(node->nodes[a], size, depth);
+ subdivide_metaball_octal_node(node->nodes[a], size_x, size_y, size_z, depth);
}
}
}
@@ -1976,7 +2034,7 @@ void init_metaball_octal_tree(int depth)
size[2]= node->z_max - node->z_min;
/* first node is subdivided recursively */
- subdivide_metaball_octal_node(node, size, metaball_tree->depth);
+ subdivide_metaball_octal_node(node, size[0], size[1], size[2], metaball_tree->depth);
}
void metaball_polygonize(Object *ob)
diff --git a/source/blender/blenkernel/intern/mesh.c b/source/blender/blenkernel/intern/mesh.c
index 1632f57c66e..07a1a5c5f44 100644
--- a/source/blender/blenkernel/intern/mesh.c
+++ b/source/blender/blenkernel/intern/mesh.c
@@ -78,45 +78,6 @@
#include "BLI_editVert.h"
#include "BLI_arithb.h"
-int update_realtime_texture(MTFace *tface, double time)
-{
- Image *ima;
- int inc = 0;
- float diff;
- int newframe;
-
- ima = tface->tpage;
-
- if (!ima)
- return 0;
-
- if (ima->lastupdate<0)
- ima->lastupdate = 0;
-
- if (ima->lastupdate>time)
- ima->lastupdate=(float)time;
-
- if(ima->tpageflag & IMA_TWINANIM) {
- if(ima->twend >= ima->xrep*ima->yrep) ima->twend= ima->xrep*ima->yrep-1;
-
- /* check: is the bindcode not in the array? Then free. (still to do) */
-
- diff = (float)(time-ima->lastupdate);
-
- inc = (int)(diff*(float)ima->animspeed);
-
- ima->lastupdate+=((float)inc/(float)ima->animspeed);
-
- newframe = ima->lastframe+inc;
-
- if (newframe > (int)ima->twend)
- newframe = (int)ima->twsta-1 + (newframe-ima->twend)%(ima->twend-ima->twsta);
-
- ima->lastframe = newframe;
- }
- return inc;
-}
-
void mesh_update_customdata_pointers(Mesh *me)
{
me->mvert = CustomData_get_layer(&me->vdata, CD_MVERT);
@@ -526,7 +487,7 @@ void transform_mesh_orco_verts(Mesh *me, float (*orco)[3], int totvert, int inve
/* rotates the vertices of a face in case v[2] or v[3] (vertex index) is = 0.
this is necessary to make the if(mface->v4) check for quads work */
-void test_index_face(MFace *mface, CustomData *fdata, int mfindex, int nr)
+int test_index_face(MFace *mface, CustomData *fdata, int mfindex, int nr)
{
/* first test if the face is legal */
if(mface->v3 && mface->v3==mface->v4) {
@@ -568,6 +529,8 @@ void test_index_face(MFace *mface, CustomData *fdata, int mfindex, int nr)
CustomData_swap(fdata, mfindex, corner_indices);
}
}
+
+ return nr;
}
Mesh *get_mesh(Object *ob)
@@ -764,8 +727,7 @@ void mball_to_mesh(ListBase *lb, Mesh *me)
mface->v4= index[3];
mface->flag= ME_SMOOTH;
- if(mface->v3==mface->v4)
- mface->v4= 0;
+ test_index_face(mface, NULL, 0, (mface->v3==mface->v4)? 3: 4);
mface++;
index+= 4;
@@ -1104,9 +1066,13 @@ float (*mesh_getRefKeyCos(Mesh *me, int *numVerts_r))[3]
if(me->key && me->key->refkey) {
if(numVerts_r) *numVerts_r= me->totvert;
- cos= MEM_mallocN(sizeof(*cos)*me->totvert, "vertexcos1");
-
+
kb= me->key->refkey;
+
+ /* prevent accessing invalid memory */
+ if (me->totvert > kb->totelem) cos= MEM_callocN(sizeof(*cos)*me->totvert, "vertexcos1");
+ else cos= MEM_mallocN(sizeof(*cos)*me->totvert, "vertexcos1");
+
totvert= MIN2(kb->totelem, me->totvert);
memcpy(cos, kb->data, sizeof(*cos)*totvert);
@@ -1136,12 +1102,12 @@ UvVertMap *make_uv_vert_map(struct MFace *mface, struct MTFace *tface, unsigned
if(totuv==0)
return NULL;
- vmap= (UvVertMap*)MEM_mallocN(sizeof(*vmap), "UvVertMap");
+ vmap= (UvVertMap*)MEM_callocN(sizeof(*vmap), "UvVertMap");
if (!vmap)
return NULL;
vmap->vert= (UvMapVert**)MEM_callocN(sizeof(*vmap->vert)*totvert, "UvMapVert*");
- buf= vmap->buf= (UvMapVert*)MEM_mallocN(sizeof(*vmap->buf)*totuv, "UvMapVert");
+ buf= vmap->buf= (UvMapVert*)MEM_callocN(sizeof(*vmap->buf)*totuv, "UvMapVert");
if (!vmap->vert || !vmap->buf) {
free_uv_vert_map(vmap);
diff --git a/source/blender/blenkernel/intern/modifier.c b/source/blender/blenkernel/intern/modifier.c
index 9b9e94774bc..eebd5e6d056 100644
--- a/source/blender/blenkernel/intern/modifier.c
+++ b/source/blender/blenkernel/intern/modifier.c
@@ -40,9 +40,11 @@
#include "stdarg.h"
#include "math.h"
#include "float.h"
+#include "ctype.h"
#include "BLI_arithb.h"
#include "BLI_blenlib.h"
+#include "BLI_kdopbvh.h"
#include "BLI_kdtree.h"
#include "BLI_linklist.h"
#include "BLI_rand.h"
@@ -52,7 +54,11 @@
#include "MEM_guardedalloc.h"
+#include "DNA_action_types.h"
#include "DNA_armature_types.h"
+#include "DNA_camera_types.h"
+#include "DNA_cloth_types.h"
+#include "DNA_curve_types.h"
#include "DNA_effect_types.h"
#include "DNA_material_types.h"
#include "DNA_mesh_types.h"
@@ -63,8 +69,6 @@
#include "DNA_particle_types.h"
#include "DNA_scene_types.h"
#include "DNA_texture_types.h"
-#include "DNA_curve_types.h"
-#include "DNA_camera_types.h"
#include "BLI_editVert.h"
@@ -73,25 +77,34 @@
#include "BKE_main.h"
#include "BKE_anim.h"
+#include "BKE_bmesh.h"
+#include "BKE_booleanops.h"
+#include "BKE_cloth.h"
+#include "BKE_collision.h"
+#include "BKE_cdderivedmesh.h"
#include "BKE_curve.h"
#include "BKE_customdata.h"
-#include "BKE_global.h"
-#include "BKE_cdderivedmesh.h"
#include "BKE_DerivedMesh.h"
-#include "BKE_booleanops.h"
#include "BKE_displist.h"
-#include "BKE_modifier.h"
+#include "BKE_fluidsim.h"
+#include "BKE_global.h"
#include "BKE_lattice.h"
#include "BKE_library.h"
-#include "BKE_subsurf.h"
-#include "BKE_object.h"
-#include "BKE_mesh.h"
-#include "BKE_softbody.h"
#include "BKE_material.h"
+#include "BKE_mesh.h"
+#include "BKE_modifier.h"
+#include "BKE_object.h"
#include "BKE_particle.h"
#include "BKE_pointcache.h"
+#include "BKE_softbody.h"
+#include "BKE_subsurf.h"
+#include "BKE_texture.h"
#include "BKE_utildefines.h"
+
#include "depsgraph_private.h"
+#include "BKE_deform.h"
+#include "BKE_shrinkwrap.h"
+#include "BKE_simple_deform.h"
//XXX #include "LOD_DependKludge.h"
#include "LOD_decimation.h"
@@ -147,9 +160,9 @@ static int curveModifier_isDisabled(ModifierData *md)
}
static void curveModifier_foreachObjectLink(
- ModifierData *md, Object *ob,
- void (*walk)(void *userData, Object *ob, Object **obpoin),
- void *userData)
+ ModifierData *md, Object *ob,
+ void (*walk)(void *userData, Object *ob, Object **obpoin),
+ void *userData)
{
CurveModifierData *cmd = (CurveModifierData*) md;
@@ -157,8 +170,8 @@ static void curveModifier_foreachObjectLink(
}
static void curveModifier_updateDepgraph(
- ModifierData *md, DagForest *forest,
- Object *ob, DagNode *obNode)
+ ModifierData *md, DagForest *forest,
+ Object *ob, DagNode *obNode)
{
CurveModifierData *cmd = (CurveModifierData*) md;
@@ -166,23 +179,23 @@ static void curveModifier_updateDepgraph(
DagNode *curNode = dag_get_node(forest, cmd->object);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Curve Modifier");
}
}
static void curveModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
CurveModifierData *cmd = (CurveModifierData*) md;
curve_deform_verts(cmd->object, ob, derivedData, vertexCos, numVerts,
- cmd->name, cmd->defaxis);
+ cmd->name, cmd->defaxis);
}
static void curveModifier_deformVertsEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm = derivedData;
@@ -223,9 +236,9 @@ static int latticeModifier_isDisabled(ModifierData *md)
}
static void latticeModifier_foreachObjectLink(
- ModifierData *md, Object *ob,
- void (*walk)(void *userData, Object *ob, Object **obpoin),
- void *userData)
+ ModifierData *md, Object *ob,
+ void (*walk)(void *userData, Object *ob, Object **obpoin),
+ void *userData)
{
LatticeModifierData *lmd = (LatticeModifierData*) md;
@@ -233,7 +246,7 @@ static void latticeModifier_foreachObjectLink(
}
static void latticeModifier_updateDepgraph(ModifierData *md, DagForest *forest,
- Object *ob, DagNode *obNode)
+ Object *ob, DagNode *obNode)
{
LatticeModifierData *lmd = (LatticeModifierData*) md;
@@ -241,7 +254,7 @@ static void latticeModifier_updateDepgraph(ModifierData *md, DagForest *forest,
DagNode *latNode = dag_get_node(forest, lmd->object);
dag_add_relation(forest, latNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Lattice Modifier");
}
}
@@ -260,8 +273,8 @@ static void modifier_vgroup_cache(ModifierData *md, float (*vertexCos)[3])
static void latticeModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
LatticeModifierData *lmd = (LatticeModifierData*) md;
@@ -269,12 +282,12 @@ static void latticeModifier_deformVerts(
modifier_vgroup_cache(md, vertexCos); /* if next modifier needs original vertices */
lattice_deform_verts(lmd->object, ob, derivedData,
- vertexCos, numVerts, lmd->name);
+ vertexCos, numVerts, lmd->name);
}
static void latticeModifier_deformVertsEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm = derivedData;
@@ -320,28 +333,28 @@ static void subsurfModifier_freeData(ModifierData *md)
}
static DerivedMesh *subsurfModifier_applyModifier(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- int useRenderParams, int isFinalCalc)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
{
SubsurfModifierData *smd = (SubsurfModifierData*) md;
DerivedMesh *result;
result = subsurf_make_derived_from_derived(derivedData, smd,
- useRenderParams, NULL,
- isFinalCalc, 0);
+ useRenderParams, NULL,
+ isFinalCalc, 0);
return result;
}
static DerivedMesh *subsurfModifier_applyModifierEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData)
{
SubsurfModifierData *smd = (SubsurfModifierData*) md;
DerivedMesh *result;
result = subsurf_make_derived_from_derived(derivedData, smd, 0,
- NULL, 0, 1);
+ NULL, 0, 1);
return result;
}
@@ -373,8 +386,8 @@ static int buildModifier_dependsOnTime(ModifierData *md)
}
static DerivedMesh *buildModifier_applyModifier(ModifierData *md, Object *ob,
- DerivedMesh *derivedData,
- int useRenderParams, int isFinalCalc)
+ DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
{
DerivedMesh *dm = derivedData;
DerivedMesh *result;
@@ -387,29 +400,29 @@ static DerivedMesh *buildModifier_applyModifier(ModifierData *md, Object *ob,
GHashIterator *hashIter;
/* maps vert indices in old mesh to indices in new mesh */
GHash *vertHash = BLI_ghash_new(BLI_ghashutil_inthash,
- BLI_ghashutil_intcmp);
+ BLI_ghashutil_intcmp);
/* maps edge indices in new mesh to indices in old mesh */
GHash *edgeHash = BLI_ghash_new(BLI_ghashutil_inthash,
- BLI_ghashutil_intcmp);
+ BLI_ghashutil_intcmp);
maxVerts = dm->getNumVerts(dm);
vertMap = MEM_callocN(sizeof(*vertMap) * maxVerts,
- "build modifier vertMap");
+ "build modifier vertMap");
for(i = 0; i < maxVerts; ++i) vertMap[i] = i;
maxEdges = dm->getNumEdges(dm);
edgeMap = MEM_callocN(sizeof(*edgeMap) * maxEdges,
- "build modifier edgeMap");
+ "build modifier edgeMap");
for(i = 0; i < maxEdges; ++i) edgeMap[i] = i;
maxFaces = dm->getNumFaces(dm);
faceMap = MEM_callocN(sizeof(*faceMap) * maxFaces,
- "build modifier faceMap");
+ "build modifier faceMap");
for(i = 0; i < maxFaces; ++i) faceMap[i] = i;
if (ob) {
frac = bsystem_time(ob, (float)G.scene->r.cfra,
- bmd->start - 1.0f) / bmd->length;
+ bmd->start - 1.0f) / bmd->length;
} else {
frac = G.scene->r.cfra - bmd->start / bmd->length;
}
@@ -424,156 +437,511 @@ static DerivedMesh *buildModifier_applyModifier(ModifierData *md, Object *ob,
if(bmd->randomize)
BLI_array_randomize(faceMap, sizeof(*faceMap),
- maxFaces, bmd->seed);
+ maxFaces, bmd->seed);
/* get the set of all vert indices that will be in the final mesh,
- * mapped to the new indices
- */
+ * mapped to the new indices
+ */
for(i = 0; i < numFaces; ++i) {
MFace mf;
dm->getFace(dm, faceMap[i], &mf);
- if(!BLI_ghash_haskey(vertHash, (void *)mf.v1))
- BLI_ghash_insert(vertHash, (void *)mf.v1,
- (void *)BLI_ghash_size(vertHash));
- if(!BLI_ghash_haskey(vertHash, (void *)mf.v2))
- BLI_ghash_insert(vertHash, (void *)mf.v2,
- (void *)BLI_ghash_size(vertHash));
- if(!BLI_ghash_haskey(vertHash, (void *)mf.v3))
- BLI_ghash_insert(vertHash, (void *)mf.v3,
- (void *)BLI_ghash_size(vertHash));
- if(mf.v4 && !BLI_ghash_haskey(vertHash, (void *)mf.v4))
- BLI_ghash_insert(vertHash, (void *)mf.v4,
- (void *)BLI_ghash_size(vertHash));
+ if(!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v1)))
+ BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(mf.v1),
+ SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
+ if(!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v2)))
+ BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(mf.v2),
+ SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
+ if(!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v3)))
+ BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(mf.v3),
+ SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
+ if(mf.v4 && !BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v4)))
+ BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(mf.v4),
+ SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
}
/* get the set of edges that will be in the new mesh (i.e. all edges
- * that have both verts in the new mesh)
- */
+ * that have both verts in the new mesh)
+ */
maxEdges = dm->getNumEdges(dm);
for(i = 0; i < maxEdges; ++i) {
MEdge me;
dm->getEdge(dm, i, &me);
- if(BLI_ghash_haskey(vertHash, (void *)me.v1)
- && BLI_ghash_haskey(vertHash, (void *)me.v2))
+ if(BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v1))
+ && BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v2)))
BLI_ghash_insert(edgeHash,
- (void *)BLI_ghash_size(edgeHash), (void *)i);
+ SET_INT_IN_POINTER(BLI_ghash_size(edgeHash)), SET_INT_IN_POINTER(i));
}
} else if(numEdges) {
if(bmd->randomize)
BLI_array_randomize(edgeMap, sizeof(*edgeMap),
- maxEdges, bmd->seed);
+ maxEdges, bmd->seed);
/* get the set of all vert indices that will be in the final mesh,
- * mapped to the new indices
- */
+ * mapped to the new indices
+ */
for(i = 0; i < numEdges; ++i) {
MEdge me;
dm->getEdge(dm, edgeMap[i], &me);
- if(!BLI_ghash_haskey(vertHash, (void *)me.v1))
- BLI_ghash_insert(vertHash, (void *)me.v1,
- (void *)BLI_ghash_size(vertHash));
- if(!BLI_ghash_haskey(vertHash, (void *)me.v2))
- BLI_ghash_insert(vertHash, (void *)me.v2,
- (void *)BLI_ghash_size(vertHash));
+ if(!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v1)))
+ BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(me.v1),
+ SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
+ if(!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v2)))
+ BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(me.v2),
+ SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
}
/* get the set of edges that will be in the new mesh
- */
+ */
for(i = 0; i < numEdges; ++i) {
MEdge me;
dm->getEdge(dm, edgeMap[i], &me);
- BLI_ghash_insert(edgeHash, (void *)BLI_ghash_size(edgeHash),
- (void *)edgeMap[i]);
+ BLI_ghash_insert(edgeHash, SET_INT_IN_POINTER(BLI_ghash_size(edgeHash)),
+ SET_INT_IN_POINTER(edgeMap[i]));
}
} else {
int numVerts = dm->getNumVerts(dm) * frac;
if(bmd->randomize)
BLI_array_randomize(vertMap, sizeof(*vertMap),
- maxVerts, bmd->seed);
+ maxVerts, bmd->seed);
/* get the set of all vert indices that will be in the final mesh,
- * mapped to the new indices
- */
+ * mapped to the new indices
+ */
for(i = 0; i < numVerts; ++i)
- BLI_ghash_insert(vertHash, (void *)vertMap[i], (void *)i);
+ BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(vertMap[i]), SET_INT_IN_POINTER(i));
}
/* now we know the number of verts, edges and faces, we can create
- * the mesh
- */
+ * the mesh
+ */
result = CDDM_from_template(dm, BLI_ghash_size(vertHash),
- BLI_ghash_size(edgeHash), numFaces);
+ BLI_ghash_size(edgeHash), numFaces);
/* copy the vertices across */
for(hashIter = BLI_ghashIterator_new(vertHash);
- !BLI_ghashIterator_isDone(hashIter);
- BLI_ghashIterator_step(hashIter)) {
+ !BLI_ghashIterator_isDone(hashIter);
+ BLI_ghashIterator_step(hashIter)) {
+ MVert source;
+ MVert *dest;
+ int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
+ int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
+
+ dm->getVert(dm, oldIndex, &source);
+ dest = CDDM_get_vert(result, newIndex);
+
+ DM_copy_vert_data(dm, result, oldIndex, newIndex, 1);
+ *dest = source;
+ }
+ BLI_ghashIterator_free(hashIter);
+
+ /* copy the edges across, remapping indices */
+ for(i = 0; i < BLI_ghash_size(edgeHash); ++i) {
+ MEdge source;
+ MEdge *dest;
+ int oldIndex = GET_INT_FROM_POINTER(BLI_ghash_lookup(edgeHash, SET_INT_IN_POINTER(i)));
+
+ dm->getEdge(dm, oldIndex, &source);
+ dest = CDDM_get_edge(result, i);
+
+ source.v1 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v1)));
+ source.v2 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v2)));
+
+ DM_copy_edge_data(dm, result, oldIndex, i, 1);
+ *dest = source;
+ }
+
+ /* copy the faces across, remapping indices */
+ for(i = 0; i < numFaces; ++i) {
+ MFace source;
+ MFace *dest;
+ int orig_v4;
+
+ dm->getFace(dm, faceMap[i], &source);
+ dest = CDDM_get_face(result, i);
+
+ orig_v4 = source.v4;
+
+ source.v1 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v1)));
+ source.v2 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v2)));
+ source.v3 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v3)));
+ if(source.v4)
+ source.v4 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v4)));
+
+ DM_copy_face_data(dm, result, faceMap[i], i, 1);
+ *dest = source;
+
+ test_index_face(dest, &result->faceData, i, (orig_v4 ? 4 : 3));
+ }
+
+ CDDM_calc_normals(result);
+
+ BLI_ghash_free(vertHash, NULL, NULL);
+ BLI_ghash_free(edgeHash, NULL, NULL);
+
+ MEM_freeN(vertMap);
+ MEM_freeN(edgeMap);
+ MEM_freeN(faceMap);
+
+ return result;
+}
+
+/* Mask */
+
+static void maskModifier_copyData(ModifierData *md, ModifierData *target)
+{
+ MaskModifierData *mmd = (MaskModifierData*) md;
+ MaskModifierData *tmmd = (MaskModifierData*) target;
+
+ strcpy(tmmd->vgroup, mmd->vgroup);
+}
+
+static CustomDataMask maskModifier_requiredDataMask(ModifierData *md)
+{
+ return (1 << CD_MDEFORMVERT);
+}
+
+static void maskModifier_foreachObjectLink(
+ ModifierData *md, Object *ob,
+ void (*walk)(void *userData, Object *ob, Object **obpoin),
+ void *userData)
+{
+ MaskModifierData *mmd = (MaskModifierData *)md;
+ walk(userData, ob, &mmd->ob_arm);
+}
+
+static void maskModifier_updateDepgraph(ModifierData *md, DagForest *forest,
+ Object *ob, DagNode *obNode)
+{
+ MaskModifierData *mmd = (MaskModifierData *)md;
+
+ if (mmd->ob_arm)
+ {
+ DagNode *armNode = dag_get_node(forest, mmd->ob_arm);
+
+ dag_add_relation(forest, armNode, obNode,
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Mask Modifier");
+ }
+}
+
+static DerivedMesh *maskModifier_applyModifier(ModifierData *md, Object *ob,
+ DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
+{
+ MaskModifierData *mmd= (MaskModifierData *)md;
+ DerivedMesh *dm= derivedData, *result= NULL;
+ GHash *vertHash=NULL, *edgeHash, *faceHash;
+ GHashIterator *hashIter;
+ MDeformVert *dvert= NULL;
+ int numFaces=0, numEdges=0, numVerts=0;
+ int maxVerts, maxEdges, maxFaces;
+ int i;
+
+ /* Overview of Method:
+ * 1. Get the vertices that are in the vertexgroup of interest
+ * 2. Filter out unwanted geometry (i.e. not in vertexgroup), by populating mappings with new vs old indices
+ * 3. Make a new mesh containing only the mapping data
+ */
+
+ /* get original number of verts, edges, and faces */
+ maxVerts= dm->getNumVerts(dm);
+ maxEdges= dm->getNumEdges(dm);
+ maxFaces= dm->getNumFaces(dm);
+
+ /* check if we can just return the original mesh
+ * - must have verts and therefore verts assigned to vgroups to do anything useful
+ */
+ if ( !(ELEM(mmd->mode, MOD_MASK_MODE_ARM, MOD_MASK_MODE_VGROUP)) ||
+ (maxVerts == 0) || (ob->defbase.first == NULL) )
+ {
+ return derivedData;
+ }
+
+ /* if mode is to use selected armature bones, aggregate the bone groups */
+ if (mmd->mode == MOD_MASK_MODE_ARM) /* --- using selected bones --- */
+ {
+ GHash *vgroupHash, *boneHash;
+ Object *oba= mmd->ob_arm;
+ bPoseChannel *pchan;
+ bDeformGroup *def;
+
+ /* check that there is armature object with bones to use, otherwise return original mesh */
+ if (ELEM(NULL, mmd->ob_arm, mmd->ob_arm->pose))
+ return derivedData;
+
+ /* hashes for finding mapping of:
+ * - vgroups to indicies -> vgroupHash (string, int)
+ * - bones to vgroup indices -> boneHash (index of vgroup, dummy)
+ */
+ vgroupHash= BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp);
+ boneHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp);
+
+ /* build mapping of names of vertex groups to indices */
+ for (i = 0, def = ob->defbase.first; def; def = def->next, i++)
+ BLI_ghash_insert(vgroupHash, def->name, SET_INT_IN_POINTER(i));
+
+ /* get selected-posechannel <-> vertexgroup index mapping */
+ for (pchan= oba->pose->chanbase.first; pchan; pchan= pchan->next)
+ {
+ /* check if bone is selected */
+ // TODO: include checks for visibility too?
+ // FIXME: the depsgraph needs extensions to make this work in realtime...
+ if ( (pchan->bone) && (pchan->bone->flag & BONE_SELECTED) )
+ {
+ /* check if hash has group for this bone */
+ if (BLI_ghash_haskey(vgroupHash, pchan->name))
+ {
+ int defgrp_index= GET_INT_FROM_POINTER(BLI_ghash_lookup(vgroupHash, pchan->name));
+
+ /* add index to hash (store under key only) */
+ BLI_ghash_insert(boneHash, SET_INT_IN_POINTER(defgrp_index), pchan);
+ }
+ }
+ }
+
+ /* if no bones selected, free hashes and return original mesh */
+ if (BLI_ghash_size(boneHash) == 0)
+ {
+ BLI_ghash_free(vgroupHash, NULL, NULL);
+ BLI_ghash_free(boneHash, NULL, NULL);
+
+ return derivedData;
+ }
+
+ /* repeat the previous check, but for dverts */
+ dvert= dm->getVertDataArray(dm, CD_MDEFORMVERT);
+ if (dvert == NULL)
+ {
+ BLI_ghash_free(vgroupHash, NULL, NULL);
+ BLI_ghash_free(boneHash, NULL, NULL);
+
+ return derivedData;
+ }
+
+ /* hashes for quickly providing a mapping from old to new - use key=oldindex, value=newindex */
+ vertHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp);
+
+ /* add vertices which exist in vertexgroups into vertHash for filtering */
+ for (i = 0; i < maxVerts; i++)
+ {
+ MDeformWeight *def_weight = NULL;
+ int j;
+
+ for (j= 0; j < dvert[i].totweight; j++)
+ {
+ if (BLI_ghash_haskey(boneHash, SET_INT_IN_POINTER(dvert[i].dw[j].def_nr)))
+ {
+ def_weight = &dvert[i].dw[j];
+ break;
+ }
+ }
+
+ /* check if include vert in vertHash */
+ if (mmd->flag & MOD_MASK_INV) {
+ /* if this vert is in the vgroup, don't include it in vertHash */
+ if (def_weight) continue;
+ }
+ else {
+ /* if this vert isn't in the vgroup, don't include it in vertHash */
+ if (!def_weight) continue;
+ }
+
+ /* add to ghash for verts (numVerts acts as counter for mapping) */
+ BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numVerts));
+ numVerts++;
+ }
+
+ /* free temp hashes */
+ BLI_ghash_free(vgroupHash, NULL, NULL);
+ BLI_ghash_free(boneHash, NULL, NULL);
+ }
+ else /* --- Using Nominated VertexGroup only --- */
+ {
+ int defgrp_index = -1;
+
+ /* get index of vertex group */
+ if (mmd->vgroup[0])
+ {
+ bDeformGroup *def;
+
+ /* find index by comparing names - SLOW... */
+ for (i = 0, def = ob->defbase.first; def; def = def->next, i++)
+ {
+ if (!strcmp(def->name, mmd->vgroup))
+ {
+ defgrp_index = i;
+ break;
+ }
+ }
+ }
+
+ /* get dverts */
+ if (defgrp_index >= 0)
+ dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
+
+ /* if no vgroup (i.e. dverts) found, return the initial mesh */
+ if ((defgrp_index < 0) || (dvert == NULL))
+ return dm;
+
+ /* hashes for quickly providing a mapping from old to new - use key=oldindex, value=newindex */
+ vertHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp);
+
+ /* add vertices which exist in vertexgroup into ghash for filtering */
+ for (i = 0; i < maxVerts; i++)
+ {
+ MDeformWeight *def_weight = NULL;
+ int j;
+
+ for (j= 0; j < dvert[i].totweight; j++)
+ {
+ if (dvert[i].dw[j].def_nr == defgrp_index)
+ {
+ def_weight = &dvert[i].dw[j];
+ break;
+ }
+ }
+
+ /* check if include vert in vertHash */
+ if (mmd->flag & MOD_MASK_INV) {
+ /* if this vert is in the vgroup, don't include it in vertHash */
+ if (def_weight) continue;
+ }
+ else {
+ /* if this vert isn't in the vgroup, don't include it in vertHash */
+ if (!def_weight) continue;
+ }
+
+ /* add to ghash for verts (numVerts acts as counter for mapping) */
+ BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numVerts));
+ numVerts++;
+ }
+ }
+
+ /* hashes for quickly providing a mapping from old to new - use key=oldindex, value=newindex */
+ edgeHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp);
+ faceHash= BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp);
+
+ /* loop over edges and faces, and do the same thing to
+ * ensure that they only reference existing verts
+ */
+ for (i = 0; i < maxEdges; i++)
+ {
+ MEdge me;
+ dm->getEdge(dm, i, &me);
+
+ /* only add if both verts will be in new mesh */
+ if ( BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v1)) &&
+ BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v2)) )
+ {
+ BLI_ghash_insert(edgeHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numEdges));
+ numEdges++;
+ }
+ }
+ for (i = 0; i < maxFaces; i++)
+ {
+ MFace mf;
+ dm->getFace(dm, i, &mf);
+
+ /* all verts must be available */
+ if ( BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v1)) &&
+ BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v2)) &&
+ BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v3)) &&
+ (mf.v4==0 || BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v4))) )
+ {
+ BLI_ghash_insert(faceHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numFaces));
+ numFaces++;
+ }
+ }
+
+
+ /* now we know the number of verts, edges and faces,
+ * we can create the new (reduced) mesh
+ */
+ result = CDDM_from_template(dm, numVerts, numEdges, numFaces);
+
+
+ /* using ghash-iterators, map data into new mesh */
+ /* vertices */
+ for ( hashIter = BLI_ghashIterator_new(vertHash);
+ !BLI_ghashIterator_isDone(hashIter);
+ BLI_ghashIterator_step(hashIter) )
+ {
MVert source;
MVert *dest;
- int oldIndex = (int)BLI_ghashIterator_getKey(hashIter);
- int newIndex = (int)BLI_ghashIterator_getValue(hashIter);
-
+ int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
+ int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
+
dm->getVert(dm, oldIndex, &source);
dest = CDDM_get_vert(result, newIndex);
-
+
DM_copy_vert_data(dm, result, oldIndex, newIndex, 1);
*dest = source;
}
BLI_ghashIterator_free(hashIter);
-
- /* copy the edges across, remapping indices */
- for(i = 0; i < BLI_ghash_size(edgeHash); ++i) {
+
+ /* edges */
+ for ( hashIter = BLI_ghashIterator_new(edgeHash);
+ !BLI_ghashIterator_isDone(hashIter);
+ BLI_ghashIterator_step(hashIter) )
+ {
MEdge source;
MEdge *dest;
- int oldIndex = (int)BLI_ghash_lookup(edgeHash, (void *)i);
-
+ int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
+ int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
+
dm->getEdge(dm, oldIndex, &source);
- dest = CDDM_get_edge(result, i);
-
- source.v1 = (int)BLI_ghash_lookup(vertHash, (void *)source.v1);
- source.v2 = (int)BLI_ghash_lookup(vertHash, (void *)source.v2);
-
- DM_copy_edge_data(dm, result, oldIndex, i, 1);
+ dest = CDDM_get_edge(result, newIndex);
+
+ source.v1 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v1)));
+ source.v2 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v2)));
+
+ DM_copy_edge_data(dm, result, oldIndex, newIndex, 1);
*dest = source;
}
-
- /* copy the faces across, remapping indices */
- for(i = 0; i < numFaces; ++i) {
+ BLI_ghashIterator_free(hashIter);
+
+ /* faces */
+ for ( hashIter = BLI_ghashIterator_new(faceHash);
+ !BLI_ghashIterator_isDone(hashIter);
+ BLI_ghashIterator_step(hashIter) )
+ {
MFace source;
MFace *dest;
+ int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
+ int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
int orig_v4;
-
- dm->getFace(dm, faceMap[i], &source);
- dest = CDDM_get_face(result, i);
-
+
+ dm->getFace(dm, oldIndex, &source);
+ dest = CDDM_get_face(result, newIndex);
+
orig_v4 = source.v4;
-
- source.v1 = (int)BLI_ghash_lookup(vertHash, (void *)source.v1);
- source.v2 = (int)BLI_ghash_lookup(vertHash, (void *)source.v2);
- source.v3 = (int)BLI_ghash_lookup(vertHash, (void *)source.v3);
- if(source.v4)
- source.v4 = (int)BLI_ghash_lookup(vertHash, (void *)source.v4);
-
- DM_copy_face_data(dm, result, faceMap[i], i, 1);
+
+ source.v1 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v1)));
+ source.v2 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v2)));
+ source.v3 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v3)));
+ if (source.v4)
+ source.v4 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v4)));
+
+ DM_copy_face_data(dm, result, oldIndex, newIndex, 1);
*dest = source;
-
- test_index_face(dest, &result->faceData, i, (orig_v4 ? 4 : 3));
+
+ test_index_face(dest, &result->faceData, newIndex, (orig_v4 ? 4 : 3));
}
-
+ BLI_ghashIterator_free(hashIter);
+
+ /* recalculate normals */
CDDM_calc_normals(result);
-
+
+ /* free hashes */
BLI_ghash_free(vertHash, NULL, NULL);
BLI_ghash_free(edgeHash, NULL, NULL);
-
- MEM_freeN(vertMap);
- MEM_freeN(edgeMap);
- MEM_freeN(faceMap);
-
+ BLI_ghash_free(faceHash, NULL, NULL);
+
+ /* return the new mesh */
return result;
}
@@ -586,7 +954,7 @@ static void arrayModifier_initData(ModifierData *md)
ArrayModifierData *amd = (ArrayModifierData*) md;
/* default to 2 duplicates distributed along the x-axis by an
- offset of 1 object-width
+ offset of 1 object-width
*/
amd->start_cap = amd->end_cap = amd->curve_ob = amd->offset_ob = NULL;
amd->count = 2;
@@ -620,9 +988,9 @@ static void arrayModifier_copyData(ModifierData *md, ModifierData *target)
}
static void arrayModifier_foreachObjectLink(
- ModifierData *md, Object *ob,
- void (*walk)(void *userData, Object *ob, Object **obpoin),
- void *userData)
+ ModifierData *md, Object *ob,
+ void (*walk)(void *userData, Object *ob, Object **obpoin),
+ void *userData)
{
ArrayModifierData *amd = (ArrayModifierData*) md;
@@ -633,7 +1001,7 @@ static void arrayModifier_foreachObjectLink(
}
static void arrayModifier_updateDepgraph(ModifierData *md, DagForest *forest,
- Object *ob, DagNode *obNode)
+ Object *ob, DagNode *obNode)
{
ArrayModifierData *amd = (ArrayModifierData*) md;
@@ -641,25 +1009,25 @@ static void arrayModifier_updateDepgraph(ModifierData *md, DagForest *forest,
DagNode *curNode = dag_get_node(forest, amd->start_cap);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Array Modifier");
}
if (amd->end_cap) {
DagNode *curNode = dag_get_node(forest, amd->end_cap);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Array Modifier");
}
if (amd->curve_ob) {
DagNode *curNode = dag_get_node(forest, amd->curve_ob);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Array Modifier");
}
if (amd->offset_ob) {
DagNode *curNode = dag_get_node(forest, amd->offset_ob);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Array Modifier");
}
}
@@ -686,12 +1054,12 @@ typedef struct IndexMapEntry {
/* the new vert index that this old vert index maps to */
int new;
/* -1 if this vert isn't merged, otherwise the old vert index it
- * should be replaced with
- */
+ * should be replaced with
+ */
int merge;
/* 1 if this vert's first copy is merged with the last copy of its
- * merge target, otherwise 0
- */
+ * merge target, otherwise 0
+ */
short merge_final;
} IndexMapEntry;
@@ -710,19 +1078,19 @@ static int calc_mapping(IndexMapEntry *indexMap, int oldIndex, int copyNum)
} else {
/* vert was merged with another vert */
/* follow the chain of merges to the end, or until we've passed
- * a number of vertices equal to the copy number
- */
+ * a number of vertices equal to the copy number
+ */
if(copyNum <= 0)
return indexMap[oldIndex].new;
else
return calc_mapping(indexMap, indexMap[oldIndex].merge,
- copyNum - 1);
+ copyNum - 1);
}
}
static DerivedMesh *arrayModifier_doArray(ArrayModifierData *amd,
- Object *ob, DerivedMesh *dm,
- int initFlags)
+ Object *ob, DerivedMesh *dm,
+ int initFlags)
{
int i, j;
/* offset matrix */
@@ -752,7 +1120,7 @@ static DerivedMesh *arrayModifier_doArray(ArrayModifierData *amd,
MTC_Mat4One(offset);
indexMap = MEM_callocN(sizeof(*indexMap) * dm->getNumVerts(dm),
- "indexmap");
+ "indexmap");
src_mvert = dm->getVertArray(dm);
@@ -763,7 +1131,7 @@ static DerivedMesh *arrayModifier_doArray(ArrayModifierData *amd,
if(amd->offset_type & MOD_ARR_OFF_RELATIVE) {
for(j = 0; j < 3; j++)
offset[3][j] += amd->scale[j] * vertarray_size(src_mvert,
- maxVerts, j);
+ maxVerts, j);
}
if((amd->offset_type & MOD_ARR_OFF_OBJ) && (amd->offset_ob)) {
@@ -776,472 +1144,509 @@ static DerivedMesh *arrayModifier_doArray(ArrayModifierData *amd,
MTC_Mat4One(obinv);
MTC_Mat4MulSerie(result_mat, offset,
- obinv, amd->offset_ob->obmat,
- NULL, NULL, NULL, NULL, NULL);
+ obinv, amd->offset_ob->obmat,
+ NULL, NULL, NULL, NULL, NULL);
MTC_Mat4CpyMat4(offset, result_mat);
}
if(amd->fit_type == MOD_ARR_FITCURVE && amd->curve_ob) {
Curve *cu = amd->curve_ob->data;
if(cu) {
+ float tmp_mat[3][3];
+ float scale;
+
+ object_to_mat3(amd->curve_ob, tmp_mat);
+ scale = Mat3ToScalef(tmp_mat);
+
if(!cu->path) {
cu->flag |= CU_PATH; // needed for path & bevlist
makeDispListCurveTypes(amd->curve_ob, 0);
}
if(cu->path)
- length = cu->path->totdist;
+ length = scale*cu->path->totdist;
}
}
/* calculate the maximum number of copies which will fit within the
- prescribed length */
+ prescribed length */
if(amd->fit_type == MOD_ARR_FITLENGTH
- || amd->fit_type == MOD_ARR_FITCURVE) {
+ || amd->fit_type == MOD_ARR_FITCURVE) {
float dist = sqrt(MTC_dot3Float(offset[3], offset[3]));
- if(dist > FLT_EPSILON)
+ if(dist > 1e-6f)
/* this gives length = first copy start to last copy end
- add a tiny offset for floating point rounding errors */
- count = (length + FLT_EPSILON) / dist;
+ add a tiny offset for floating point rounding errors */
+ count = (length + 1e-6f) / dist;
else
/* if the offset has no translation, just make one copy */
count = 1;
- }
+ }
- if(count < 1)
- count = 1;
+ if(count < 1)
+ count = 1;
/* allocate memory for count duplicates (including original) plus
- * start and end caps
- */
- finalVerts = dm->getNumVerts(dm) * count;
- finalEdges = dm->getNumEdges(dm) * count;
- finalFaces = dm->getNumFaces(dm) * count;
- if(start_cap) {
- finalVerts += start_cap->getNumVerts(start_cap);
- finalEdges += start_cap->getNumEdges(start_cap);
- finalFaces += start_cap->getNumFaces(start_cap);
- }
- if(end_cap) {
- finalVerts += end_cap->getNumVerts(end_cap);
- finalEdges += end_cap->getNumEdges(end_cap);
- finalFaces += end_cap->getNumFaces(end_cap);
- }
- result = CDDM_from_template(dm, finalVerts, finalEdges, finalFaces);
-
- /* calculate the offset matrix of the final copy (for merging) */
- MTC_Mat4One(final_offset);
-
- for(j=0; j < count - 1; j++) {
- MTC_Mat4MulMat4(tmp_mat, final_offset, offset);
- MTC_Mat4CpyMat4(final_offset, tmp_mat);
- }
-
- numVerts = numEdges = numFaces = 0;
- mvert = CDDM_get_verts(result);
-
- for (i = 0; i < maxVerts; i++) {
- MVert *inMV;
- MVert *mv = &mvert[numVerts];
- MVert *mv2;
- float co[3];
-
- inMV = &src_mvert[i];
-
- DM_copy_vert_data(dm, result, i, numVerts, 1);
- *mv = *inMV;
- numVerts++;
-
- indexMap[i].new = numVerts - 1;
- indexMap[i].merge = -1; /* default to no merge */
- indexMap[i].merge_final = 0; /* default to no merge */
-
- VECCOPY(co, mv->co);
+ * start and end caps
+ */
+ finalVerts = dm->getNumVerts(dm) * count;
+ finalEdges = dm->getNumEdges(dm) * count;
+ finalFaces = dm->getNumFaces(dm) * count;
+ if(start_cap) {
+ finalVerts += start_cap->getNumVerts(start_cap);
+ finalEdges += start_cap->getNumEdges(start_cap);
+ finalFaces += start_cap->getNumFaces(start_cap);
+ }
+ if(end_cap) {
+ finalVerts += end_cap->getNumVerts(end_cap);
+ finalEdges += end_cap->getNumEdges(end_cap);
+ finalFaces += end_cap->getNumFaces(end_cap);
+ }
+ result = CDDM_from_template(dm, finalVerts, finalEdges, finalFaces);
+
+ /* calculate the offset matrix of the final copy (for merging) */
+ MTC_Mat4One(final_offset);
+
+ for(j=0; j < count - 1; j++) {
+ MTC_Mat4MulMat4(tmp_mat, final_offset, offset);
+ MTC_Mat4CpyMat4(final_offset, tmp_mat);
+ }
+
+ numVerts = numEdges = numFaces = 0;
+ mvert = CDDM_get_verts(result);
+
+ for (i = 0; i < maxVerts; i++) {
+ indexMap[i].merge = -1; /* default to no merge */
+ indexMap[i].merge_final = 0; /* default to no merge */
+ }
+
+ for (i = 0; i < maxVerts; i++) {
+ MVert *inMV;
+ MVert *mv = &mvert[numVerts];
+ MVert *mv2;
+ float co[3];
+
+ inMV = &src_mvert[i];
+
+ DM_copy_vert_data(dm, result, i, numVerts, 1);
+ *mv = *inMV;
+ numVerts++;
+
+ indexMap[i].new = numVerts - 1;
+
+ VECCOPY(co, mv->co);
/* Attempts to merge verts from one duplicate with verts from the
- * next duplicate which are closer than amd->merge_dist.
- * Only the first such vert pair is merged.
- * If verts are merged in the first duplicate pair, they are merged
- * in all pairs.
- */
- if((count > 1) && (amd->flags & MOD_ARR_MERGE)) {
- float tmp_co[3];
- VECCOPY(tmp_co, mv->co);
- MTC_Mat4MulVecfl(offset, tmp_co);
-
- for(j = 0; j < maxVerts; j++) {
- inMV = &src_mvert[j];
- /* if this vert is within merge limit, merge */
- if(VecLenCompare(tmp_co, inMV->co, amd->merge_dist)) {
- indexMap[i].merge = j;
-
- /* test for merging with final copy of merge target */
- if(amd->flags & MOD_ARR_MERGEFINAL) {
- VECCOPY(tmp_co, inMV->co);
- inMV = &src_mvert[i];
- MTC_Mat4MulVecfl(final_offset, tmp_co);
- if(VecLenCompare(tmp_co, inMV->co, amd->merge_dist))
- indexMap[i].merge_final = 1;
- }
- break;
- }
- }
- }
-
- /* if no merging, generate copies of this vert */
- if(indexMap[i].merge < 0) {
- for(j=0; j < count - 1; j++) {
- mv2 = &mvert[numVerts];
-
- DM_copy_vert_data(result, result, numVerts - 1, numVerts, 1);
- *mv2 = *mv;
- numVerts++;
-
- MTC_Mat4MulVecfl(offset, co);
- VECCOPY(mv2->co, co);
- }
- } else if(indexMap[i].merge != i && indexMap[i].merge_final) {
+ * next duplicate which are closer than amd->merge_dist.
+ * Only the first such vert pair is merged.
+ * If verts are merged in the first duplicate pair, they are merged
+ * in all pairs.
+ */
+ if((count > 1) && (amd->flags & MOD_ARR_MERGE)) {
+ float tmp_co[3];
+ VECCOPY(tmp_co, mv->co);
+ MTC_Mat4MulVecfl(offset, tmp_co);
+
+ for(j = 0; j < maxVerts; j++) {
+ /* if vertex already merged, don't use it */
+ if( indexMap[j].merge != -1 ) continue;
+
+ inMV = &src_mvert[j];
+ /* if this vert is within merge limit, merge */
+ if(VecLenCompare(tmp_co, inMV->co, amd->merge_dist)) {
+ indexMap[i].merge = j;
+
+ /* test for merging with final copy of merge target */
+ if(amd->flags & MOD_ARR_MERGEFINAL) {
+ VECCOPY(tmp_co, inMV->co);
+ inMV = &src_mvert[i];
+ MTC_Mat4MulVecfl(final_offset, tmp_co);
+ if(VecLenCompare(tmp_co, inMV->co, amd->merge_dist))
+ indexMap[i].merge_final = 1;
+ }
+ break;
+ }
+ }
+ }
+
+ /* if no merging, generate copies of this vert */
+ if(indexMap[i].merge < 0) {
+ for(j=0; j < count - 1; j++) {
+ mv2 = &mvert[numVerts];
+
+ DM_copy_vert_data(result, result, numVerts - 1, numVerts, 1);
+ *mv2 = *mv;
+ numVerts++;
+
+ MTC_Mat4MulVecfl(offset, co);
+ VECCOPY(mv2->co, co);
+ }
+ } else if(indexMap[i].merge != i && indexMap[i].merge_final) {
/* if this vert is not merging with itself, and it is merging
- * with the final copy of its merge target, remove the first copy
- */
- numVerts--;
- DM_free_vert_data(result, numVerts, 1);
- }
- }
-
- /* make a hashtable so we can avoid duplicate edges from merging */
- edges = BLI_edgehash_new();
-
- maxEdges = dm->getNumEdges(dm);
- medge = CDDM_get_edges(result);
- for(i = 0; i < maxEdges; i++) {
- MEdge inMED;
- MEdge med;
- MEdge *med2;
- int vert1, vert2;
-
- dm->getEdge(dm, i, &inMED);
-
- med = inMED;
- med.v1 = indexMap[inMED.v1].new;
- med.v2 = indexMap[inMED.v2].new;
+ * with the final copy of its merge target, remove the first copy
+ */
+ numVerts--;
+ DM_free_vert_data(result, numVerts, 1);
+ }
+ }
+
+ /* make a hashtable so we can avoid duplicate edges from merging */
+ edges = BLI_edgehash_new();
+
+ maxEdges = dm->getNumEdges(dm);
+ medge = CDDM_get_edges(result);
+ for(i = 0; i < maxEdges; i++) {
+ MEdge inMED;
+ MEdge med;
+ MEdge *med2;
+ int vert1, vert2;
+
+ dm->getEdge(dm, i, &inMED);
+
+ med = inMED;
+ med.v1 = indexMap[inMED.v1].new;
+ med.v2 = indexMap[inMED.v2].new;
/* if vertices are to be merged with the final copies of their
- * merge targets, calculate that final copy
- */
- if(indexMap[inMED.v1].merge_final) {
- med.v1 = calc_mapping(indexMap, indexMap[inMED.v1].merge,
- count - 1);
- }
- if(indexMap[inMED.v2].merge_final) {
- med.v2 = calc_mapping(indexMap, indexMap[inMED.v2].merge,
- count - 1);
- }
-
- if (initFlags) {
- med.flag |= ME_EDGEDRAW | ME_EDGERENDER;
- }
-
- if(!BLI_edgehash_haskey(edges, med.v1, med.v2)) {
- DM_copy_edge_data(dm, result, i, numEdges, 1);
- medge[numEdges] = med;
- numEdges++;
-
- BLI_edgehash_insert(edges, med.v1, med.v2, NULL);
- }
-
- for(j = 1; j < count; j++)
- {
- vert1 = calc_mapping(indexMap, inMED.v1, j);
- vert2 = calc_mapping(indexMap, inMED.v2, j);
- /* avoid duplicate edges */
- if(!BLI_edgehash_haskey(edges, vert1, vert2)) {
- med2 = &medge[numEdges];
-
- DM_copy_edge_data(dm, result, i, numEdges, 1);
- *med2 = med;
- numEdges++;
-
- med2->v1 = vert1;
- med2->v2 = vert2;
-
- BLI_edgehash_insert(edges, med2->v1, med2->v2, NULL);
- }
- }
- }
-
- maxFaces = dm->getNumFaces(dm);
- mface = CDDM_get_faces(result);
- for (i=0; i < maxFaces; i++) {
- MFace inMF;
- MFace *mf = &mface[numFaces];
-
- dm->getFace(dm, i, &inMF);
-
- DM_copy_face_data(dm, result, i, numFaces, 1);
- *mf = inMF;
-
- mf->v1 = indexMap[inMF.v1].new;
- mf->v2 = indexMap[inMF.v2].new;
- mf->v3 = indexMap[inMF.v3].new;
- if(inMF.v4)
- mf->v4 = indexMap[inMF.v4].new;
+ * merge targets, calculate that final copy
+ */
+ if(indexMap[inMED.v1].merge_final) {
+ med.v1 = calc_mapping(indexMap, indexMap[inMED.v1].merge,
+ count - 1);
+ }
+ if(indexMap[inMED.v2].merge_final) {
+ med.v2 = calc_mapping(indexMap, indexMap[inMED.v2].merge,
+ count - 1);
+ }
+
+ if(med.v1 == med.v2) continue;
+
+ if (initFlags) {
+ med.flag |= ME_EDGEDRAW | ME_EDGERENDER;
+ }
+
+ if(!BLI_edgehash_haskey(edges, med.v1, med.v2)) {
+ DM_copy_edge_data(dm, result, i, numEdges, 1);
+ medge[numEdges] = med;
+ numEdges++;
+
+ BLI_edgehash_insert(edges, med.v1, med.v2, NULL);
+ }
+
+ for(j = 1; j < count; j++)
+ {
+ vert1 = calc_mapping(indexMap, inMED.v1, j);
+ vert2 = calc_mapping(indexMap, inMED.v2, j);
+ /* avoid duplicate edges */
+ if(!BLI_edgehash_haskey(edges, vert1, vert2)) {
+ med2 = &medge[numEdges];
+
+ DM_copy_edge_data(dm, result, i, numEdges, 1);
+ *med2 = med;
+ numEdges++;
+
+ med2->v1 = vert1;
+ med2->v2 = vert2;
+
+ BLI_edgehash_insert(edges, med2->v1, med2->v2, NULL);
+ }
+ }
+ }
+
+ maxFaces = dm->getNumFaces(dm);
+ mface = CDDM_get_faces(result);
+ for (i=0; i < maxFaces; i++) {
+ MFace inMF;
+ MFace *mf = &mface[numFaces];
+
+ dm->getFace(dm, i, &inMF);
+
+ DM_copy_face_data(dm, result, i, numFaces, 1);
+ *mf = inMF;
+
+ mf->v1 = indexMap[inMF.v1].new;
+ mf->v2 = indexMap[inMF.v2].new;
+ mf->v3 = indexMap[inMF.v3].new;
+ if(inMF.v4)
+ mf->v4 = indexMap[inMF.v4].new;
/* if vertices are to be merged with the final copies of their
- * merge targets, calculate that final copy
- */
- if(indexMap[inMF.v1].merge_final)
- mf->v1 = calc_mapping(indexMap, indexMap[inMF.v1].merge, count-1);
- if(indexMap[inMF.v2].merge_final)
- mf->v2 = calc_mapping(indexMap, indexMap[inMF.v2].merge, count-1);
- if(indexMap[inMF.v3].merge_final)
- mf->v3 = calc_mapping(indexMap, indexMap[inMF.v3].merge, count-1);
- if(inMF.v4 && indexMap[inMF.v4].merge_final)
- mf->v4 = calc_mapping(indexMap, indexMap[inMF.v4].merge, count-1);
-
- test_index_face(mf, &result->faceData, numFaces, inMF.v4?4:3);
- numFaces++;
-
- /* if the face has fewer than 3 vertices, don't create it */
- if(mf->v3 == 0) {
- numFaces--;
- DM_free_face_data(result, numFaces, 1);
- }
-
- for(j = 1; j < count; j++)
- {
- MFace *mf2 = &mface[numFaces];
-
- DM_copy_face_data(dm, result, i, numFaces, 1);
- *mf2 = *mf;
-
- mf2->v1 = calc_mapping(indexMap, inMF.v1, j);
- mf2->v2 = calc_mapping(indexMap, inMF.v2, j);
- mf2->v3 = calc_mapping(indexMap, inMF.v3, j);
- if (inMF.v4)
- mf2->v4 = calc_mapping(indexMap, inMF.v4, j);
-
- test_index_face(mf2, &result->faceData, numFaces, inMF.v4?4:3);
- numFaces++;
-
- /* if the face has fewer than 3 vertices, don't create it */
- if(mf2->v3 == 0) {
- numFaces--;
- DM_free_face_data(result, numFaces, 1);
- }
- }
- }
-
- /* add start and end caps */
- if(start_cap) {
- float startoffset[4][4];
- MVert *cap_mvert;
- MEdge *cap_medge;
- MFace *cap_mface;
- int *origindex;
- int *vert_map;
- int capVerts, capEdges, capFaces;
-
- capVerts = start_cap->getNumVerts(start_cap);
- capEdges = start_cap->getNumEdges(start_cap);
- capFaces = start_cap->getNumFaces(start_cap);
- cap_mvert = start_cap->getVertArray(start_cap);
- cap_medge = start_cap->getEdgeArray(start_cap);
- cap_mface = start_cap->getFaceArray(start_cap);
-
- Mat4Invert(startoffset, offset);
-
- vert_map = MEM_callocN(sizeof(*vert_map) * capVerts,
- "arrayModifier_doArray vert_map");
-
- origindex = result->getVertDataArray(result, CD_ORIGINDEX);
- for(i = 0; i < capVerts; i++) {
- MVert *mv = &cap_mvert[i];
- short merged = 0;
-
- if(amd->flags & MOD_ARR_MERGE) {
- float tmp_co[3];
- MVert *in_mv;
- int j;
-
- VECCOPY(tmp_co, mv->co);
- Mat4MulVecfl(startoffset, tmp_co);
-
- for(j = 0; j < maxVerts; j++) {
- in_mv = &src_mvert[j];
- /* if this vert is within merge limit, merge */
- if(VecLenCompare(tmp_co, in_mv->co, amd->merge_dist)) {
- vert_map[i] = calc_mapping(indexMap, j, 0);
- merged = 1;
- break;
- }
- }
- }
-
- if(!merged) {
- DM_copy_vert_data(start_cap, result, i, numVerts, 1);
- mvert[numVerts] = *mv;
- Mat4MulVecfl(startoffset, mvert[numVerts].co);
- origindex[numVerts] = ORIGINDEX_NONE;
-
- vert_map[i] = numVerts;
-
- numVerts++;
- }
- }
- origindex = result->getEdgeDataArray(result, CD_ORIGINDEX);
- for(i = 0; i < capEdges; i++) {
- int v1, v2;
-
- v1 = vert_map[cap_medge[i].v1];
- v2 = vert_map[cap_medge[i].v2];
-
- if(!BLI_edgehash_haskey(edges, v1, v2)) {
- DM_copy_edge_data(start_cap, result, i, numEdges, 1);
- medge[numEdges] = cap_medge[i];
- medge[numEdges].v1 = v1;
- medge[numEdges].v2 = v2;
- origindex[numEdges] = ORIGINDEX_NONE;
-
- numEdges++;
- }
- }
- origindex = result->getFaceDataArray(result, CD_ORIGINDEX);
- for(i = 0; i < capFaces; i++) {
- DM_copy_face_data(start_cap, result, i, numFaces, 1);
- mface[numFaces] = cap_mface[i];
- mface[numFaces].v1 = vert_map[mface[numFaces].v1];
- mface[numFaces].v2 = vert_map[mface[numFaces].v2];
- mface[numFaces].v3 = vert_map[mface[numFaces].v3];
- if(mface[numFaces].v4)
- mface[numFaces].v4 = vert_map[mface[numFaces].v4];
- origindex[numFaces] = ORIGINDEX_NONE;
-
- numFaces++;
- }
-
- MEM_freeN(vert_map);
- start_cap->release(start_cap);
- }
-
- if(end_cap) {
- float endoffset[4][4];
- MVert *cap_mvert;
- MEdge *cap_medge;
- MFace *cap_mface;
- int *origindex;
- int *vert_map;
- int capVerts, capEdges, capFaces;
-
- capVerts = end_cap->getNumVerts(end_cap);
- capEdges = end_cap->getNumEdges(end_cap);
- capFaces = end_cap->getNumFaces(end_cap);
- cap_mvert = end_cap->getVertArray(end_cap);
- cap_medge = end_cap->getEdgeArray(end_cap);
- cap_mface = end_cap->getFaceArray(end_cap);
-
- Mat4MulMat4(endoffset, final_offset, offset);
-
- vert_map = MEM_callocN(sizeof(*vert_map) * capVerts,
- "arrayModifier_doArray vert_map");
-
- origindex = result->getVertDataArray(result, CD_ORIGINDEX);
- for(i = 0; i < capVerts; i++) {
- MVert *mv = &cap_mvert[i];
- short merged = 0;
-
- if(amd->flags & MOD_ARR_MERGE) {
- float tmp_co[3];
- MVert *in_mv;
- int j;
-
- VECCOPY(tmp_co, mv->co);
- Mat4MulVecfl(offset, tmp_co);
-
- for(j = 0; j < maxVerts; j++) {
- in_mv = &src_mvert[j];
- /* if this vert is within merge limit, merge */
- if(VecLenCompare(tmp_co, in_mv->co, amd->merge_dist)) {
- vert_map[i] = calc_mapping(indexMap, j, count - 1);
- merged = 1;
- break;
- }
- }
- }
-
- if(!merged) {
- DM_copy_vert_data(end_cap, result, i, numVerts, 1);
- mvert[numVerts] = *mv;
- Mat4MulVecfl(endoffset, mvert[numVerts].co);
- origindex[numVerts] = ORIGINDEX_NONE;
-
- vert_map[i] = numVerts;
-
- numVerts++;
- }
- }
- origindex = result->getEdgeDataArray(result, CD_ORIGINDEX);
- for(i = 0; i < capEdges; i++) {
- int v1, v2;
-
- v1 = vert_map[cap_medge[i].v1];
- v2 = vert_map[cap_medge[i].v2];
-
- if(!BLI_edgehash_haskey(edges, v1, v2)) {
- DM_copy_edge_data(end_cap, result, i, numEdges, 1);
- medge[numEdges] = cap_medge[i];
- medge[numEdges].v1 = v1;
- medge[numEdges].v2 = v2;
- origindex[numEdges] = ORIGINDEX_NONE;
-
- numEdges++;
- }
- }
- origindex = result->getFaceDataArray(result, CD_ORIGINDEX);
- for(i = 0; i < capFaces; i++) {
- DM_copy_face_data(end_cap, result, i, numFaces, 1);
- mface[numFaces] = cap_mface[i];
- mface[numFaces].v1 = vert_map[mface[numFaces].v1];
- mface[numFaces].v2 = vert_map[mface[numFaces].v2];
- mface[numFaces].v3 = vert_map[mface[numFaces].v3];
- if(mface[numFaces].v4)
- mface[numFaces].v4 = vert_map[mface[numFaces].v4];
- origindex[numFaces] = ORIGINDEX_NONE;
-
- numFaces++;
- }
-
- MEM_freeN(vert_map);
- end_cap->release(end_cap);
- }
-
- BLI_edgehash_free(edges, NULL);
- MEM_freeN(indexMap);
-
- CDDM_lower_num_verts(result, numVerts);
- CDDM_lower_num_edges(result, numEdges);
- CDDM_lower_num_faces(result, numFaces);
-
- return result;
+ * merge targets, calculate that final copy
+ */
+ if(indexMap[inMF.v1].merge_final)
+ mf->v1 = calc_mapping(indexMap, indexMap[inMF.v1].merge, count-1);
+ if(indexMap[inMF.v2].merge_final)
+ mf->v2 = calc_mapping(indexMap, indexMap[inMF.v2].merge, count-1);
+ if(indexMap[inMF.v3].merge_final)
+ mf->v3 = calc_mapping(indexMap, indexMap[inMF.v3].merge, count-1);
+ if(inMF.v4 && indexMap[inMF.v4].merge_final)
+ mf->v4 = calc_mapping(indexMap, indexMap[inMF.v4].merge, count-1);
+
+ if(test_index_face(mf, &result->faceData, numFaces, inMF.v4?4:3) < 3)
+ continue;
+
+ numFaces++;
+
+ /* if the face has fewer than 3 vertices, don't create it */
+ if(mf->v3 == 0 || (mf->v1 && (mf->v1 == mf->v3 || mf->v1 == mf->v4))) {
+ numFaces--;
+ DM_free_face_data(result, numFaces, 1);
+ }
+
+ for(j = 1; j < count; j++)
+ {
+ MFace *mf2 = &mface[numFaces];
+
+ DM_copy_face_data(dm, result, i, numFaces, 1);
+ *mf2 = *mf;
+
+ mf2->v1 = calc_mapping(indexMap, inMF.v1, j);
+ mf2->v2 = calc_mapping(indexMap, inMF.v2, j);
+ mf2->v3 = calc_mapping(indexMap, inMF.v3, j);
+ if (inMF.v4)
+ mf2->v4 = calc_mapping(indexMap, inMF.v4, j);
+
+ test_index_face(mf2, &result->faceData, numFaces, inMF.v4?4:3);
+ numFaces++;
+
+ /* if the face has fewer than 3 vertices, don't create it */
+ if(mf2->v3 == 0 || (mf2->v1 && (mf2->v1 == mf2->v3 || mf2->v1 ==
+ mf2->v4))) {
+ numFaces--;
+ DM_free_face_data(result, numFaces, 1);
+ }
+ }
+ }
+
+ /* add start and end caps */
+ if(start_cap) {
+ float startoffset[4][4];
+ MVert *cap_mvert;
+ MEdge *cap_medge;
+ MFace *cap_mface;
+ int *origindex;
+ int *vert_map;
+ int capVerts, capEdges, capFaces;
+
+ capVerts = start_cap->getNumVerts(start_cap);
+ capEdges = start_cap->getNumEdges(start_cap);
+ capFaces = start_cap->getNumFaces(start_cap);
+ cap_mvert = start_cap->getVertArray(start_cap);
+ cap_medge = start_cap->getEdgeArray(start_cap);
+ cap_mface = start_cap->getFaceArray(start_cap);
+
+ Mat4Invert(startoffset, offset);
+
+ vert_map = MEM_callocN(sizeof(*vert_map) * capVerts,
+ "arrayModifier_doArray vert_map");
+
+ origindex = result->getVertDataArray(result, CD_ORIGINDEX);
+ for(i = 0; i < capVerts; i++) {
+ MVert *mv = &cap_mvert[i];
+ short merged = 0;
+
+ if(amd->flags & MOD_ARR_MERGE) {
+ float tmp_co[3];
+ MVert *in_mv;
+ int j;
+
+ VECCOPY(tmp_co, mv->co);
+ Mat4MulVecfl(startoffset, tmp_co);
+
+ for(j = 0; j < maxVerts; j++) {
+ in_mv = &src_mvert[j];
+ /* if this vert is within merge limit, merge */
+ if(VecLenCompare(tmp_co, in_mv->co, amd->merge_dist)) {
+ vert_map[i] = calc_mapping(indexMap, j, 0);
+ merged = 1;
+ break;
+ }
+ }
+ }
+
+ if(!merged) {
+ DM_copy_vert_data(start_cap, result, i, numVerts, 1);
+ mvert[numVerts] = *mv;
+ Mat4MulVecfl(startoffset, mvert[numVerts].co);
+ origindex[numVerts] = ORIGINDEX_NONE;
+
+ vert_map[i] = numVerts;
+
+ numVerts++;
+ }
+ }
+ origindex = result->getEdgeDataArray(result, CD_ORIGINDEX);
+ for(i = 0; i < capEdges; i++) {
+ int v1, v2;
+
+ v1 = vert_map[cap_medge[i].v1];
+ v2 = vert_map[cap_medge[i].v2];
+
+ if(!BLI_edgehash_haskey(edges, v1, v2)) {
+ DM_copy_edge_data(start_cap, result, i, numEdges, 1);
+ medge[numEdges] = cap_medge[i];
+ medge[numEdges].v1 = v1;
+ medge[numEdges].v2 = v2;
+ origindex[numEdges] = ORIGINDEX_NONE;
+
+ numEdges++;
+ }
+ }
+ origindex = result->getFaceDataArray(result, CD_ORIGINDEX);
+ for(i = 0; i < capFaces; i++) {
+ DM_copy_face_data(start_cap, result, i, numFaces, 1);
+ mface[numFaces] = cap_mface[i];
+ mface[numFaces].v1 = vert_map[mface[numFaces].v1];
+ mface[numFaces].v2 = vert_map[mface[numFaces].v2];
+ mface[numFaces].v3 = vert_map[mface[numFaces].v3];
+ if(mface[numFaces].v4) {
+ mface[numFaces].v4 = vert_map[mface[numFaces].v4];
+
+ test_index_face(&mface[numFaces], &result->faceData,
+ numFaces, 4);
+ }
+ else
+ {
+ test_index_face(&mface[numFaces], &result->faceData,
+ numFaces, 3);
+ }
+
+ origindex[numFaces] = ORIGINDEX_NONE;
+
+ numFaces++;
+ }
+
+ MEM_freeN(vert_map);
+ start_cap->release(start_cap);
+ }
+
+ if(end_cap) {
+ float endoffset[4][4];
+ MVert *cap_mvert;
+ MEdge *cap_medge;
+ MFace *cap_mface;
+ int *origindex;
+ int *vert_map;
+ int capVerts, capEdges, capFaces;
+
+ capVerts = end_cap->getNumVerts(end_cap);
+ capEdges = end_cap->getNumEdges(end_cap);
+ capFaces = end_cap->getNumFaces(end_cap);
+ cap_mvert = end_cap->getVertArray(end_cap);
+ cap_medge = end_cap->getEdgeArray(end_cap);
+ cap_mface = end_cap->getFaceArray(end_cap);
+
+ Mat4MulMat4(endoffset, final_offset, offset);
+
+ vert_map = MEM_callocN(sizeof(*vert_map) * capVerts,
+ "arrayModifier_doArray vert_map");
+
+ origindex = result->getVertDataArray(result, CD_ORIGINDEX);
+ for(i = 0; i < capVerts; i++) {
+ MVert *mv = &cap_mvert[i];
+ short merged = 0;
+
+ if(amd->flags & MOD_ARR_MERGE) {
+ float tmp_co[3];
+ MVert *in_mv;
+ int j;
+
+ VECCOPY(tmp_co, mv->co);
+ Mat4MulVecfl(offset, tmp_co);
+
+ for(j = 0; j < maxVerts; j++) {
+ in_mv = &src_mvert[j];
+ /* if this vert is within merge limit, merge */
+ if(VecLenCompare(tmp_co, in_mv->co, amd->merge_dist)) {
+ vert_map[i] = calc_mapping(indexMap, j, count - 1);
+ merged = 1;
+ break;
+ }
+ }
+ }
+
+ if(!merged) {
+ DM_copy_vert_data(end_cap, result, i, numVerts, 1);
+ mvert[numVerts] = *mv;
+ Mat4MulVecfl(endoffset, mvert[numVerts].co);
+ origindex[numVerts] = ORIGINDEX_NONE;
+
+ vert_map[i] = numVerts;
+
+ numVerts++;
+ }
+ }
+ origindex = result->getEdgeDataArray(result, CD_ORIGINDEX);
+ for(i = 0; i < capEdges; i++) {
+ int v1, v2;
+
+ v1 = vert_map[cap_medge[i].v1];
+ v2 = vert_map[cap_medge[i].v2];
+
+ if(!BLI_edgehash_haskey(edges, v1, v2)) {
+ DM_copy_edge_data(end_cap, result, i, numEdges, 1);
+ medge[numEdges] = cap_medge[i];
+ medge[numEdges].v1 = v1;
+ medge[numEdges].v2 = v2;
+ origindex[numEdges] = ORIGINDEX_NONE;
+
+ numEdges++;
+ }
+ }
+ origindex = result->getFaceDataArray(result, CD_ORIGINDEX);
+ for(i = 0; i < capFaces; i++) {
+ DM_copy_face_data(end_cap, result, i, numFaces, 1);
+ mface[numFaces] = cap_mface[i];
+ mface[numFaces].v1 = vert_map[mface[numFaces].v1];
+ mface[numFaces].v2 = vert_map[mface[numFaces].v2];
+ mface[numFaces].v3 = vert_map[mface[numFaces].v3];
+ if(mface[numFaces].v4) {
+ mface[numFaces].v4 = vert_map[mface[numFaces].v4];
+
+ test_index_face(&mface[numFaces], &result->faceData,
+ numFaces, 4);
+ }
+ else
+ {
+ test_index_face(&mface[numFaces], &result->faceData,
+ numFaces, 3);
+ }
+ origindex[numFaces] = ORIGINDEX_NONE;
+
+ numFaces++;
+ }
+
+ MEM_freeN(vert_map);
+ end_cap->release(end_cap);
+ }
+
+ BLI_edgehash_free(edges, NULL);
+ MEM_freeN(indexMap);
+
+ CDDM_lower_num_verts(result, numVerts);
+ CDDM_lower_num_edges(result, numEdges);
+ CDDM_lower_num_faces(result, numFaces);
+
+ return result;
}
static DerivedMesh *arrayModifier_applyModifier(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- int useRenderParams, int isFinalCalc)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
{
DerivedMesh *result;
ArrayModifierData *amd = (ArrayModifierData*) md;
result = arrayModifier_doArray(amd, ob, derivedData, 0);
- CDDM_calc_normals(result);
+ if(result != derivedData)
+ CDDM_calc_normals(result);
return result;
}
static DerivedMesh *arrayModifier_applyModifierEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData)
{
return arrayModifier_applyModifier(md, ob, derivedData, 0, 1);
}
@@ -1252,7 +1657,7 @@ static void mirrorModifier_initData(ModifierData *md)
{
MirrorModifierData *mmd = (MirrorModifierData*) md;
- mmd->flag |= MOD_MIR_AXIS_X;
+ mmd->flag |= (MOD_MIR_AXIS_X | MOD_MIR_VGROUP);
mmd->tolerance = 0.001;
mmd->mirror_ob = NULL;
}
@@ -1269,9 +1674,9 @@ static void mirrorModifier_copyData(ModifierData *md, ModifierData *target)
}
static void mirrorModifier_foreachObjectLink(
- ModifierData *md, Object *ob,
- void (*walk)(void *userData, Object *ob, Object **obpoin),
- void *userData)
+ ModifierData *md, Object *ob,
+ void (*walk)(void *userData, Object *ob, Object **obpoin),
+ void *userData)
{
MirrorModifierData *mmd = (MirrorModifierData*) md;
@@ -1279,7 +1684,7 @@ static void mirrorModifier_foreachObjectLink(
}
static void mirrorModifier_updateDepgraph(ModifierData *md, DagForest *forest,
- Object *ob, DagNode *obNode)
+ Object *ob, DagNode *obNode)
{
MirrorModifierData *mmd = (MirrorModifierData*) md;
@@ -1287,15 +1692,127 @@ static void mirrorModifier_updateDepgraph(ModifierData *md, DagForest *forest,
DagNode *latNode = dag_get_node(forest, mmd->mirror_ob);
dag_add_relation(forest, latNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Mirror Modifier");
}
}
+/* finds the best possible flipped name. For renaming; check for unique names afterwards */
+/* if strip_number: removes number extensions */
+void vertgroup_flip_name (char *name, int strip_number)
+{
+ int len;
+ char prefix[128]={""}; /* The part before the facing */
+ char suffix[128]={""}; /* The part after the facing */
+ char replace[128]={""}; /* The replacement string */
+ char number[128]={""}; /* The number extension string */
+ char *index=NULL;
+
+ len= strlen(name);
+ if(len<3) return; // we don't do names like .R or .L
+
+ /* We first check the case with a .### extension, let's find the last period */
+ if(isdigit(name[len-1])) {
+ index= strrchr(name, '.'); // last occurrance
+ if (index && isdigit(index[1]) ) { // doesnt handle case bone.1abc2 correct..., whatever!
+ if(strip_number==0)
+ strcpy(number, index);
+ *index= 0;
+ len= strlen(name);
+ }
+ }
+
+ strcpy (prefix, name);
+
+#define IS_SEPARATOR(a) ((a)=='.' || (a)==' ' || (a)=='-' || (a)=='_')
+
+ /* first case; separator . - _ with extensions r R l L */
+ if( IS_SEPARATOR(name[len-2]) ) {
+ switch(name[len-1]) {
+ case 'l':
+ prefix[len-1]= 0;
+ strcpy(replace, "r");
+ break;
+ case 'r':
+ prefix[len-1]= 0;
+ strcpy(replace, "l");
+ break;
+ case 'L':
+ prefix[len-1]= 0;
+ strcpy(replace, "R");
+ break;
+ case 'R':
+ prefix[len-1]= 0;
+ strcpy(replace, "L");
+ break;
+ }
+ }
+ /* case; beginning with r R l L , with separator after it */
+ else if( IS_SEPARATOR(name[1]) ) {
+ switch(name[0]) {
+ case 'l':
+ strcpy(replace, "r");
+ strcpy(suffix, name+1);
+ prefix[0]= 0;
+ break;
+ case 'r':
+ strcpy(replace, "l");
+ strcpy(suffix, name+1);
+ prefix[0]= 0;
+ break;
+ case 'L':
+ strcpy(replace, "R");
+ strcpy(suffix, name+1);
+ prefix[0]= 0;
+ break;
+ case 'R':
+ strcpy(replace, "L");
+ strcpy(suffix, name+1);
+ prefix[0]= 0;
+ break;
+ }
+ }
+ else if(len > 5) {
+ /* hrms, why test for a separator? lets do the rule 'ultimate left or right' */
+ index = BLI_strcasestr(prefix, "right");
+ if (index==prefix || index==prefix+len-5) {
+ if(index[0]=='r')
+ strcpy (replace, "left");
+ else {
+ if(index[1]=='I')
+ strcpy (replace, "LEFT");
+ else
+ strcpy (replace, "Left");
+ }
+ *index= 0;
+ strcpy (suffix, index+5);
+ }
+ else {
+ index = BLI_strcasestr(prefix, "left");
+ if (index==prefix || index==prefix+len-4) {
+ if(index[0]=='l')
+ strcpy (replace, "right");
+ else {
+ if(index[1]=='E')
+ strcpy (replace, "RIGHT");
+ else
+ strcpy (replace, "Right");
+ }
+ *index= 0;
+ strcpy (suffix, index+4);
+ }
+ }
+ }
+
+#undef IS_SEPARATOR
+
+ sprintf (name, "%s%s%s%s", prefix, replace, suffix, number);
+}
+
static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
- Object *ob,
- DerivedMesh *dm,
- int initFlags,
- int axis)
+ Object *ob,
+ DerivedMesh *dm,
+ int initFlags,
+ int axis)
{
int i;
float tolerance = mmd->tolerance;
@@ -1304,6 +1821,9 @@ static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
int maxVerts = dm->getNumVerts(dm);
int maxEdges = dm->getNumEdges(dm);
int maxFaces = dm->getNumFaces(dm);
+ int vector_size=0, j, a, b;
+ bDeformGroup *def, *defb;
+ bDeformGroup **vector_def = NULL;
int (*indexMap)[2];
float mtx[4][4], imtx[4][4];
@@ -1313,9 +1833,24 @@ static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
result = CDDM_from_template(dm, maxVerts * 2, maxEdges * 2, maxFaces * 2);
+
+ if (mmd->flag & MOD_MIR_VGROUP) {
+ /* calculate the number of deformedGroups */
+ for(vector_size = 0, def = ob->defbase.first; def;
+ def = def->next, vector_size++);
+
+ /* load the deformedGroups for fast access */
+ vector_def =
+ (bDeformGroup **)MEM_mallocN(sizeof(bDeformGroup*) * vector_size,
+ "group_index");
+ for(a = 0, def = ob->defbase.first; def; def = def->next, a++) {
+ vector_def[a] = def;
+ }
+ }
+
if (mmd->mirror_ob) {
float obinv[4][4];
-
+
Mat4Invert(obinv, mmd->mirror_ob->obmat);
Mat4MulMat4(mtx, ob->obmat, obinv);
Mat4Invert(imtx, mtx);
@@ -1326,27 +1861,27 @@ static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
MVert *mv = CDDM_get_vert(result, numVerts);
int isShared;
float co[3];
-
+
dm->getVert(dm, i, &inMV);
-
+
VecCopyf(co, inMV.co);
-
+
if (mmd->mirror_ob) {
VecMat4MulVecfl(co, mtx, co);
}
isShared = ABS(co[axis])<=tolerance;
-
+
/* Because the topology result (# of vertices) must be the same if
- * the mesh data is overridden by vertex cos, have to calc sharedness
- * based on original coordinates. This is why we test before copy.
- */
+ * the mesh data is overridden by vertex cos, have to calc sharedness
+ * based on original coordinates. This is why we test before copy.
+ */
DM_copy_vert_data(dm, result, i, numVerts, 1);
*mv = inMV;
numVerts++;
-
+
indexMap[i][0] = numVerts - 1;
indexMap[i][1] = !isShared;
-
+
if(isShared) {
co[axis] = 0;
if (mmd->mirror_ob) {
@@ -1357,41 +1892,73 @@ static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
mv->flag |= ME_VERT_MERGED;
} else {
MVert *mv2 = CDDM_get_vert(result, numVerts);
-
+ MDeformVert *dvert = NULL;
+
DM_copy_vert_data(dm, result, i, numVerts, 1);
*mv2 = *mv;
- numVerts++;
-
+
co[axis] = -co[axis];
if (mmd->mirror_ob) {
VecMat4MulVecfl(co, imtx, co);
}
VecCopyf(mv2->co, co);
+
+ if (mmd->flag & MOD_MIR_VGROUP){
+ dvert = DM_get_vert_data(result, numVerts, CD_MDEFORMVERT);
+
+ if (dvert)
+ {
+ for(j = 0; j < dvert[0].totweight; ++j)
+ {
+ char tmpname[32];
+
+ if(dvert->dw[j].def_nr < 0 ||
+ dvert->dw[j].def_nr >= vector_size)
+ continue;
+
+ def = vector_def[dvert->dw[j].def_nr];
+ strcpy(tmpname, def->name);
+ vertgroup_flip_name(tmpname,0);
+
+ for(b = 0, defb = ob->defbase.first; defb;
+ defb = defb->next, b++)
+ {
+ if(!strcmp(defb->name, tmpname))
+ {
+ dvert->dw[j].def_nr = b;
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ numVerts++;
}
}
for(i = 0; i < maxEdges; i++) {
MEdge inMED;
MEdge *med = CDDM_get_edge(result, numEdges);
-
+
dm->getEdge(dm, i, &inMED);
-
+
DM_copy_edge_data(dm, result, i, numEdges, 1);
*med = inMED;
numEdges++;
-
+
med->v1 = indexMap[inMED.v1][0];
med->v2 = indexMap[inMED.v2][0];
if(initFlags)
med->flag |= ME_EDGEDRAW | ME_EDGERENDER;
-
+
if(indexMap[inMED.v1][1] || indexMap[inMED.v2][1]) {
MEdge *med2 = CDDM_get_edge(result, numEdges);
-
+
DM_copy_edge_data(dm, result, i, numEdges, 1);
*med2 = *med;
numEdges++;
-
+
med2->v1 += indexMap[inMED.v1][1];
med2->v2 += indexMap[inMED.v2][1];
}
@@ -1400,33 +1967,33 @@ static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
for(i = 0; i < maxFaces; i++) {
MFace inMF;
MFace *mf = CDDM_get_face(result, numFaces);
-
+
dm->getFace(dm, i, &inMF);
-
+
DM_copy_face_data(dm, result, i, numFaces, 1);
*mf = inMF;
numFaces++;
-
+
mf->v1 = indexMap[inMF.v1][0];
mf->v2 = indexMap[inMF.v2][0];
mf->v3 = indexMap[inMF.v3][0];
mf->v4 = indexMap[inMF.v4][0];
if(indexMap[inMF.v1][1]
- || indexMap[inMF.v2][1]
- || indexMap[inMF.v3][1]
- || (mf->v4 && indexMap[inMF.v4][1])) {
+ || indexMap[inMF.v2][1]
+ || indexMap[inMF.v3][1]
+ || (mf->v4 && indexMap[inMF.v4][1])) {
MFace *mf2 = CDDM_get_face(result, numFaces);
static int corner_indices[4] = {2, 1, 0, 3};
-
+
DM_copy_face_data(dm, result, i, numFaces, 1);
*mf2 = *mf;
-
+
mf2->v1 += indexMap[inMF.v1][1];
mf2->v2 += indexMap[inMF.v2][1];
mf2->v3 += indexMap[inMF.v3][1];
if(inMF.v4) mf2->v4 += indexMap[inMF.v4][1];
-
+
/* mirror UVs if enabled */
if(mmd->flag & (MOD_MIR_MIRROR_U | MOD_MIR_MIRROR_V)) {
MTFace *tf = result->getFaceData(result, numFaces, CD_MTFACE);
@@ -1440,16 +2007,18 @@ static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
}
}
}
-
+
/* Flip face normal */
SWAP(int, mf2->v1, mf2->v3);
DM_swap_face_data(result, numFaces, corner_indices);
-
+
test_index_face(mf2, &result->faceData, numFaces, inMF.v4?4:3);
numFaces++;
}
}
+ if (vector_def) MEM_freeN(vector_def);
+
MEM_freeN(indexMap);
CDDM_lower_num_verts(result, numVerts);
@@ -1460,8 +2029,8 @@ static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
}
static DerivedMesh *mirrorModifier__doMirror(MirrorModifierData *mmd,
- Object *ob, DerivedMesh *dm,
- int initFlags)
+ Object *ob, DerivedMesh *dm,
+ int initFlags)
{
DerivedMesh *result = dm;
@@ -1484,22 +2053,23 @@ static DerivedMesh *mirrorModifier__doMirror(MirrorModifierData *mmd,
}
static DerivedMesh *mirrorModifier_applyModifier(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- int useRenderParams, int isFinalCalc)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
{
DerivedMesh *result;
MirrorModifierData *mmd = (MirrorModifierData*) md;
result = mirrorModifier__doMirror(mmd, ob, derivedData, 0);
- CDDM_calc_normals(result);
+ if(result != derivedData)
+ CDDM_calc_normals(result);
return result;
}
static DerivedMesh *mirrorModifier_applyModifierEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData)
{
return mirrorModifier_applyModifier(md, ob, derivedData, 0, 1);
}
@@ -1570,6 +2140,8 @@ typedef struct SmoothMesh {
DerivedMesh *dm;
float threshold; /* the cosine of the smoothing angle */
int flags;
+ MemArena *arena;
+ ListBase propagatestack, reusestack;
} SmoothMesh;
static SmoothVert *smoothvert_copy(SmoothVert *vert, SmoothMesh *mesh)
@@ -1622,15 +2194,15 @@ static int smoothedge_has_vert(SmoothEdge *edge, SmoothVert *vert)
}
static SmoothMesh *smoothmesh_new(int num_verts, int num_edges, int num_faces,
- int max_verts, int max_edges, int max_faces)
+ int max_verts, int max_edges, int max_faces)
{
SmoothMesh *mesh = MEM_callocN(sizeof(*mesh), "smoothmesh");
mesh->verts = MEM_callocN(sizeof(*mesh->verts) * max_verts,
- "SmoothMesh.verts");
+ "SmoothMesh.verts");
mesh->edges = MEM_callocN(sizeof(*mesh->edges) * max_edges,
- "SmoothMesh.edges");
+ "SmoothMesh.edges");
mesh->faces = MEM_callocN(sizeof(*mesh->faces) * max_faces,
- "SmoothMesh.faces");
+ "SmoothMesh.faces");
mesh->num_verts = num_verts;
mesh->num_edges = num_edges;
@@ -1652,6 +2224,9 @@ static void smoothmesh_free(SmoothMesh *mesh)
for(i = 0; i < mesh->num_edges; ++i)
BLI_linklist_free(mesh->edges[i].faces, NULL);
+
+ if(mesh->arena)
+ BLI_memarena_free(mesh->arena);
MEM_freeN(mesh->verts);
MEM_freeN(mesh->edges);
@@ -1729,7 +2304,7 @@ static void smoothmesh_print(SmoothMesh *mesh)
printf("%3d: ind={%3d, %3d}, pos={% 5.1f, % 5.1f, % 5.1f}",
i, vert->oldIndex, vert->newIndex,
- mv.co[0], mv.co[1], mv.co[2]);
+ mv.co[0], mv.co[1], mv.co[2]);
printf(", faces={");
for(node = vert->faces; node != NULL; node = node->next) {
printf(" %d", ((SmoothFace *)node->link)->newIndex);
@@ -1744,8 +2319,8 @@ static void smoothmesh_print(SmoothMesh *mesh)
printf("%4d: indices={%4d, %4d}, verts={%4d, %4d}",
i,
- edge->oldIndex, edge->newIndex,
- edge->verts[0]->newIndex, edge->verts[1]->newIndex);
+ edge->oldIndex, edge->newIndex,
+ edge->verts[0]->newIndex, edge->verts[1]->newIndex);
if(edge->verts[0] == edge->verts[1]) printf(" <- DUPLICATE VERTEX");
printf(", faces={");
for(node = edge->faces; node != NULL; node = node->next) {
@@ -1787,7 +2362,7 @@ static SmoothMesh *smoothmesh_from_derivedmesh(DerivedMesh *dm)
totface = dm->getNumFaces(dm);
mesh = smoothmesh_new(totvert, totedge, totface,
- totvert, totedge, totface);
+ totvert, totedge, totface);
mesh->dm = dm;
@@ -1857,9 +2432,9 @@ static SmoothMesh *smoothmesh_from_derivedmesh(DerivedMesh *dm)
static DerivedMesh *CDDM_from_smoothmesh(SmoothMesh *mesh)
{
DerivedMesh *result = CDDM_from_template(mesh->dm,
- mesh->num_verts,
- mesh->num_edges,
- mesh->num_faces);
+ mesh->num_verts,
+ mesh->num_edges,
+ mesh->num_faces);
MVert *new_verts = CDDM_get_verts(result);
MEdge *new_edges = CDDM_get_edges(result);
MFace *new_faces = CDDM_get_faces(result);
@@ -1870,7 +2445,7 @@ static DerivedMesh *CDDM_from_smoothmesh(SmoothMesh *mesh)
MVert *newMV = &new_verts[vert->newIndex];
DM_copy_vert_data(mesh->dm, result,
- vert->oldIndex, vert->newIndex, 1);
+ vert->oldIndex, vert->newIndex, 1);
mesh->dm->getVert(mesh->dm, vert->oldIndex, newMV);
}
@@ -1879,7 +2454,7 @@ static DerivedMesh *CDDM_from_smoothmesh(SmoothMesh *mesh)
MEdge *newME = &new_edges[edge->newIndex];
DM_copy_edge_data(mesh->dm, result,
- edge->oldIndex, edge->newIndex, 1);
+ edge->oldIndex, edge->newIndex, 1);
mesh->dm->getEdge(mesh->dm, edge->oldIndex, newME);
newME->v1 = edge->verts[0]->newIndex;
newME->v2 = edge->verts[1]->newIndex;
@@ -1890,7 +2465,7 @@ static DerivedMesh *CDDM_from_smoothmesh(SmoothMesh *mesh)
MFace *newMF = &new_faces[face->newIndex];
DM_copy_face_data(mesh->dm, result,
- face->oldIndex, face->newIndex, 1);
+ face->oldIndex, face->newIndex, 1);
mesh->dm->getFace(mesh->dm, face->oldIndex, newMF);
newMF->v1 = face->edges[0]->verts[face->flip[0]]->newIndex;
@@ -1920,7 +2495,7 @@ static SmoothVert *other_vert(SmoothEdge *edge, SmoothVert *vert)
* (this should never happen)
*/
static SmoothEdge *other_edge(SmoothFace *face, SmoothVert *vert,
- SmoothEdge *edge)
+ SmoothEdge *edge)
{
int i,j;
for(i = 0; i < SMOOTHFACE_MAX_EDGES && face->edges[i]; i++) {
@@ -1932,8 +2507,8 @@ static SmoothEdge *other_edge(SmoothFace *face, SmoothVert *vert,
}
/* if we get to here, something's wrong (there should always be 2 edges
- * which use the same vert in a face)
- */
+ * which use the same vert in a face)
+ */
return NULL;
}
@@ -1962,18 +2537,18 @@ static void linklist_copy(LinkNode **target, LinkNode *source)
for(; source; source = source->next) {
if(node) {
node->next = MEM_mallocN(sizeof(*node->next), "nlink_copy");
- node = node->next;
- } else {
- node = *target = MEM_mallocN(sizeof(**target), "nlink_copy");
- }
- node->link = source->link;
- node->next = NULL;
- }
+ node = node->next;
+} else {
+ node = *target = MEM_mallocN(sizeof(**target), "nlink_copy");
+}
+ node->link = source->link;
+ node->next = NULL;
+}
}
#endif
-/* appends source to target if it's not already in target */
-static void linklist_append_unique(LinkNode **target, void *source)
+ /* appends source to target if it's not already in target */
+ static void linklist_append_unique(LinkNode **target, void *source)
{
LinkNode *node;
LinkNode *prev = NULL;
@@ -2007,7 +2582,7 @@ static void linklist_prepend_linklist(LinkNode **list, LinkNode *prepend)
node->next = *list;
*list = prepend;
- }
+}
}
#endif
@@ -2050,7 +2625,7 @@ static void linklist_empty(LinkNode **list, LinkNodeFreeFP freefunc)
* frees the pointer with freefunc if freefunc is not NULL
*/
static void linklist_remove_first(LinkNode **list, void *value,
- LinkNodeFreeFP freefunc)
+ LinkNodeFreeFP freefunc)
{
LinkNode *node = *list;
LinkNode *prev = NULL;
@@ -2075,7 +2650,7 @@ static void linklist_remove_first(LinkNode **list, void *value,
/* removes all elements in source from target */
static void linklist_remove_list(LinkNode **target, LinkNode *source,
- LinkNodeFreeFP freefunc)
+ LinkNodeFreeFP freefunc)
{
for(; source; source = source->next)
linklist_remove_first(target, source->link, freefunc);
@@ -2150,15 +2725,15 @@ static void face_replace_edge(void *ptr, void *userdata)
#ifdef EDGESPLIT_DEBUG_3
printf("replacing edge %4d with %4d in face %4d",
- find->newIndex, replace->newIndex, face->newIndex);
+ find->newIndex, replace->newIndex, face->newIndex);
if(face->edges[3])
printf(": {%2d %2d %2d %2d}",
face->edges[0]->newIndex, face->edges[1]->newIndex,
- face->edges[2]->newIndex, face->edges[3]->newIndex);
+ face->edges[2]->newIndex, face->edges[3]->newIndex);
else
printf(": {%2d %2d %2d}",
face->edges[0]->newIndex, face->edges[1]->newIndex,
- face->edges[2]->newIndex);
+ face->edges[2]->newIndex);
#endif
for(i = 0; i < SMOOTHFACE_MAX_EDGES && face->edges[i]; i++) {
@@ -2173,11 +2748,11 @@ static void face_replace_edge(void *ptr, void *userdata)
if(face->edges[3])
printf(" -> {%2d %2d %2d %2d}\n",
face->edges[0]->newIndex, face->edges[1]->newIndex,
- face->edges[2]->newIndex, face->edges[3]->newIndex);
+ face->edges[2]->newIndex, face->edges[3]->newIndex);
else
printf(" -> {%2d %2d %2d}\n",
face->edges[0]->newIndex, face->edges[1]->newIndex,
- face->edges[2]->newIndex);
+ face->edges[2]->newIndex);
#endif
}
@@ -2187,7 +2762,7 @@ static int edge_is_loose(SmoothEdge *edge)
}
static int edge_is_sharp(SmoothEdge *edge, int flags,
- float threshold)
+ float threshold)
{
#ifdef EDGESPLIT_DEBUG_1
printf("edge %d: ", edge->newIndex);
@@ -2218,7 +2793,7 @@ static int edge_is_sharp(SmoothEdge *edge, int flags,
* - returns to the start edge (NULL is returned)
*/
static SmoothEdge *find_other_sharp_edge(SmoothVert *vert, SmoothEdge *edge,
- LinkNode **visited_faces, float threshold, int flags)
+ LinkNode **visited_faces, float threshold, int flags)
{
SmoothFace *face = NULL;
SmoothEdge *edge2 = NULL;
@@ -2244,10 +2819,10 @@ static SmoothEdge *find_other_sharp_edge(SmoothVert *vert, SmoothEdge *edge,
BLI_linklist_prepend(visited_faces, face);
/* search until we hit a loose edge or a sharp edge or an edge we've
- * seen before
- */
+ * seen before
+ */
while(face && !edge_is_sharp(edge2, flags, threshold)
- && !linklist_contains(visited_edges, edge2)) {
+ && !linklist_contains(visited_edges, edge2)) {
#ifdef EDGESPLIT_DEBUG_3
printf("current face %4d; current edge %4d\n", face->newIndex,
edge2->newIndex);
@@ -2273,25 +2848,25 @@ static SmoothEdge *find_other_sharp_edge(SmoothVert *vert, SmoothEdge *edge,
printf("loose edge: %4d\n", edge2->newIndex);
#endif
}
- }
+ }
- /* either we came back to the start edge or we found a sharp/loose edge */
- if(linklist_contains(visited_edges, edge2))
- /* we came back to the start edge */
- edge2 = NULL;
+ /* either we came back to the start edge or we found a sharp/loose edge */
+ if(linklist_contains(visited_edges, edge2))
+ /* we came back to the start edge */
+ edge2 = NULL;
- BLI_linklist_free(visited_edges, NULL);
+ BLI_linklist_free(visited_edges, NULL);
#ifdef EDGESPLIT_DEBUG_1
- printf("=== END === find_other_sharp_edge(edge = %4d, vert = %4d), "
- "returning edge %d\n",
- edge->newIndex, vert->newIndex, edge2 ? edge2->newIndex : -1);
+ printf("=== END === find_other_sharp_edge(edge = %4d, vert = %4d), "
+ "returning edge %d\n",
+ edge->newIndex, vert->newIndex, edge2 ? edge2->newIndex : -1);
#endif
- return edge2;
+ return edge2;
}
static void split_single_vert(SmoothVert *vert, SmoothFace *face,
- SmoothMesh *mesh)
+ SmoothMesh *mesh)
{
SmoothVert *copy_vert;
ReplaceData repdata;
@@ -2303,10 +2878,53 @@ static void split_single_vert(SmoothVert *vert, SmoothFace *face,
face_replace_vert(face, &repdata);
}
+typedef struct PropagateEdge {
+ struct PropagateEdge *next, *prev;
+ SmoothEdge *edge;
+ SmoothVert *vert;
+} PropagateEdge;
+
+static void push_propagate_stack(SmoothEdge *edge, SmoothVert *vert, SmoothMesh *mesh)
+{
+ PropagateEdge *pedge = mesh->reusestack.first;
+
+ if(pedge) {
+ BLI_remlink(&mesh->reusestack, pedge);
+ }
+ else {
+ if(!mesh->arena) {
+ mesh->arena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
+ BLI_memarena_use_calloc(mesh->arena);
+ }
+
+ pedge = BLI_memarena_alloc(mesh->arena, sizeof(PropagateEdge));
+ }
+
+ pedge->edge = edge;
+ pedge->vert = vert;
+ BLI_addhead(&mesh->propagatestack, pedge);
+}
+
+static void pop_propagate_stack(SmoothEdge **edge, SmoothVert **vert, SmoothMesh *mesh)
+{
+ PropagateEdge *pedge = mesh->propagatestack.first;
+
+ if(pedge) {
+ *edge = pedge->edge;
+ *vert = pedge->vert;
+ BLI_remlink(&mesh->propagatestack, pedge);
+ BLI_addhead(&mesh->reusestack, pedge);
+ }
+ else {
+ *edge = NULL;
+ *vert = NULL;
+ }
+}
+
static void split_edge(SmoothEdge *edge, SmoothVert *vert, SmoothMesh *mesh);
static void propagate_split(SmoothEdge *edge, SmoothVert *vert,
- SmoothMesh *mesh)
+ SmoothMesh *mesh)
{
SmoothEdge *edge2;
LinkNode *visited_faces = NULL;
@@ -2316,7 +2934,7 @@ static void propagate_split(SmoothEdge *edge, SmoothVert *vert,
#endif
edge2 = find_other_sharp_edge(vert, edge, &visited_faces,
- mesh->threshold, mesh->flags);
+ mesh->threshold, mesh->flags);
if(!edge2) {
/* didn't find a sharp or loose edge, so we've hit a dead end */
@@ -2375,12 +2993,12 @@ static void split_edge(SmoothEdge *edge, SmoothVert *vert, SmoothMesh *mesh)
#endif
edge2 = find_other_sharp_edge(vert, edge, &visited_faces,
- mesh->threshold, mesh->flags);
+ mesh->threshold, mesh->flags);
if(!edge2) {
/* didn't find a sharp or loose edge, so try the other vert */
vert2 = other_vert(edge, vert);
- propagate_split(edge, vert2, mesh);
+ push_propagate_stack(edge, vert2, mesh);
} else if(!edge_is_loose(edge2)) {
/* edge2 is not loose, so it must be sharp */
SmoothEdge *copy_edge = smoothedge_copy(edge, mesh);
@@ -2400,20 +3018,20 @@ static void split_edge(SmoothEdge *edge, SmoothVert *vert, SmoothMesh *mesh)
vert2 = smoothvert_copy(vert, mesh);
/* replace vert with its copy in visited_faces (must be done after
- * edge replacement so edges have correct vertices)
- */
+ * edge replacement so edges have correct vertices)
+ */
repdata.find = vert;
repdata.replace = vert2;
BLI_linklist_apply(visited_faces, face_replace_vert, &repdata);
/* all copying and replacing is done; the mesh should be consistent.
- * now propagate the split to the vertices at either end
- */
- propagate_split(copy_edge, other_vert(copy_edge, vert2), mesh);
- propagate_split(copy_edge2, other_vert(copy_edge2, vert2), mesh);
+ * now propagate the split to the vertices at either end
+ */
+ push_propagate_stack(copy_edge, other_vert(copy_edge, vert2), mesh);
+ push_propagate_stack(copy_edge2, other_vert(copy_edge2, vert2), mesh);
if(smoothedge_has_vert(edge, vert))
- propagate_split(edge, vert, mesh);
+ push_propagate_stack(edge, vert, mesh);
} else {
/* edge2 is loose */
SmoothEdge *copy_edge = smoothedge_copy(edge, mesh);
@@ -2427,19 +3045,19 @@ static void split_edge(SmoothEdge *edge, SmoothVert *vert, SmoothMesh *mesh)
vert2 = smoothvert_copy(vert, mesh);
/* replace vert with its copy in visited_faces (must be done after
- * edge replacement so edges have correct vertices)
- */
+ * edge replacement so edges have correct vertices)
+ */
repdata.find = vert;
repdata.replace = vert2;
BLI_linklist_apply(visited_faces, face_replace_vert, &repdata);
/* copying and replacing is done; the mesh should be consistent.
- * now propagate the split to the vertex at the other end
- */
- propagate_split(copy_edge, other_vert(copy_edge, vert2), mesh);
+ * now propagate the split to the vertex at the other end
+ */
+ push_propagate_stack(copy_edge, other_vert(copy_edge, vert2), mesh);
if(smoothedge_has_vert(edge, vert))
- propagate_split(edge, vert, mesh);
+ push_propagate_stack(edge, vert, mesh);
}
BLI_linklist_free(visited_faces, NULL);
@@ -2450,7 +3068,7 @@ static void split_edge(SmoothEdge *edge, SmoothVert *vert, SmoothMesh *mesh)
}
static void tag_and_count_extra_edges(SmoothMesh *mesh, float split_angle,
- int flags, int *extra_edges)
+ int flags, int *extra_edges)
{
/* if normal1 dot normal2 < threshold, angle is greater, so split */
/* FIXME not sure if this always works */
@@ -2477,40 +3095,41 @@ static void tag_and_count_extra_edges(SmoothMesh *mesh, float split_angle,
for(node = edge->faces->next->next->next; node; node = node->next)
(*extra_edges)++;
} else if((flags & (MOD_EDGESPLIT_FROMANGLE | MOD_EDGESPLIT_FROMFLAG))
- && !edge_is_loose(edge)) {
+ && !edge_is_loose(edge)) {
/* (the edge can only be sharp if we're checking angle or flag,
- * and it has at least 2 faces) */
+ * and it has at least 2 faces) */
- /* if we're checking the sharp flag and it's set, good */
- if((flags & MOD_EDGESPLIT_FROMFLAG) && (edge->flag & ME_SHARP)) {
- /* this edge is sharp */
- sharp = 1;
+ /* if we're checking the sharp flag and it's set, good */
+ if((flags & MOD_EDGESPLIT_FROMFLAG) && (edge->flag & ME_SHARP)) {
+ /* this edge is sharp */
+ sharp = 1;
- (*extra_edges)++;
- } else if(flags & MOD_EDGESPLIT_FROMANGLE) {
- /* we know the edge has 2 faces, so check the angle */
- SmoothFace *face1 = edge->faces->link;
- SmoothFace *face2 = edge->faces->next->link;
- float edge_angle_cos = MTC_dot3Float(face1->normal,
- face2->normal);
-
- if(edge_angle_cos < threshold) {
- /* this edge is sharp */
- sharp = 1;
-
- (*extra_edges)++;
- }
- }
- }
+ (*extra_edges)++;
+ } else if(flags & MOD_EDGESPLIT_FROMANGLE) {
+ /* we know the edge has 2 faces, so check the angle */
+ SmoothFace *face1 = edge->faces->link;
+ SmoothFace *face2 = edge->faces->next->link;
+ float edge_angle_cos = MTC_dot3Float(face1->normal,
+ face2->normal);
+
+ if(edge_angle_cos < threshold) {
+ /* this edge is sharp */
+ sharp = 1;
- /* set/clear sharp flag appropriately */
- if(sharp) edge->flag |= ME_SHARP;
- else edge->flag &= ~ME_SHARP;
+ (*extra_edges)++;
+ }
+ }
+ }
+
+ /* set/clear sharp flag appropriately */
+ if(sharp) edge->flag |= ME_SHARP;
+ else edge->flag &= ~ME_SHARP;
}
}
static void split_sharp_edges(SmoothMesh *mesh, float split_angle, int flags)
{
+ SmoothVert *vert;
int i;
/* if normal1 dot normal2 < threshold, angle is greater, so split */
/* FIXME not sure if this always works */
@@ -2523,10 +3142,16 @@ static void split_sharp_edges(SmoothMesh *mesh, float split_angle, int flags)
for(i = 0; i < mesh->num_edges; i++) {
SmoothEdge *edge = &mesh->edges[i];
- if(edge_is_sharp(edge, flags, mesh->threshold))
+ if(edge_is_sharp(edge, flags, mesh->threshold)) {
split_edge(edge, edge->verts[0], mesh);
- }
+ do {
+ pop_propagate_stack(&edge, &vert, mesh);
+ if(edge && smoothedge_has_vert(edge, vert))
+ propagate_split(edge, vert, mesh);
+ } while(edge);
+ }
+ }
}
static int count_bridge_verts(SmoothMesh *mesh)
@@ -2548,19 +3173,19 @@ static int count_bridge_verts(SmoothMesh *mesh)
next_edge = face->edges[next];
/* if there are other faces sharing this vertex but not
- * these edges, the vertex will be split, so count it
- */
+ * these edges, the vertex will be split, so count it
+ */
/* vert has to have at least one face (this one), so faces != 0 */
if(!edge->faces->next && !next_edge->faces->next
- && vert->faces->next) {
+ && vert->faces->next) {
count++;
- }
+ }
}
}
/* each bridge vert will be counted once per face that uses it,
- * so count is too high, but it's ok for now
- */
+ * so count is too high, but it's ok for now
+ */
return count;
}
@@ -2583,21 +3208,21 @@ static void split_bridge_verts(SmoothMesh *mesh)
next_edge = face->edges[next];
/* if there are other faces sharing this vertex but not
- * these edges, split the vertex
- */
+ * these edges, split the vertex
+ */
/* vert has to have at least one face (this one), so faces != 0 */
if(!edge->faces->next && !next_edge->faces->next
- && vert->faces->next)
+ && vert->faces->next)
/* FIXME this needs to find all faces that share edges with
- * this one and split off together
- */
+ * this one and split off together
+ */
split_single_vert(vert, face, mesh);
}
}
}
static DerivedMesh *edgesplitModifier_do(EdgeSplitModifierData *emd,
- Object *ob, DerivedMesh *dm)
+ Object *ob, DerivedMesh *dm)
{
SmoothMesh *mesh;
DerivedMesh *result;
@@ -2640,8 +3265,8 @@ static DerivedMesh *edgesplitModifier_do(EdgeSplitModifierData *emd,
#ifdef EDGESPLIT_DEBUG_0
printf("Edgesplit: Estimated %d verts & %d edges, "
- "found %d verts & %d edges\n", max_verts, max_edges,
- mesh->num_verts, mesh->num_edges);
+ "found %d verts & %d edges\n", max_verts, max_edges,
+ mesh->num_verts, mesh->num_edges);
#endif
result = CDDM_from_smoothmesh(mesh);
@@ -2651,26 +3276,111 @@ static DerivedMesh *edgesplitModifier_do(EdgeSplitModifierData *emd,
}
static DerivedMesh *edgesplitModifier_applyModifier(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- int useRenderParams, int isFinalCalc)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
{
DerivedMesh *result;
EdgeSplitModifierData *emd = (EdgeSplitModifierData*) md;
result = edgesplitModifier_do(emd, ob, derivedData);
- CDDM_calc_normals(result);
+ if(result != derivedData)
+ CDDM_calc_normals(result);
return result;
}
static DerivedMesh *edgesplitModifier_applyModifierEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData)
{
return edgesplitModifier_applyModifier(md, ob, derivedData, 0, 1);
}
+/* Bevel */
+
+static void bevelModifier_initData(ModifierData *md)
+{
+ BevelModifierData *bmd = (BevelModifierData*) md;
+
+ bmd->value = 0.1f;
+ bmd->res = 1;
+ bmd->flags = 0;
+ bmd->val_flags = 0;
+ bmd->lim_flags = 0;
+ bmd->e_flags = 0;
+ bmd->bevel_angle = 30;
+ bmd->defgrp_name[0] = '\0';
+}
+
+static void bevelModifier_copyData(ModifierData *md, ModifierData *target)
+{
+ BevelModifierData *bmd = (BevelModifierData*) md;
+ BevelModifierData *tbmd = (BevelModifierData*) target;
+
+ tbmd->value = bmd->value;
+ tbmd->res = bmd->res;
+ tbmd->flags = bmd->flags;
+ tbmd->val_flags = bmd->val_flags;
+ tbmd->lim_flags = bmd->lim_flags;
+ tbmd->e_flags = bmd->e_flags;
+ tbmd->bevel_angle = bmd->bevel_angle;
+ strncpy(tbmd->defgrp_name, bmd->defgrp_name, 32);
+}
+
+CustomDataMask bevelModifier_requiredDataMask(ModifierData *md)
+{
+ BevelModifierData *bmd = (BevelModifierData *)md;
+ CustomDataMask dataMask = 0;
+
+ /* ask for vertexgroups if we need them */
+ if(bmd->defgrp_name[0]) dataMask |= (1 << CD_MDEFORMVERT);
+
+ return dataMask;
+}
+
+static DerivedMesh *bevelModifier_applyModifier(
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
+{
+ DerivedMesh *result;
+ BME_Mesh *bm;
+
+ /*bDeformGroup *def;*/
+ int /*i,*/ options, defgrp_index = -1;
+ BevelModifierData *bmd = (BevelModifierData*) md;
+
+ options = bmd->flags|bmd->val_flags|bmd->lim_flags|bmd->e_flags;
+
+ //~ if ((options & BME_BEVEL_VWEIGHT) && bmd->defgrp_name[0]) {
+ //~ for (i = 0, def = ob->defbase.first; def; def = def->next, i++) {
+ //~ if (!strcmp(def->name, bmd->defgrp_name)) {
+ //~ defgrp_index = i;
+ //~ break;
+ //~ }
+ //~ }
+ //~ if (defgrp_index < 0) {
+ //~ options &= ~BME_BEVEL_VWEIGHT;
+ //~ }
+ //~ }
+
+ bm = BME_derivedmesh_to_bmesh(derivedData);
+ BME_bevel(bm,bmd->value,bmd->res,options,defgrp_index,bmd->bevel_angle,NULL);
+ result = BME_bmesh_to_derivedmesh(bm,derivedData);
+ BME_free_mesh(bm);
+
+ CDDM_calc_normals(result);
+
+ return result;
+}
+
+static DerivedMesh *bevelModifier_applyModifierEM(
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData)
+{
+ return bevelModifier_applyModifier(md, ob, derivedData, 0, 1);
+}
+
/* Displace */
static void displaceModifier_initData(ModifierData *md)
@@ -2712,8 +3422,22 @@ CustomDataMask displaceModifier_requiredDataMask(ModifierData *md)
return dataMask;
}
+static int displaceModifier_dependsOnTime(ModifierData *md)
+{
+ DisplaceModifierData *dmd = (DisplaceModifierData *)md;
+
+ if(dmd->texture)
+ {
+ return BKE_texture_dependsOnTime(dmd->texture);
+ }
+ else
+ {
+ return 0;
+ }
+}
+
static void displaceModifier_foreachObjectLink(ModifierData *md, Object *ob,
- ObjectWalkFunc walk, void *userData)
+ ObjectWalkFunc walk, void *userData)
{
DisplaceModifierData *dmd = (DisplaceModifierData*) md;
@@ -2721,13 +3445,13 @@ static void displaceModifier_foreachObjectLink(ModifierData *md, Object *ob,
}
static void displaceModifier_foreachIDLink(ModifierData *md, Object *ob,
- IDWalkFunc walk, void *userData)
+ IDWalkFunc walk, void *userData)
{
DisplaceModifierData *dmd = (DisplaceModifierData*) md;
walk(userData, ob, (ID **)&dmd->texture);
- displaceModifier_foreachObjectLink(md, ob, (ObjectWalkFunc) walk, userData);
+ displaceModifier_foreachObjectLink(md, ob, (ObjectWalkFunc)walk, userData);
}
static int displaceModifier_isDisabled(ModifierData *md)
@@ -2738,8 +3462,8 @@ static int displaceModifier_isDisabled(ModifierData *md)
}
static void displaceModifier_updateDepgraph(
- ModifierData *md, DagForest *forest,
- Object *ob, DagNode *obNode)
+ ModifierData *md, DagForest *forest,
+ Object *ob, DagNode *obNode)
{
DisplaceModifierData *dmd = (DisplaceModifierData*) md;
@@ -2747,7 +3471,7 @@ static void displaceModifier_updateDepgraph(
DagNode *curNode = dag_get_node(forest, dmd->map_object);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Displace Modifier");
}
}
@@ -2761,17 +3485,17 @@ static void validate_layer_name(const CustomData *data, int type, char *name)
if(index < 0) {
/* either no layer was specified, or the layer we want has been
- * deleted, so assign the active layer to name
- */
+ * deleted, so assign the active layer to name
+ */
index = CustomData_get_active_layer_index(data, CD_MTFACE);
strcpy(name, data->layers[index].name);
}
}
static void get_texture_coords(DisplaceModifierData *dmd, Object *ob,
- DerivedMesh *dm,
- float (*co)[3], float (*texco)[3],
- int numVerts)
+ DerivedMesh *dm,
+ float (*co)[3], float (*texco)[3],
+ int numVerts)
{
int i;
int texmapping = dmd->texmapping;
@@ -2789,14 +3513,14 @@ static void get_texture_coords(DisplaceModifierData *dmd, Object *ob,
MFace *mface = dm->getFaceArray(dm);
MFace *mf;
char *done = MEM_callocN(sizeof(*done) * numVerts,
- "get_texture_coords done");
+ "get_texture_coords done");
int numFaces = dm->getNumFaces(dm);
MTFace *tf;
validate_layer_name(&dm->faceData, CD_MTFACE, dmd->uvlayer_name);
tf = CustomData_get_layer_named(&dm->faceData, CD_MTFACE,
- dmd->uvlayer_name);
+ dmd->uvlayer_name);
/* verts are given the UV from the first face that uses them */
for(i = 0, mf = mface; i < numFaces; ++i, ++mf, ++tf) {
@@ -2840,18 +3564,18 @@ static void get_texture_coords(DisplaceModifierData *dmd, Object *ob,
for(i = 0; i < numVerts; ++i, ++co, ++texco) {
switch(texmapping) {
- case MOD_DISP_MAP_LOCAL:
- VECCOPY(*texco, *co);
- break;
- case MOD_DISP_MAP_GLOBAL:
- VECCOPY(*texco, *co);
- Mat4MulVecfl(ob->obmat, *texco);
- break;
- case MOD_DISP_MAP_OBJECT:
- VECCOPY(*texco, *co);
- Mat4MulVecfl(ob->obmat, *texco);
- Mat4MulVecfl(dmd->map_object->imat, *texco);
- break;
+ case MOD_DISP_MAP_LOCAL:
+ VECCOPY(*texco, *co);
+ break;
+ case MOD_DISP_MAP_GLOBAL:
+ VECCOPY(*texco, *co);
+ Mat4MulVecfl(ob->obmat, *texco);
+ break;
+ case MOD_DISP_MAP_OBJECT:
+ VECCOPY(*texco, *co);
+ Mat4MulVecfl(ob->obmat, *texco);
+ Mat4MulVecfl(dmd->map_object->imat, *texco);
+ break;
}
}
}
@@ -2861,23 +3585,23 @@ static void get_texture_value(Tex *texture, float *tex_co, TexResult *texres)
int result_type;
result_type = multitex_ext(texture, tex_co, NULL,
- NULL, 1, texres);
+ NULL, 1, texres);
/* if the texture gave an RGB value, we assume it didn't give a valid
- * intensity, so calculate one (formula from do_material_tex).
- * if the texture didn't give an RGB value, copy the intensity across
- */
+ * intensity, so calculate one (formula from do_material_tex).
+ * if the texture didn't give an RGB value, copy the intensity across
+ */
if(result_type & TEX_RGB)
texres->tin = (0.35 * texres->tr + 0.45 * texres->tg
- + 0.2 * texres->tb);
+ + 0.2 * texres->tb);
else
texres->tr = texres->tg = texres->tb = texres->tin;
}
/* dm must be a CDDerivedMesh */
static void displaceModifier_do(
- DisplaceModifierData *dmd, Object *ob,
- DerivedMesh *dm, float (*vertexCos)[3], int numVerts)
+ DisplaceModifierData *dmd, Object *ob,
+ DerivedMesh *dm, float (*vertexCos)[3], int numVerts)
{
int i;
MVert *mvert;
@@ -2904,7 +3628,7 @@ static void displaceModifier_do(
dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
tex_co = MEM_callocN(sizeof(*tex_co) * numVerts,
- "displaceModifier_do tex_co");
+ "displaceModifier_do tex_co");
get_texture_coords(dmd, ob, dm, vertexCos, tex_co, numVerts);
for(i = 0; i < numVerts; ++i) {
@@ -2933,25 +3657,25 @@ static void displaceModifier_do(
delta *= strength;
switch(dmd->direction) {
- case MOD_DISP_DIR_X:
- vertexCos[i][0] += delta;
- break;
- case MOD_DISP_DIR_Y:
- vertexCos[i][1] += delta;
- break;
- case MOD_DISP_DIR_Z:
- vertexCos[i][2] += delta;
- break;
- case MOD_DISP_DIR_RGB_XYZ:
- vertexCos[i][0] += (texres.tr - dmd->midlevel) * strength;
- vertexCos[i][1] += (texres.tg - dmd->midlevel) * strength;
- vertexCos[i][2] += (texres.tb - dmd->midlevel) * strength;
- break;
- case MOD_DISP_DIR_NOR:
- vertexCos[i][0] += delta * mvert[i].no[0] / 32767.0f;
- vertexCos[i][1] += delta * mvert[i].no[1] / 32767.0f;
- vertexCos[i][2] += delta * mvert[i].no[2] / 32767.0f;
- break;
+ case MOD_DISP_DIR_X:
+ vertexCos[i][0] += delta;
+ break;
+ case MOD_DISP_DIR_Y:
+ vertexCos[i][1] += delta;
+ break;
+ case MOD_DISP_DIR_Z:
+ vertexCos[i][2] += delta;
+ break;
+ case MOD_DISP_DIR_RGB_XYZ:
+ vertexCos[i][0] += (texres.tr - dmd->midlevel) * strength;
+ vertexCos[i][1] += (texres.tg - dmd->midlevel) * strength;
+ vertexCos[i][2] += (texres.tb - dmd->midlevel) * strength;
+ break;
+ case MOD_DISP_DIR_NOR:
+ vertexCos[i][0] += delta * mvert[i].no[0] / 32767.0f;
+ vertexCos[i][1] += delta * mvert[i].no[1] / 32767.0f;
+ vertexCos[i][2] += delta * mvert[i].no[2] / 32767.0f;
+ break;
}
}
@@ -2959,8 +3683,8 @@ static void displaceModifier_do(
}
static void displaceModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm;
@@ -2972,14 +3696,14 @@ static void displaceModifier_deformVerts(
CDDM_calc_normals(dm);
displaceModifier_do((DisplaceModifierData *)md, ob, dm,
- vertexCos, numVerts);
+ vertexCos, numVerts);
dm->release(dm);
}
static void displaceModifier_deformVertsEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm;
@@ -2990,7 +3714,7 @@ static void displaceModifier_deformVertsEM(
CDDM_calc_normals(dm);
displaceModifier_do((DisplaceModifierData *)md, ob, dm,
- vertexCos, numVerts);
+ vertexCos, numVerts);
dm->release(dm);
}
@@ -3038,7 +3762,7 @@ CustomDataMask uvprojectModifier_requiredDataMask(ModifierData *md)
}
static void uvprojectModifier_foreachObjectLink(ModifierData *md, Object *ob,
- ObjectWalkFunc walk, void *userData)
+ ObjectWalkFunc walk, void *userData)
{
UVProjectModifierData *umd = (UVProjectModifierData*) md;
int i;
@@ -3048,18 +3772,18 @@ static void uvprojectModifier_foreachObjectLink(ModifierData *md, Object *ob,
}
static void uvprojectModifier_foreachIDLink(ModifierData *md, Object *ob,
- IDWalkFunc walk, void *userData)
+ IDWalkFunc walk, void *userData)
{
UVProjectModifierData *umd = (UVProjectModifierData*) md;
walk(userData, ob, (ID **)&umd->image);
uvprojectModifier_foreachObjectLink(md, ob, (ObjectWalkFunc)walk,
- userData);
+ userData);
}
static void uvprojectModifier_updateDepgraph(ModifierData *md,
- DagForest *forest, Object *ob, DagNode *obNode)
+ DagForest *forest, Object *ob, DagNode *obNode)
{
UVProjectModifierData *umd = (UVProjectModifierData*) md;
int i;
@@ -3069,7 +3793,7 @@ static void uvprojectModifier_updateDepgraph(ModifierData *md,
DagNode *curNode = dag_get_node(forest, umd->projectors[i]);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "UV Project Modifier");
}
}
}
@@ -3081,7 +3805,7 @@ typedef struct Projector {
} Projector;
static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
- Object *ob, DerivedMesh *dm)
+ Object *ob, DerivedMesh *dm)
{
float (*coords)[3], (*co)[3];
MTFace *tface;
@@ -3110,13 +3834,13 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
/* make sure we are not modifying the original UV layer */
tface = CustomData_duplicate_referenced_layer_named(&dm->faceData,
- CD_MTFACE,
- umd->uvlayer_name);
+ CD_MTFACE,
+ umd->uvlayer_name);
numVerts = dm->getNumVerts(dm);
coords = MEM_callocN(sizeof(*coords) * numVerts,
- "uvprojectModifier_do coords");
+ "uvprojectModifier_do coords");
dm->getVertCos(dm, coords);
/* convert coords to world space */
@@ -3127,12 +3851,12 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
for(i = 0; i < num_projectors; ++i) {
float tmpmat[4][4];
float offsetmat[4][4];
-
+ Camera *cam = NULL;
/* calculate projection matrix */
Mat4Invert(projectors[i].projmat, projectors[i].ob->obmat);
if(projectors[i].ob->type == OB_CAMERA) {
- Camera *cam = (Camera *)projectors[i].ob->data;
+ cam = (Camera *)projectors[i].ob->data;
if(cam->type == CAM_PERSP) {
float perspmat[4][4];
float xmax;
@@ -3152,7 +3876,7 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
ymin = -ymax;
i_window(xmin, xmax, ymin, ymax,
- cam->clipsta, cam->clipend, perspmat);
+ cam->clipsta, cam->clipend, perspmat);
Mat4MulMat4(tmpmat, projectors[i].projmat, perspmat);
} else if(cam->type == CAM_ORTHO) {
float orthomat[4][4];
@@ -3172,7 +3896,7 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
ymin = -ymax;
i_ortho(xmin, xmax, ymin, ymax,
- cam->clipsta, cam->clipend, orthomat);
+ cam->clipsta, cam->clipend, orthomat);
Mat4MulMat4(tmpmat, projectors[i].projmat, orthomat);
}
} else {
@@ -3182,6 +3906,20 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
Mat4One(offsetmat);
Mat4MulFloat3(offsetmat[0], 0.5);
offsetmat[3][0] = offsetmat[3][1] = offsetmat[3][2] = 0.5;
+
+ if (cam) {
+ if (umd->aspectx == umd->aspecty) {
+ offsetmat[3][0] -= cam->shiftx;
+ offsetmat[3][1] -= cam->shifty;
+ } else if (umd->aspectx < umd->aspecty) {
+ offsetmat[3][0] -=(cam->shiftx * umd->aspecty/umd->aspectx);
+ offsetmat[3][1] -= cam->shifty;
+ } else {
+ offsetmat[3][0] -= cam->shiftx;
+ offsetmat[3][1] -=(cam->shifty * umd->aspectx/umd->aspecty);
+ }
+ }
+
Mat4MulMat4(projectors[i].projmat, tmpmat, offsetmat);
/* calculate worldspace projector normal (for best projector test) */
@@ -3216,8 +3954,8 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
}
} else {
/* multiple projectors, select the closest to face normal
- * direction
- */
+ * direction
+ */
float co1[3], co2[3], co3[3], co4[3];
float face_no[3];
int j;
@@ -3237,14 +3975,14 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
}
/* find the projector which the face points at most directly
- * (projector normal with largest dot product is best)
- */
+ * (projector normal with largest dot product is best)
+ */
best_dot = MTC_dot3Float(projectors[0].normal, face_no);
best_projector = &projectors[0];
for(j = 1; j < num_projectors; ++j) {
float tmp_dot = MTC_dot3Float(projectors[j].normal,
- face_no);
+ face_no);
if(tmp_dot > best_dot) {
best_dot = tmp_dot;
best_projector = &projectors[j];
@@ -3283,8 +4021,8 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
}
static DerivedMesh *uvprojectModifier_applyModifier(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- int useRenderParams, int isFinalCalc)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
{
DerivedMesh *result;
UVProjectModifierData *umd = (UVProjectModifierData*) md;
@@ -3295,8 +4033,8 @@ static DerivedMesh *uvprojectModifier_applyModifier(
}
static DerivedMesh *uvprojectModifier_applyModifierEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData)
{
return uvprojectModifier_applyModifier(md, ob, derivedData, 0, 1);
}
@@ -3321,8 +4059,8 @@ static void decimateModifier_copyData(ModifierData *md, ModifierData *target)
//XXX
#if 0
static DerivedMesh *decimateModifier_applyModifier(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- int useRenderParams, int isFinalCalc)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
{
DecimateModifierData *dmd = (DecimateModifierData*) md;
DerivedMesh *dm = derivedData, *result = NULL;
@@ -3346,7 +4084,7 @@ static DerivedMesh *decimateModifier_applyModifier(
if(numTris<3) {
modifier_setError(md,
- "There must be more than 3 input faces (triangles).");
+ "Modifier requires more than 3 input faces (triangles).");
goto exit;
}
@@ -3436,7 +4174,7 @@ static DerivedMesh *decimateModifier_applyModifier(
MEM_freeN(lod.triangle_index_buffer);
exit:
- return result;
+ return result;
}
#endif
@@ -3488,8 +4226,8 @@ CustomDataMask smoothModifier_requiredDataMask(ModifierData *md)
}
static void smoothModifier_do(
- SmoothModifierData *smd, Object *ob, DerivedMesh *dm,
- float (*vertexCos)[3], int numVerts)
+ SmoothModifierData *smd, Object *ob, DerivedMesh *dm,
+ float (*vertexCos)[3], int numVerts)
{
MDeformVert *dvert = NULL;
MEdge *medges = NULL;
@@ -3499,10 +4237,10 @@ static void smoothModifier_do(
float *ftmp, fac, facm;
ftmp = (float*)MEM_callocN(3*sizeof(float)*numVerts,
- "smoothmodifier_f");
+ "smoothmodifier_f");
if (!ftmp) return;
uctmp = (unsigned char*)MEM_callocN(sizeof(unsigned char)*numVerts,
- "smoothmodifier_uc");
+ "smoothmodifier_uc");
if (!uctmp) {
if (ftmp) MEM_freeN(ftmp);
return;
@@ -3531,7 +4269,7 @@ static void smoothModifier_do(
dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
/* NOTICE: this can be optimized a little bit by moving the
- * if (dvert) out of the loop, if needed */
+ * if (dvert) out of the loop, if needed */
for (j = 0; j < smd->repeat; j++) {
for (i = 0; i < numDMEdges; i++) {
float fvec[3];
@@ -3627,8 +4365,8 @@ static void smoothModifier_do(
}
static void smoothModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm;
@@ -3639,14 +4377,14 @@ static void smoothModifier_deformVerts(
CDDM_calc_normals(dm);
smoothModifier_do((SmoothModifierData *)md, ob, dm,
- vertexCos, numVerts);
+ vertexCos, numVerts);
dm->release(dm);
}
static void smoothModifier_deformVertsEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm;
@@ -3657,7 +4395,7 @@ static void smoothModifier_deformVertsEM(
CDDM_calc_normals(dm);
smoothModifier_do((SmoothModifierData *)md, ob, dm,
- vertexCos, numVerts);
+ vertexCos, numVerts);
dm->release(dm);
}
@@ -3672,7 +4410,7 @@ static void castModifier_initData(ModifierData *md)
cmd->radius = 0.0f;
cmd->size = 0.0f;
cmd->flag = MOD_CAST_X | MOD_CAST_Y | MOD_CAST_Z
- | MOD_CAST_SIZE_FROM_RADIUS;
+ | MOD_CAST_SIZE_FROM_RADIUS;
cmd->type = MOD_CAST_TYPE_SPHERE;
cmd->defgrp_name[0] = '\0';
cmd->object = NULL;
@@ -3717,9 +4455,9 @@ CustomDataMask castModifier_requiredDataMask(ModifierData *md)
}
static void castModifier_foreachObjectLink(
- ModifierData *md, Object *ob,
- void (*walk)(void *userData, Object *ob, Object **obpoin),
- void *userData)
+ ModifierData *md, Object *ob,
+ void (*walk)(void *userData, Object *ob, Object **obpoin),
+ void *userData)
{
CastModifierData *cmd = (CastModifierData*) md;
@@ -3727,21 +4465,22 @@ static void castModifier_foreachObjectLink(
}
static void castModifier_updateDepgraph(
- ModifierData *md, DagForest *forest, Object *ob,
- DagNode *obNode)
+ ModifierData *md, DagForest *forest, Object *ob,
+ DagNode *obNode)
{
CastModifierData *cmd = (CastModifierData*) md;
if (cmd->object) {
DagNode *curNode = dag_get_node(forest, cmd->object);
- dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA);
+ dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA,
+ "Cast Modifier");
}
}
static void castModifier_sphere_do(
- CastModifierData *cmd, Object *ob, DerivedMesh *dm,
- float (*vertexCos)[3], int numVerts)
+ CastModifierData *cmd, Object *ob, DerivedMesh *dm,
+ float (*vertexCos)[3], int numVerts)
{
MDeformVert *dvert = NULL;
@@ -3766,8 +4505,8 @@ static void castModifier_sphere_do(
ctrl_ob = cmd->object;
/* spherify's center is {0, 0, 0} (the ob's own center in its local
- * space), by default, but if the user defined a control object,
- * we use its location, transformed to ob's local space */
+ * space), by default, but if the user defined a control object,
+ * we use its location, transformed to ob's local space */
if (ctrl_ob) {
if(flag & MOD_CAST_USE_OB_TRANSFORM) {
Mat4Invert(ctrl_ob->imat, ctrl_ob->obmat);
@@ -3784,11 +4523,11 @@ static void castModifier_sphere_do(
/* 1) (flag was checked in the "if (ctrl_ob)" block above) */
/* 2) cmd->radius > 0.0f: only the vertices within this radius from
- * the center of the effect should be deformed */
+ * the center of the effect should be deformed */
if (cmd->radius > FLT_EPSILON) has_radius = 1;
/* 3) if we were given a vertex group name,
- * only those vertices should be affected */
+ * only those vertices should be affected */
if (cmd->defgrp_name[0]) {
bDeformGroup *def;
@@ -3820,10 +4559,10 @@ static void castModifier_sphere_do(
}
/* ready to apply the effect, one vertex at a time;
- * tiny optimization: the code is separated (with parts repeated)
+ * tiny optimization: the code is separated (with parts repeated)
* in two possible cases:
- * with or w/o a vgroup. With lots of if's in the code below,
- * further optimizations are possible, if needed */
+ * with or w/o a vgroup. With lots of if's in the code below,
+ * further optimizations are possible, if needed */
if (dvert) { /* with a vgroup */
float fac_orig = fac;
for (i = 0; i < numVerts; i++) {
@@ -3926,8 +4665,8 @@ static void castModifier_sphere_do(
}
static void castModifier_cuboid_do(
- CastModifierData *cmd, Object *ob, DerivedMesh *dm,
- float (*vertexCos)[3], int numVerts)
+ CastModifierData *cmd, Object *ob, DerivedMesh *dm,
+ float (*vertexCos)[3], int numVerts)
{
MDeformVert *dvert = NULL;
Object *ctrl_ob = NULL;
@@ -3951,11 +4690,11 @@ static void castModifier_cuboid_do(
/* 1) (flag was checked in the "if (ctrl_ob)" block above) */
/* 2) cmd->radius > 0.0f: only the vertices within this radius from
- * the center of the effect should be deformed */
+ * the center of the effect should be deformed */
if (cmd->radius > FLT_EPSILON) has_radius = 1;
/* 3) if we were given a vertex group name,
- * only those vertices should be affected */
+ * only those vertices should be affected */
if (cmd->defgrp_name[0]) {
bDeformGroup *def;
@@ -3995,12 +4734,12 @@ static void castModifier_cuboid_do(
} else {
/* get bound box */
/* We can't use the object's bound box because other modifiers
- * may have changed the vertex data. */
+ * may have changed the vertex data. */
INIT_MINMAX(min, max);
/* Cast's center is the ob's own center in its local space,
- * by default, but if the user defined a control object, we use
- * its location, transformed to ob's local space. */
+ * by default, but if the user defined a control object, we use
+ * its location, transformed to ob's local space. */
if (ctrl_ob) {
float vec[3];
@@ -4036,10 +4775,10 @@ static void castModifier_cuboid_do(
bb[4][2] = bb[5][2] = bb[6][2] = bb[7][2] = max[2];
/* ready to apply the effect, one vertex at a time;
- * tiny optimization: the code is separated (with parts repeated)
+ * tiny optimization: the code is separated (with parts repeated)
* in two possible cases:
- * with or w/o a vgroup. With lots of if's in the code below,
- * further optimizations are possible, if needed */
+ * with or w/o a vgroup. With lots of if's in the code below,
+ * further optimizations are possible, if needed */
if (dvert) { /* with a vgroup */
float fac_orig = fac;
for (i = 0; i < numVerts; i++) {
@@ -4059,8 +4798,8 @@ static void castModifier_cuboid_do(
if (has_radius) {
if (fabs(tmp_co[0]) > cmd->radius ||
- fabs(tmp_co[1]) > cmd->radius ||
- fabs(tmp_co[2]) > cmd->radius) continue;
+ fabs(tmp_co[1]) > cmd->radius ||
+ fabs(tmp_co[2]) > cmd->radius) continue;
}
for (j = 0; j < dvert[i].totweight; ++j) {
@@ -4077,10 +4816,10 @@ static void castModifier_cuboid_do(
/* The algo used to project the vertices to their
* bounding box (bb) is pretty simple:
* for each vertex v:
- * 1) find in which octant v is in;
- * 2) find which outer "wall" of that octant is closer to v;
- * 3) calculate factor (var fbb) to project v to that wall;
- * 4) project. */
+ * 1) find in which octant v is in;
+ * 2) find which outer "wall" of that octant is closer to v;
+ * 3) calculate factor (var fbb) to project v to that wall;
+ * 4) project. */
/* find in which octant this vertex is in */
octant = 0;
@@ -4114,7 +4853,7 @@ static void castModifier_cuboid_do(
continue;
/* finally, this is the factor we wanted, to project the vertex
- * to its bounding box (bb) */
+ * to its bounding box (bb) */
fbb = apex[coord] / tmp_co[coord];
/* calculate the new vertex position */
@@ -4155,8 +4894,8 @@ static void castModifier_cuboid_do(
if (has_radius) {
if (fabs(tmp_co[0]) > cmd->radius ||
- fabs(tmp_co[1]) > cmd->radius ||
- fabs(tmp_co[2]) > cmd->radius) continue;
+ fabs(tmp_co[1]) > cmd->radius ||
+ fabs(tmp_co[2]) > cmd->radius) continue;
}
octant = 0;
@@ -4206,8 +4945,8 @@ static void castModifier_cuboid_do(
}
static void castModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm = derivedData;
CastModifierData *cmd = (CastModifierData *)md;
@@ -4225,8 +4964,8 @@ static void castModifier_deformVerts(
}
static void castModifier_deformVertsEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm = derivedData;
CastModifierData *cmd = (CastModifierData *)md;
@@ -4245,13 +4984,13 @@ static void castModifier_deformVertsEM(
/* Wave */
-static void waveModifier_initData(ModifierData *md)
+static void waveModifier_initData(ModifierData *md)
{
WaveModifierData *wmd = (WaveModifierData*) md; // whadya know, moved here from Iraq
-
+
wmd->flag |= (MOD_WAVE_X | MOD_WAVE_Y | MOD_WAVE_CYCL
- | MOD_WAVE_NORM_X | MOD_WAVE_NORM_Y | MOD_WAVE_NORM_Z);
-
+ | MOD_WAVE_NORM_X | MOD_WAVE_NORM_Y | MOD_WAVE_NORM_Z);
+
wmd->objectcenter = NULL;
wmd->texture = NULL;
wmd->map_object = NULL;
@@ -4261,6 +5000,7 @@ static void waveModifier_initData(ModifierData *md)
wmd->narrow= 1.5f;
wmd->lifetime= 0.0f;
wmd->damp= 10.0f;
+ wmd->falloff= 0.0f;
wmd->texmapping = MOD_WAV_MAP_LOCAL;
wmd->defgrp_name[0] = 0;
}
@@ -4280,6 +5020,7 @@ static void waveModifier_copyData(ModifierData *md, ModifierData *target)
twmd->starty = wmd->starty;
twmd->timeoffs = wmd->timeoffs;
twmd->width = wmd->width;
+ twmd->falloff = wmd->falloff;
twmd->objectcenter = wmd->objectcenter;
twmd->texture = wmd->texture;
twmd->map_object = wmd->map_object;
@@ -4293,8 +5034,8 @@ static int waveModifier_dependsOnTime(ModifierData *md)
}
static void waveModifier_foreachObjectLink(
- ModifierData *md, Object *ob,
- ObjectWalkFunc walk, void *userData)
+ ModifierData *md, Object *ob,
+ ObjectWalkFunc walk, void *userData)
{
WaveModifierData *wmd = (WaveModifierData*) md;
@@ -4303,7 +5044,7 @@ static void waveModifier_foreachObjectLink(
}
static void waveModifier_foreachIDLink(ModifierData *md, Object *ob,
- IDWalkFunc walk, void *userData)
+ IDWalkFunc walk, void *userData)
{
WaveModifierData *wmd = (WaveModifierData*) md;
@@ -4313,21 +5054,23 @@ static void waveModifier_foreachIDLink(ModifierData *md, Object *ob,
}
static void waveModifier_updateDepgraph(
- ModifierData *md, DagForest *forest, Object *ob,
- DagNode *obNode)
+ ModifierData *md, DagForest *forest, Object *ob,
+ DagNode *obNode)
{
WaveModifierData *wmd = (WaveModifierData*) md;
if(wmd->objectcenter) {
DagNode *curNode = dag_get_node(forest, wmd->objectcenter);
- dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA);
+ dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA,
+ "Wave Modifier");
}
if(wmd->map_object) {
DagNode *curNode = dag_get_node(forest, wmd->map_object);
- dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA);
+ dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA,
+ "Wave Modifer");
}
}
@@ -4349,9 +5092,9 @@ CustomDataMask waveModifier_requiredDataMask(ModifierData *md)
}
static void wavemod_get_texture_coords(WaveModifierData *wmd, Object *ob,
- DerivedMesh *dm,
- float (*co)[3], float (*texco)[3],
- int numVerts)
+ DerivedMesh *dm,
+ float (*co)[3], float (*texco)[3],
+ int numVerts)
{
int i;
int texmapping = wmd->texmapping;
@@ -4369,14 +5112,14 @@ static void wavemod_get_texture_coords(WaveModifierData *wmd, Object *ob,
MFace *mface = dm->getFaceArray(dm);
MFace *mf;
char *done = MEM_callocN(sizeof(*done) * numVerts,
- "get_texture_coords done");
+ "get_texture_coords done");
int numFaces = dm->getNumFaces(dm);
MTFace *tf;
validate_layer_name(&dm->faceData, CD_MTFACE, wmd->uvlayer_name);
tf = CustomData_get_layer_named(&dm->faceData, CD_MTFACE,
- wmd->uvlayer_name);
+ wmd->uvlayer_name);
/* verts are given the UV from the first face that uses them */
for(i = 0, mf = mface; i < numFaces; ++i, ++mf, ++tf) {
@@ -4420,25 +5163,25 @@ static void wavemod_get_texture_coords(WaveModifierData *wmd, Object *ob,
for(i = 0; i < numVerts; ++i, ++co, ++texco) {
switch(texmapping) {
- case MOD_WAV_MAP_LOCAL:
- VECCOPY(*texco, *co);
- break;
- case MOD_WAV_MAP_GLOBAL:
- VECCOPY(*texco, *co);
- Mat4MulVecfl(ob->obmat, *texco);
- break;
- case MOD_WAV_MAP_OBJECT:
- VECCOPY(*texco, *co);
- Mat4MulVecfl(ob->obmat, *texco);
- Mat4MulVecfl(wmd->map_object->imat, *texco);
- break;
+ case MOD_WAV_MAP_LOCAL:
+ VECCOPY(*texco, *co);
+ break;
+ case MOD_WAV_MAP_GLOBAL:
+ VECCOPY(*texco, *co);
+ Mat4MulVecfl(ob->obmat, *texco);
+ break;
+ case MOD_WAV_MAP_OBJECT:
+ VECCOPY(*texco, *co);
+ Mat4MulVecfl(ob->obmat, *texco);
+ Mat4MulVecfl(wmd->map_object->imat, *texco);
+ break;
}
}
}
static void waveModifier_do(
- WaveModifierData *md, Object *ob, DerivedMesh *dm,
- float (*vertexCos)[3], int numVerts)
+ WaveModifierData *md, Object *ob, DerivedMesh *dm,
+ float (*vertexCos)[3], int numVerts)
{
WaveModifierData *wmd = (WaveModifierData*) md;
MVert *mvert = NULL;
@@ -4446,7 +5189,7 @@ static void waveModifier_do(
int defgrp_index;
float ctime = bsystem_time(ob, (float)G.scene->r.cfra, 0.0);
float minfac =
- (float)(1.0 / exp(wmd->width * wmd->narrow * wmd->width * wmd->narrow));
+ (float)(1.0 / exp(wmd->width * wmd->narrow * wmd->width * wmd->narrow));
float lifefac = wmd->height;
float (*tex_co)[3] = NULL;
@@ -4488,16 +5231,16 @@ static void waveModifier_do(
if(x > wmd->lifetime) {
lifefac = x - wmd->lifetime;
-
+
if(lifefac > wmd->damp) lifefac = 0.0;
else lifefac =
- (float)(wmd->height * (1.0 - sqrt(lifefac / wmd->damp)));
+ (float)(wmd->height * (1.0 - sqrt(lifefac / wmd->damp)));
}
}
if(wmd->texture) {
tex_co = MEM_mallocN(sizeof(*tex_co) * numVerts,
- "waveModifier_do tex_co");
+ "waveModifier_do tex_co");
wavemod_get_texture_coords(wmd, ob, dm, vertexCos, tex_co, numVerts);
}
@@ -4509,6 +5252,8 @@ static void waveModifier_do(
float x = co[0] - wmd->startx;
float y = co[1] - wmd->starty;
float amplit= 0.0f;
+ float dist = 0.0f;
+ float falloff_fac = 0.0f;
TexResult texres;
MDeformWeight *def_weight = NULL;
@@ -4531,32 +5276,54 @@ static void waveModifier_do(
get_texture_value(wmd->texture, tex_co[i], &texres);
}
+ /*get dist*/
+ if(wmd->flag & MOD_WAVE_X) {
+ if(wmd->flag & MOD_WAVE_Y){
+ dist = (float)sqrt(x*x + y*y);
+ }
+ else{
+ dist = fabs(x);
+ }
+ }
+ else if(wmd->flag & MOD_WAVE_Y) {
+ dist = fabs(y);
+ }
+
+ falloff_fac = (1.0-(dist / wmd->falloff));
+ CLAMP(falloff_fac,0,1);
if(wmd->flag & MOD_WAVE_X) {
if(wmd->flag & MOD_WAVE_Y) amplit = (float)sqrt(x*x + y*y);
else amplit = x;
}
- else if(wmd->flag & MOD_WAVE_Y)
+ else if(wmd->flag & MOD_WAVE_Y)
amplit= y;
-
+
/* this way it makes nice circles */
amplit -= (ctime - wmd->timeoffs) * wmd->speed;
if(wmd->flag & MOD_WAVE_CYCL) {
amplit = (float)fmod(amplit - wmd->width, 2.0 * wmd->width)
- + wmd->width;
+ + wmd->width;
}
/* GAUSSIAN */
if(amplit > -wmd->width && amplit < wmd->width) {
amplit = amplit * wmd->narrow;
amplit = (float)(1.0 / exp(amplit * amplit) - minfac);
+
+ /*apply texture*/
if(wmd->texture)
amplit = amplit * texres.tin;
+ /*apply weight*/
if(def_weight)
amplit = amplit * def_weight->weight;
+ /*apply falloff*/
+ if (wmd->falloff > 0)
+ amplit = amplit * falloff_fac;
+
if(mvert) {
/* move along normals */
if(wmd->flag & MOD_WAVE_NORM_X) {
@@ -4581,8 +5348,8 @@ static void waveModifier_do(
}
static void waveModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm;
WaveModifierData *wmd = (WaveModifierData *)md;
@@ -4604,15 +5371,15 @@ static void waveModifier_deformVerts(
}
static void waveModifier_deformVertsEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm;
WaveModifierData *wmd = (WaveModifierData *)md;
if(!wmd->texture && !wmd->defgrp_name[0] && !(wmd->flag & MOD_WAVE_NORM))
dm = derivedData;
- else if(derivedData) dm = derivedData;
+ else if(derivedData) dm = CDDM_copy(derivedData);
else dm = CDDM_from_editmesh(editData, ob->data);
if(wmd->flag & MOD_WAVE_NORM) {
@@ -4662,9 +5429,9 @@ static int armatureModifier_isDisabled(ModifierData *md)
}
static void armatureModifier_foreachObjectLink(
- ModifierData *md, Object *ob,
- void (*walk)(void *userData, Object *ob, Object **obpoin),
- void *userData)
+ ModifierData *md, Object *ob,
+ void (*walk)(void *userData, Object *ob, Object **obpoin),
+ void *userData)
{
ArmatureModifierData *amd = (ArmatureModifierData*) md;
@@ -4672,8 +5439,8 @@ static void armatureModifier_foreachObjectLink(
}
static void armatureModifier_updateDepgraph(
- ModifierData *md, DagForest *forest, Object *ob,
- DagNode *obNode)
+ ModifierData *md, DagForest *forest, Object *ob,
+ DagNode *obNode)
{
ArmatureModifierData *amd = (ArmatureModifierData*) md;
@@ -4681,21 +5448,21 @@ static void armatureModifier_updateDepgraph(
DagNode *curNode = dag_get_node(forest, amd->object);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Armature Modifier");
}
}
static void armatureModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
ArmatureModifierData *amd = (ArmatureModifierData*) md;
modifier_vgroup_cache(md, vertexCos); /* if next modifier needs original vertices */
armature_deform_verts(amd->object, ob, derivedData, vertexCos, NULL,
- numVerts, amd->deformflag,
- (float(*)[3])amd->prevCos, amd->defgrp_name);
+ numVerts, amd->deformflag,
+ (float(*)[3])amd->prevCos, amd->defgrp_name);
/* free cache */
if(amd->prevCos) {
MEM_freeN(amd->prevCos);
@@ -4704,8 +5471,8 @@ static void armatureModifier_deformVerts(
}
static void armatureModifier_deformVertsEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
ArmatureModifierData *amd = (ArmatureModifierData*) md;
DerivedMesh *dm = derivedData;
@@ -4713,15 +5480,15 @@ static void armatureModifier_deformVertsEM(
if(!derivedData) dm = CDDM_from_editmesh(editData, ob->data);
armature_deform_verts(amd->object, ob, dm, vertexCos, NULL, numVerts,
- amd->deformflag, NULL, amd->defgrp_name);
+ amd->deformflag, NULL, amd->defgrp_name);
if(!derivedData) dm->release(dm);
}
static void armatureModifier_deformMatricesEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData, float (*vertexCos)[3],
- float (*defMats)[3][3], int numVerts)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3],
+ float (*defMats)[3][3], int numVerts)
{
ArmatureModifierData *amd = (ArmatureModifierData*) md;
DerivedMesh *dm = derivedData;
@@ -4729,7 +5496,7 @@ static void armatureModifier_deformMatricesEM(
if(!derivedData) dm = CDDM_from_editmesh(editData, ob->data);
armature_deform_verts(amd->object, ob, dm, vertexCos, defMats, numVerts,
- amd->deformflag, NULL, amd->defgrp_name);
+ amd->deformflag, NULL, amd->defgrp_name);
if(!derivedData) dm->release(dm);
}
@@ -4784,9 +5551,9 @@ static int hookModifier_isDisabled(ModifierData *md)
}
static void hookModifier_foreachObjectLink(
- ModifierData *md, Object *ob,
- void (*walk)(void *userData, Object *ob, Object **obpoin),
- void *userData)
+ ModifierData *md, Object *ob,
+ void (*walk)(void *userData, Object *ob, Object **obpoin),
+ void *userData)
{
HookModifierData *hmd = (HookModifierData*) md;
@@ -4794,20 +5561,21 @@ static void hookModifier_foreachObjectLink(
}
static void hookModifier_updateDepgraph(ModifierData *md, DagForest *forest,
- Object *ob, DagNode *obNode)
+ Object *ob, DagNode *obNode)
{
HookModifierData *hmd = (HookModifierData*) md;
if (hmd->object) {
DagNode *curNode = dag_get_node(forest, hmd->object);
- dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA);
+ dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA,
+ "Hook Modifier");
}
}
static void hookModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
HookModifierData *hmd = (HookModifierData*) md;
float vec[3], mat[4][4];
@@ -4816,7 +5584,7 @@ static void hookModifier_deformVerts(
Mat4Invert(ob->imat, ob->obmat);
Mat4MulSerie(mat, ob->imat, hmd->object->obmat, hmd->parentinv,
- NULL, NULL, NULL, NULL, NULL);
+ NULL, NULL, NULL, NULL, NULL);
/* vertex indices? */
if(hmd->indexar) {
@@ -4824,24 +5592,24 @@ static void hookModifier_deformVerts(
int index = hmd->indexar[i];
/* This should always be true and I don't generally like
- * "paranoid" style code like this, but old files can have
- * indices that are out of range because old blender did
- * not correct them on exit editmode. - zr
- */
+ * "paranoid" style code like this, but old files can have
+ * indices that are out of range because old blender did
+ * not correct them on exit editmode. - zr
+ */
if(index < numVerts) {
float *co = vertexCos[index];
float fac = hmd->force;
/* if DerivedMesh is present and has original index data,
- * use it
- */
+ * use it
+ */
if(dm && dm->getVertData(dm, 0, CD_ORIGINDEX)) {
int j;
int orig_index;
for(j = 0; j < numVerts; ++j) {
fac = hmd->force;
orig_index = *(int *)dm->getVertData(dm, j,
- CD_ORIGINDEX);
+ CD_ORIGINDEX);
if(orig_index == index) {
co = vertexCos[j];
if(hmd->falloff != 0.0) {
@@ -4885,44 +5653,44 @@ static void hookModifier_deformVerts(
if(dm)
if(dm->getVertData(dm, 0, CD_MDEFORMVERT)) {
+ use_dverts = 1;
+ maxVerts = dm->getNumVerts(dm);
+ } else use_dverts = 0;
+ else if(me->dvert) {
use_dverts = 1;
- maxVerts = dm->getNumVerts(dm);
+ maxVerts = me->totvert;
} else use_dverts = 0;
- else if(me->dvert) {
- use_dverts = 1;
- maxVerts = me->totvert;
- } else use_dverts = 0;
- if(curdef && use_dverts) {
- MDeformVert *dvert = me->dvert;
- int i, j;
+ if(curdef && use_dverts) {
+ MDeformVert *dvert = me->dvert;
+ int i, j;
- for(i = 0; i < maxVerts; i++, dvert++) {
- if(dm) dvert = dm->getVertData(dm, i, CD_MDEFORMVERT);
- for(j = 0; j < dvert->totweight; j++) {
- if(dvert->dw[j].def_nr == index) {
- float fac = hmd->force*dvert->dw[j].weight;
- float *co = vertexCos[i];
+ for(i = 0; i < maxVerts; i++, dvert++) {
+ if(dm) dvert = dm->getVertData(dm, i, CD_MDEFORMVERT);
+ for(j = 0; j < dvert->totweight; j++) {
+ if(dvert->dw[j].def_nr == index) {
+ float fac = hmd->force*dvert->dw[j].weight;
+ float *co = vertexCos[i];
- if(hmd->falloff != 0.0) {
- float len = VecLenf(co, hmd->cent);
- if(len > hmd->falloff) fac = 0.0;
- else if(len > 0.0)
- fac *= sqrt(1.0 - len / hmd->falloff);
- }
+ if(hmd->falloff != 0.0) {
+ float len = VecLenf(co, hmd->cent);
+ if(len > hmd->falloff) fac = 0.0;
+ else if(len > 0.0)
+ fac *= sqrt(1.0 - len / hmd->falloff);
+ }
- VecMat4MulVecfl(vec, mat, co);
- VecLerpf(co, co, vec, fac);
+ VecMat4MulVecfl(vec, mat, co);
+ VecLerpf(co, co, vec, fac);
+ }
}
}
}
- }
}
}
static void hookModifier_deformVertsEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm = derivedData;
@@ -4936,12 +5704,322 @@ static void hookModifier_deformVertsEM(
/* Softbody */
static void softbodyModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
sbObjectStep(ob, (float)G.scene->r.cfra, vertexCos, numVerts);
}
+static int softbodyModifier_dependsOnTime(ModifierData *md)
+{
+ return 1;
+}
+
+
+/* Cloth */
+
+static void clothModifier_initData(ModifierData *md)
+{
+ ClothModifierData *clmd = (ClothModifierData*) md;
+
+ clmd->sim_parms = MEM_callocN(sizeof(ClothSimSettings), "cloth sim parms");
+ clmd->coll_parms = MEM_callocN(sizeof(ClothCollSettings), "cloth coll parms");
+ clmd->point_cache = BKE_ptcache_add();
+
+ /* check for alloc failing */
+ if(!clmd->sim_parms || !clmd->coll_parms || !clmd->point_cache)
+ return;
+
+ cloth_init (clmd);
+}
+
+static DerivedMesh *clothModifier_applyModifier(ModifierData *md, Object *ob,
+ DerivedMesh *derivedData, int useRenderParams, int isFinalCalc)
+{
+ ClothModifierData *clmd = (ClothModifierData*) md;
+ DerivedMesh *result=NULL;
+
+ /* check for alloc failing */
+ if(!clmd->sim_parms || !clmd->coll_parms)
+ {
+ clothModifier_initData(md);
+
+ if(!clmd->sim_parms || !clmd->coll_parms)
+ return derivedData;
+ }
+
+ result = clothModifier_do(clmd, ob, derivedData, useRenderParams, isFinalCalc);
+
+ if(result)
+ {
+ CDDM_calc_normals(result);
+ return result;
+ }
+ return derivedData;
+}
+
+static void clothModifier_updateDepgraph(
+ ModifierData *md, DagForest *forest, Object *ob,
+ DagNode *obNode)
+{
+ ClothModifierData *clmd = (ClothModifierData*) md;
+
+ Base *base;
+
+ if(clmd)
+ {
+ for(base = G.scene->base.first; base; base= base->next)
+ {
+ Object *ob1= base->object;
+ if(ob1 != ob)
+ {
+ CollisionModifierData *coll_clmd = (CollisionModifierData *)modifiers_findByType(ob1, eModifierType_Collision);
+ if(coll_clmd)
+ {
+ DagNode *curNode = dag_get_node(forest, ob1);
+ dag_add_relation(forest, curNode, obNode, DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Cloth Collision");
+ }
+ }
+ }
+ }
+}
+
+CustomDataMask clothModifier_requiredDataMask(ModifierData *md)
+{
+ CustomDataMask dataMask = 0;
+
+ /* ask for vertexgroups if we need them */
+ dataMask |= (1 << CD_MDEFORMVERT);
+
+ return dataMask;
+}
+
+static void clothModifier_copyData(ModifierData *md, ModifierData *target)
+{
+ ClothModifierData *clmd = (ClothModifierData*) md;
+ ClothModifierData *tclmd = (ClothModifierData*) target;
+
+ if(tclmd->sim_parms)
+ MEM_freeN(tclmd->sim_parms);
+ if(tclmd->coll_parms)
+ MEM_freeN(tclmd->coll_parms);
+ if(tclmd->point_cache)
+ BKE_ptcache_free(tclmd->point_cache);
+
+ tclmd->sim_parms = MEM_dupallocN(clmd->sim_parms);
+ tclmd->coll_parms = MEM_dupallocN(clmd->coll_parms);
+ tclmd->point_cache = BKE_ptcache_copy(clmd->point_cache);
+ tclmd->clothObject = NULL;
+}
+
+static int clothModifier_dependsOnTime(ModifierData *md)
+{
+ return 1;
+}
+
+static void clothModifier_freeData(ModifierData *md)
+{
+ ClothModifierData *clmd = (ClothModifierData*) md;
+
+ if (clmd)
+ {
+ if(G.rt > 0)
+ printf("clothModifier_freeData\n");
+
+ cloth_free_modifier_extern (clmd);
+
+ if(clmd->sim_parms)
+ MEM_freeN(clmd->sim_parms);
+ if(clmd->coll_parms)
+ MEM_freeN(clmd->coll_parms);
+ if(clmd->point_cache)
+ BKE_ptcache_free(clmd->point_cache);
+ }
+}
+
+/* Collision */
+
+static void collisionModifier_initData(ModifierData *md)
+{
+ CollisionModifierData *collmd = (CollisionModifierData*) md;
+
+ collmd->x = NULL;
+ collmd->xnew = NULL;
+ collmd->current_x = NULL;
+ collmd->current_xnew = NULL;
+ collmd->current_v = NULL;
+ collmd->time = -1;
+ collmd->numverts = 0;
+ collmd->bvhtree = NULL;
+}
+
+static void collisionModifier_freeData(ModifierData *md)
+{
+ CollisionModifierData *collmd = (CollisionModifierData*) md;
+
+ if (collmd)
+ {
+ if(collmd->bvhtree)
+ BLI_bvhtree_free(collmd->bvhtree);
+ if(collmd->x)
+ MEM_freeN(collmd->x);
+ if(collmd->xnew)
+ MEM_freeN(collmd->xnew);
+ if(collmd->current_x)
+ MEM_freeN(collmd->current_x);
+ if(collmd->current_xnew)
+ MEM_freeN(collmd->current_xnew);
+ if(collmd->current_v)
+ MEM_freeN(collmd->current_v);
+ if(collmd->mfaces)
+ MEM_freeN(collmd->mfaces);
+
+ collmd->x = NULL;
+ collmd->xnew = NULL;
+ collmd->current_x = NULL;
+ collmd->current_xnew = NULL;
+ collmd->current_v = NULL;
+ collmd->time = -1;
+ collmd->numverts = 0;
+ collmd->bvhtree = NULL;
+ collmd->mfaces = NULL;
+ }
+}
+
+static int collisionModifier_dependsOnTime(ModifierData *md)
+{
+ return 1;
+}
+
+static void collisionModifier_deformVerts(
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
+{
+ CollisionModifierData *collmd = (CollisionModifierData*) md;
+ DerivedMesh *dm = NULL;
+ float current_time = 0;
+ unsigned int numverts = 0, i = 0;
+ MVert *tempVert = NULL;
+
+ /* if possible use/create DerivedMesh */
+ if(derivedData) dm = CDDM_copy(derivedData);
+ else if(ob->type==OB_MESH) dm = CDDM_from_mesh(ob->data, ob);
+
+ if(!ob->pd)
+ {
+ printf("collisionModifier_deformVerts: Should not happen!\n");
+ return;
+ }
+
+ if(dm)
+ {
+ CDDM_apply_vert_coords(dm, vertexCos);
+ CDDM_calc_normals(dm);
+
+ current_time = bsystem_time ( ob, ( float ) G.scene->r.cfra, 0.0 );
+
+ if(G.rt > 0)
+ printf("current_time %f, collmd->time %f\n", current_time, collmd->time);
+
+ numverts = dm->getNumVerts ( dm );
+
+ if((current_time > collmd->time)|| (BKE_ptcache_get_continue_physics()))
+ {
+ // check if mesh has changed
+ if(collmd->x && (numverts != collmd->numverts))
+ collisionModifier_freeData((ModifierData *)collmd);
+
+ if(collmd->time == -1) // first time
+ {
+ collmd->x = dm->dupVertArray(dm); // frame start position
+
+ for ( i = 0; i < numverts; i++ )
+ {
+ // we save global positions
+ Mat4MulVecfl ( ob->obmat, collmd->x[i].co );
+ }
+
+ collmd->xnew = MEM_dupallocN(collmd->x); // frame end position
+ collmd->current_x = MEM_dupallocN(collmd->x); // inter-frame
+ collmd->current_xnew = MEM_dupallocN(collmd->x); // inter-frame
+ collmd->current_v = MEM_dupallocN(collmd->x); // inter-frame
+
+ collmd->numverts = numverts;
+
+ collmd->mfaces = dm->dupFaceArray(dm);
+ collmd->numfaces = dm->getNumFaces(dm);
+
+ // create bounding box hierarchy
+ collmd->bvhtree = bvhtree_build_from_mvert(collmd->mfaces, collmd->numfaces, collmd->x, numverts, ob->pd->pdef_sboft);
+
+ collmd->time = current_time;
+ }
+ else if(numverts == collmd->numverts)
+ {
+ // put positions to old positions
+ tempVert = collmd->x;
+ collmd->x = collmd->xnew;
+ collmd->xnew = tempVert;
+
+ memcpy(collmd->xnew, dm->getVertArray(dm), numverts*sizeof(MVert));
+
+ for ( i = 0; i < numverts; i++ )
+ {
+ // we save global positions
+ Mat4MulVecfl ( ob->obmat, collmd->xnew[i].co );
+ }
+
+ memcpy(collmd->current_xnew, collmd->x, numverts*sizeof(MVert));
+ memcpy(collmd->current_x, collmd->x, numverts*sizeof(MVert));
+
+ /* check if GUI setting has changed for bvh */
+ if(collmd->bvhtree)
+ {
+ if(ob->pd->pdef_sboft != BLI_bvhtree_getepsilon(collmd->bvhtree))
+ {
+ BLI_bvhtree_free(collmd->bvhtree);
+ collmd->bvhtree = bvhtree_build_from_mvert(collmd->mfaces, collmd->numfaces, collmd->current_x, numverts, ob->pd->pdef_sboft);
+ }
+
+ }
+
+ /* happens on file load (ONLY when i decomment changes in readfile.c) */
+ if(!collmd->bvhtree)
+ {
+ collmd->bvhtree = bvhtree_build_from_mvert(collmd->mfaces, collmd->numfaces, collmd->current_x, numverts, ob->pd->pdef_sboft);
+ }
+ else
+ {
+ // recalc static bounding boxes
+ bvhtree_update_from_mvert ( collmd->bvhtree, collmd->mfaces, collmd->numfaces, collmd->current_x, collmd->current_xnew, collmd->numverts, 1 );
+ }
+
+ collmd->time = current_time;
+ }
+ else if(numverts != collmd->numverts)
+ {
+ collisionModifier_freeData((ModifierData *)collmd);
+ }
+
+ }
+ else if(current_time < collmd->time)
+ {
+ collisionModifier_freeData((ModifierData *)collmd);
+ }
+ else
+ {
+ if(numverts != collmd->numverts)
+ {
+ collisionModifier_freeData((ModifierData *)collmd);
+ }
+ }
+ }
+
+ if(dm)
+ dm->release(dm);
+}
+
+
/* Boolean */
static void booleanModifier_copyData(ModifierData *md, ModifierData *target)
@@ -4961,9 +6039,9 @@ static int booleanModifier_isDisabled(ModifierData *md)
}
static void booleanModifier_foreachObjectLink(
- ModifierData *md, Object *ob,
- void (*walk)(void *userData, Object *ob, Object **obpoin),
- void *userData)
+ ModifierData *md, Object *ob,
+ void (*walk)(void *userData, Object *ob, Object **obpoin),
+ void *userData)
{
BooleanModifierData *bmd = (BooleanModifierData*) md;
@@ -4971,8 +6049,8 @@ static void booleanModifier_foreachObjectLink(
}
static void booleanModifier_updateDepgraph(
- ModifierData *md, DagForest *forest, Object *ob,
- DagNode *obNode)
+ ModifierData *md, DagForest *forest, Object *ob,
+ DagNode *obNode)
{
BooleanModifierData *bmd = (BooleanModifierData*) md;
@@ -4980,32 +6058,32 @@ static void booleanModifier_updateDepgraph(
DagNode *curNode = dag_get_node(forest, bmd->object);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Boolean Modifier");
}
}
static DerivedMesh *booleanModifier_applyModifier(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- int useRenderParams, int isFinalCalc)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
{
// XXX doesn't handle derived data
BooleanModifierData *bmd = (BooleanModifierData*) md;
/* we do a quick sanity check */
if(((Mesh *)ob->data)->totface > 3
- && bmd->object && ((Mesh *)bmd->object->data)->totface > 3) {
+ && bmd->object && ((Mesh *)bmd->object->data)->totface > 3) {
DerivedMesh *result = NewBooleanDerivedMesh(bmd->object, ob,
- 1 + bmd->operation);
+ 1 + bmd->operation);
/* if new mesh returned, return it; otherwise there was
- * an error, so delete the modifier object */
+ * an error, so delete the modifier object */
if(result)
return result;
else
bmd->object = NULL;
- }
+ }
- return derivedData;
+ return derivedData;
}
/* Particles */
@@ -5026,7 +6104,6 @@ static void particleSystemModifier_freeData(ModifierData *md)
psmd->dm=0;
}
- psmd->psys->flag &= ~PSYS_ENABLED;
psmd->psys->flag |= PSYS_DELETE;
}
static void particleSystemModifier_copyData(ModifierData *md, ModifierData *target)
@@ -5035,6 +6112,7 @@ static void particleSystemModifier_copyData(ModifierData *md, ModifierData *targ
ParticleSystemModifierData *tpsmd= (ParticleSystemModifierData*) target;
tpsmd->dm = 0;
+ tpsmd->totdmvert = tpsmd->totdmedge = tpsmd->totdmface = 0;
//tpsmd->facepa = 0;
tpsmd->flag = psmd->flag;
/* need to keep this to recognise a bit later in copy_object */
@@ -5056,7 +6134,7 @@ CustomDataMask particleSystemModifier_requiredDataMask(ModifierData *md)
}
/* particles only need this if they are after a non deform modifier, and
- * the modifier stack will only create them in that case. */
+ * the modifier stack will only create them in that case. */
dataMask |= CD_MASK_ORIGSPACE;
dataMask |= CD_MASK_ORCO;
@@ -5088,12 +6166,13 @@ static int is_last_displist(Object *ob)
}
/* saves the current emitter state for a particle system and calculates particles */
static void particleSystemModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm = derivedData;
ParticleSystemModifierData *psmd= (ParticleSystemModifierData*) md;
ParticleSystem * psys=0;
+ Mesh *me;
int needsFree=0;
if(ob->particlesystem.first)
@@ -5101,6 +6180,14 @@ static void particleSystemModifier_deformVerts(
else
return;
+ /* multires check */
+ if(ob->type == OB_MESH) {
+ me= (Mesh*)ob->data;
+ if(me->mr && me->mr->current != 1)
+ modifier_setError(md,
+ "Particles only supported on first multires level.");
+ }
+
if(!psys_check_enabled(ob, psys))
return;
@@ -5151,6 +6238,7 @@ static void particleSystemModifier_deformVerts(
/* make new dm */
psmd->dm=CDDM_copy(dm);
+ CDDM_apply_vert_coords(psmd->dm, vertexCos);
CDDM_calc_normals(psmd->dm);
if(needsFree){
@@ -5163,8 +6251,8 @@ static void particleSystemModifier_deformVerts(
/* report change in mesh structure */
if(psmd->dm->getNumVerts(psmd->dm)!=psmd->totdmvert ||
- psmd->dm->getNumEdges(psmd->dm)!=psmd->totdmedge ||
- psmd->dm->getNumFaces(psmd->dm)!=psmd->totdmface){
+ psmd->dm->getNumEdges(psmd->dm)!=psmd->totdmedge ||
+ psmd->dm->getNumFaces(psmd->dm)!=psmd->totdmface){
/* in file read dm hasn't really changed but just wasn't saved in file */
psys->recalc |= PSYS_RECALC_HAIR;
@@ -5174,13 +6262,13 @@ static void particleSystemModifier_deformVerts(
psmd->totdmvert= psmd->dm->getNumVerts(psmd->dm);
psmd->totdmedge= psmd->dm->getNumEdges(psmd->dm);
psmd->totdmface= psmd->dm->getNumFaces(psmd->dm);
- }
+ }
- if(psys){
- particle_system_update(ob,psys);
- psmd->flag |= eParticleSystemFlag_psys_updated;
- psmd->flag &= ~eParticleSystemFlag_DM_changed;
- }
+ if(psys){
+ particle_system_update(ob,psys);
+ psmd->flag |= eParticleSystemFlag_psys_updated;
+ psmd->flag &= ~eParticleSystemFlag_DM_changed;
+ }
}
/* disabled particles in editmode for now, until support for proper derivedmesh
@@ -5206,7 +6294,7 @@ static void particleInstanceModifier_initData(ModifierData *md)
ParticleInstanceModifierData *pimd= (ParticleInstanceModifierData*) md;
pimd->flag = eParticleInstanceFlag_Parents|eParticleInstanceFlag_Unborn|
- eParticleInstanceFlag_Alive|eParticleInstanceFlag_Dead;
+ eParticleInstanceFlag_Alive|eParticleInstanceFlag_Dead;
pimd->psys = 1;
}
@@ -5225,7 +6313,7 @@ static int particleInstanceModifier_dependsOnTime(ModifierData *md)
return 0;
}
static void particleInstanceModifier_updateDepgraph(ModifierData *md, DagForest *forest,
- Object *ob, DagNode *obNode)
+ Object *ob, DagNode *obNode)
{
ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData*) md;
@@ -5233,12 +6321,13 @@ static void particleInstanceModifier_updateDepgraph(ModifierData *md, DagForest
DagNode *curNode = dag_get_node(forest, pimd->ob);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
+ DAG_RL_DATA_DATA | DAG_RL_OB_DATA,
+ "Particle Instance Modifier");
}
}
static void particleInstanceModifier_foreachObjectLink(ModifierData *md, Object *ob,
- ObjectWalkFunc walk, void *userData)
+ ObjectWalkFunc walk, void *userData)
{
ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData*) md;
@@ -5246,8 +6335,8 @@ static void particleInstanceModifier_foreachObjectLink(ModifierData *md, Object
}
static DerivedMesh * particleInstanceModifier_applyModifier(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- int useRenderParams, int isFinalCalc)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
{
DerivedMesh *dm = derivedData, *result;
ParticleInstanceModifierData *pimd= (ParticleInstanceModifierData*) md;
@@ -5257,7 +6346,7 @@ static DerivedMesh * particleInstanceModifier_applyModifier(
MVert *mvert, *orig_mvert;
int i,totvert, totpart=0, totface, maxvert, maxface, first_particle=0;
short track=ob->trackflag%3, trackneg;
- float max_co=0.0, min_co=0.0, temp_co[3];
+ float max_co=0.0, min_co=0.0, temp_co[3], cross[3];
trackneg=((ob->trackflag>2)?1:0);
@@ -5336,15 +6425,29 @@ static DerivedMesh * particleInstanceModifier_applyModifier(
if(trackneg)
state.time=1.0f-state.time;
psys_get_particle_on_path(pimd->ob,psys,first_particle + i/totvert,&state,1);
+
+ mv->co[0] = 0.0;
+
+ Normalize(state.vel);
+
+ if(state.vel[0] < -0.9999 || state.vel[0] > 0.9999) {
+ state.rot[0] = 1.0;
+ state.rot[1] = state.rot[2] = state.rot[3] = 0.0f;
+ }
+ else {
+ /* a cross product of state.vel and a unit vector in x-direction */
+ cross[0] = 0.0f;
+ cross[1] = -state.vel[2];
+ cross[2] = state.vel[1];
+
+ /* state.vel[0] is the only component surviving from a dot product with a vector in x-direction*/
+ VecRotToQuat(cross,saacos(state.vel[0]),state.rot);
+ }
}
else{
state.time=-1.0;
psys_get_particle_state(pimd->ob,psys,i/totvert,&state,1);
- }
-
- /*displace vertice to path location*/
- if(pimd->flag & eParticleInstanceFlag_Path)
- mv->co[0]=0.0;
+ }
QuatMulVecf(state.rot,mv->co);
VECADD(mv->co,mv->co,state.co);
@@ -5402,8 +6505,8 @@ static DerivedMesh * particleInstanceModifier_applyModifier(
return result;
}
static DerivedMesh *particleInstanceModifier_applyModifierEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData)
{
return particleInstanceModifier_applyModifier(md, ob, derivedData, 0, 1);
}
@@ -5429,6 +6532,8 @@ static void explodeModifier_copyData(ModifierData *md, ModifierData *target)
temd->facepa = 0;
temd->flag = emd->flag;
+ temd->protect = emd->protect;
+ temd->vgroup = emd->vgroup;
}
static int explodeModifier_dependsOnTime(ModifierData *md)
{
@@ -5445,25 +6550,9 @@ CustomDataMask explodeModifier_requiredDataMask(ModifierData *md)
return dataMask;
}
-/* this should really be put somewhere permanently */
-static float vert_weight(MDeformVert *dvert, int group)
-{
- MDeformWeight *dw;
- int i;
-
- if(dvert) {
- dw= dvert->dw;
- for(i= dvert->totweight; i>0; i--, dw++) {
- if(dw->def_nr == group) return dw->weight;
- if(i==1) break; /*otherwise dw will point to somewhere it shouldn't*/
- }
- }
- return 0.0;
-}
-
static void explodeModifier_createFacepa(ExplodeModifierData *emd,
- ParticleSystemModifierData *psmd,
- Object *ob, DerivedMesh *dm)
+ ParticleSystemModifierData *psmd,
+ Object *ob, DerivedMesh *dm)
{
ParticleSystem *psys=psmd->psys;
MFace *fa=0, *mface=0;
@@ -5504,7 +6593,7 @@ static void explodeModifier_createFacepa(ExplodeModifierData *emd,
for(i=0; i<totvert; i++){
val = BLI_frand();
val = (1.0f-emd->protect)*val + emd->protect*0.5f;
- if(val < vert_weight(dvert+i,emd->vgroup-1))
+ if(val < deformvert_get_weight(dvert+i,emd->vgroup-1))
vertpa[i] = -1;
}
}
@@ -5513,7 +6602,7 @@ static void explodeModifier_createFacepa(ExplodeModifierData *emd,
/* make tree of emitter locations */
tree=BLI_kdtree_new(totpart);
for(p=0,pa=psys->particles; p<totpart; p++,pa++){
- psys_particle_on_dm(ob,psmd->dm,psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,0,0,0,0,0);
+ psys_particle_on_dm(psmd->dm,psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,0,0,0,0,0);
BLI_kdtree_insert(tree, p, co, NULL);
}
BLI_kdtree_balance(tree);
@@ -5549,20 +6638,29 @@ static void explodeModifier_createFacepa(ExplodeModifierData *emd,
if(vertpa) MEM_freeN(vertpa);
BLI_kdtree_free(tree);
}
+
+static int edgesplit_get(EdgeHash *edgehash, int v1, int v2)
+{
+ return GET_INT_FROM_POINTER(BLI_edgehash_lookup(edgehash, v1, v2));
+}
+
static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, DerivedMesh *dm){
DerivedMesh *splitdm;
MFace *mf=0,*df1=0,*df2=0,*df3=0;
MFace *mface=CDDM_get_faces(dm);
MVert *dupve, *mv;
+ EdgeHash *edgehash;
+ EdgeHashIterator *ehi;
int totvert=dm->getNumVerts(dm);
int totface=dm->getNumFaces(dm);
- int *edgesplit = MEM_callocN(sizeof(int)*totvert*totvert,"explode_edgesplit");
- int *facesplit = MEM_callocN(sizeof(int)*totface,"explode_edgesplit");
+ int *facesplit = MEM_callocN(sizeof(int)*totface,"explode_facesplit");
int *vertpa = MEM_callocN(sizeof(int)*totvert,"explode_vertpa2");
int *facepa = emd->facepa;
int *fs, totesplit=0,totfsplit=0,totin=0,curdupvert=0,curdupface=0,curdupin=0;
- int i,j,v1,v2,v3,v4;
+ int i,j,v1,v2,v3,v4,esplit;
+
+ edgehash= BLI_edgehash_new();
/* recreate vertpa from facepa calculation */
for (i=0,mf=mface; i<totface; i++,mf++) {
@@ -5582,22 +6680,22 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
v4=vertpa[mf->v4];
if(v1!=v2){
- edgesplit[mf->v1*totvert+mf->v2]=edgesplit[mf->v2*totvert+mf->v1]=1;
+ BLI_edgehash_insert(edgehash, mf->v1, mf->v2, NULL);
(*fs)++;
}
if(v2!=v3){
- edgesplit[mf->v2*totvert+mf->v3]=edgesplit[mf->v3*totvert+mf->v2]=1;
+ BLI_edgehash_insert(edgehash, mf->v2, mf->v3, NULL);
(*fs)++;
}
if(v3!=v4){
- edgesplit[mf->v3*totvert+mf->v4]=edgesplit[mf->v4*totvert+mf->v3]=1;
+ BLI_edgehash_insert(edgehash, mf->v3, mf->v4, NULL);
(*fs)++;
}
if(v1!=v4){
- edgesplit[mf->v1*totvert+mf->v4]=edgesplit[mf->v4*totvert+mf->v1]=1;
+ BLI_edgehash_insert(edgehash, mf->v1, mf->v4, NULL);
(*fs)++;
}
@@ -5606,28 +6704,29 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
*fs=1;
else if(v1!=v2){
if(v1!=v4)
- edgesplit[mf->v2*totvert+mf->v3]=edgesplit[mf->v3*totvert+mf->v2]=1;
+ BLI_edgehash_insert(edgehash, mf->v2, mf->v3, NULL);
else
- edgesplit[mf->v3*totvert+mf->v4]=edgesplit[mf->v4*totvert+mf->v3]=1;
+ BLI_edgehash_insert(edgehash, mf->v3, mf->v4, NULL);
}
else{
if(v1!=v4)
- edgesplit[mf->v1*totvert+mf->v2]=edgesplit[mf->v2*totvert+mf->v1]=1;
+ BLI_edgehash_insert(edgehash, mf->v1, mf->v2, NULL);
else
- edgesplit[mf->v1*totvert+mf->v4]=edgesplit[mf->v4*totvert+mf->v1]=1;
+ BLI_edgehash_insert(edgehash, mf->v1, mf->v4, NULL);
}
}
}
}
/* count splits & reindex */
+ ehi= BLI_edgehashIterator_new(edgehash);
totesplit=totvert;
- for(j=0; j<totvert; j++){
- for(i=j+1; i<totvert; i++){
- if(edgesplit[j*totvert+i])
- edgesplit[j*totvert+i]=edgesplit[i*totvert+j]=totesplit++;
- }
+ for(; !BLI_edgehashIterator_isDone(ehi); BLI_edgehashIterator_step(ehi)) {
+ BLI_edgehashIterator_setValue(ehi, SET_INT_IN_POINTER(totesplit));
+ totesplit++;
}
+ BLI_edgehashIterator_free(ehi);
+
/* count new faces due to splitting */
for(i=0,fs=facesplit; i<totface; i++,fs++){
if(*fs==1)
@@ -5675,23 +6774,23 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
/* create new verts */
curdupvert=totvert;
- for(j=0; j<totvert; j++){
- for(i=j+1; i<totvert; i++){
- if(edgesplit[j*totvert+i]){
- mv=CDDM_get_vert(splitdm,j);
- dupve=CDDM_get_vert(splitdm,edgesplit[j*totvert+i]);
+ ehi= BLI_edgehashIterator_new(edgehash);
+ for(; !BLI_edgehashIterator_isDone(ehi); BLI_edgehashIterator_step(ehi)) {
+ BLI_edgehashIterator_getKey(ehi, &i, &j);
+ esplit= GET_INT_FROM_POINTER(BLI_edgehashIterator_getValue(ehi));
+ mv=CDDM_get_vert(splitdm,j);
+ dupve=CDDM_get_vert(splitdm,esplit);
- DM_copy_vert_data(splitdm,splitdm,j,edgesplit[j*totvert+i],1);
+ DM_copy_vert_data(splitdm,splitdm,j,esplit,1);
- *dupve=*mv;
+ *dupve=*mv;
- mv=CDDM_get_vert(splitdm,i);
+ mv=CDDM_get_vert(splitdm,i);
- VECADD(dupve->co,dupve->co,mv->co);
- VecMulf(dupve->co,0.5);
- }
- }
+ VECADD(dupve->co,dupve->co,mv->co);
+ VecMulf(dupve->co,0.5);
}
+ BLI_edgehashIterator_free(ehi);
/* create new faces */
curdupface=totface;
@@ -5712,14 +6811,14 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
curdupface++;
if(v1==v2){
- df1->v1=edgesplit[mf->v1*totvert+mf->v4];
- df1->v2=edgesplit[mf->v2*totvert+mf->v3];
+ df1->v1=edgesplit_get(edgehash, mf->v1, mf->v4);
+ df1->v2=edgesplit_get(edgehash, mf->v2, mf->v3);
mf->v3=df1->v2;
mf->v4=df1->v1;
}
else{
- df1->v1=edgesplit[mf->v1*totvert+mf->v2];
- df1->v4=edgesplit[mf->v3*totvert+mf->v4];
+ df1->v1=edgesplit_get(edgehash, mf->v1, mf->v2);
+ df1->v4=edgesplit_get(edgehash, mf->v3, mf->v4);
mf->v2=df1->v1;
mf->v3=df1->v4;
}
@@ -5742,8 +6841,8 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
if(v1!=v2){
if(v1!=v4){
- df1->v1=edgesplit[mf->v1*totvert+mf->v4];
- df1->v2=edgesplit[mf->v1*totvert+mf->v2];
+ df1->v1=edgesplit_get(edgehash, mf->v1, mf->v4);
+ df1->v2=edgesplit_get(edgehash, mf->v1, mf->v2);
df2->v1=df1->v3=mf->v2;
df2->v3=df1->v4=mf->v4;
df2->v2=mf->v3;
@@ -5756,8 +6855,8 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
facepa[i]=v1;
}
else{
- df1->v2=edgesplit[mf->v1*totvert+mf->v2];
- df1->v3=edgesplit[mf->v2*totvert+mf->v3];
+ df1->v2=edgesplit_get(edgehash, mf->v1, mf->v2);
+ df1->v3=edgesplit_get(edgehash, mf->v2, mf->v3);
df1->v4=mf->v3;
df2->v2=mf->v3;
df2->v3=mf->v4;
@@ -5773,8 +6872,8 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
}
else{
if(v1!=v4){
- df1->v3=edgesplit[mf->v3*totvert+mf->v4];
- df1->v4=edgesplit[mf->v1*totvert+mf->v4];
+ df1->v3=edgesplit_get(edgehash, mf->v3, mf->v4);
+ df1->v4=edgesplit_get(edgehash, mf->v1, mf->v4);
df1->v2=mf->v3;
mf->v1=df1->v4;
@@ -5786,8 +6885,8 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
facepa[i]=v4;
}
else{
- df1->v3=edgesplit[mf->v2*totvert+mf->v3];
- df1->v4=edgesplit[mf->v3*totvert+mf->v4];
+ df1->v3=edgesplit_get(edgehash, mf->v2, mf->v3);
+ df1->v4=edgesplit_get(edgehash, mf->v3, mf->v4);
df1->v1=mf->v4;
df1->v2=mf->v2;
df2->v3=mf->v4;
@@ -5823,9 +6922,9 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
curdupface++;
if(v1==v2){
- df2->v1=df1->v1=edgesplit[mf->v1*totvert+mf->v4];
- df3->v1=df1->v2=edgesplit[mf->v2*totvert+mf->v3];
- df3->v3=df2->v2=df1->v3=edgesplit[mf->v3*totvert+mf->v4];
+ df2->v1=df1->v1=edgesplit_get(edgehash, mf->v1, mf->v4);
+ df3->v1=df1->v2=edgesplit_get(edgehash, mf->v2, mf->v3);
+ df3->v3=df2->v2=df1->v3=edgesplit_get(edgehash, mf->v3, mf->v4);
df3->v2=mf->v3;
df2->v3=mf->v4;
df1->v4=df2->v4=df3->v4=0;
@@ -5838,9 +6937,9 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
facepa[curdupface-2]=v4;
}
else if(v2==v3){
- df3->v1=df2->v3=df1->v1=edgesplit[mf->v1*totvert+mf->v4];
- df2->v2=df1->v2=edgesplit[mf->v1*totvert+mf->v2];
- df3->v2=df1->v3=edgesplit[mf->v3*totvert+mf->v4];
+ df3->v1=df2->v3=df1->v1=edgesplit_get(edgehash, mf->v1, mf->v4);
+ df2->v2=df1->v2=edgesplit_get(edgehash, mf->v1, mf->v2);
+ df3->v2=df1->v3=edgesplit_get(edgehash, mf->v3, mf->v4);
df3->v3=mf->v4;
df2->v1=mf->v1;
@@ -5854,9 +6953,9 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
facepa[curdupface-2]=v1;
}
else if(v3==v4){
- df3->v2=df2->v1=df1->v1=edgesplit[mf->v1*totvert+mf->v2];
- df2->v3=df1->v2=edgesplit[mf->v2*totvert+mf->v3];
- df3->v3=df1->v3=edgesplit[mf->v1*totvert+mf->v4];
+ df3->v2=df2->v1=df1->v1=edgesplit_get(edgehash, mf->v1, mf->v2);
+ df2->v3=df1->v2=edgesplit_get(edgehash, mf->v2, mf->v3);
+ df3->v3=df1->v3=edgesplit_get(edgehash, mf->v1, mf->v4);
df3->v1=mf->v1;
df2->v2=mf->v2;
@@ -5870,9 +6969,9 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
facepa[curdupface-2]=v2;
}
else{
- df3->v1=df1->v1=edgesplit[mf->v1*totvert+mf->v2];
- df3->v3=df2->v1=df1->v2=edgesplit[mf->v2*totvert+mf->v3];
- df2->v3=df1->v3=edgesplit[mf->v3*totvert+mf->v4];
+ df3->v1=df1->v1=edgesplit_get(edgehash, mf->v1, mf->v2);
+ df3->v3=df2->v1=df1->v2=edgesplit_get(edgehash, mf->v2, mf->v3);
+ df2->v3=df1->v3=edgesplit_get(edgehash, mf->v3, mf->v4);
df3->v2=mf->v2;
df2->v2=mf->v3;
@@ -5923,11 +7022,11 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
*df3=*mf;
curdupface++;
- df1->v1=edgesplit[mf->v1*totvert+mf->v2];
- df3->v2=df1->v3=edgesplit[mf->v2*totvert+mf->v3];
+ df1->v1=edgesplit_get(edgehash, mf->v1, mf->v2);
+ df3->v2=df1->v3=edgesplit_get(edgehash, mf->v2, mf->v3);
- df2->v1=edgesplit[mf->v1*totvert+mf->v4];
- df3->v4=df2->v3=edgesplit[mf->v3*totvert+mf->v4];
+ df2->v1=edgesplit_get(edgehash, mf->v1, mf->v4);
+ df3->v4=df2->v3=edgesplit_get(edgehash, mf->v3, mf->v4);
df3->v1=df2->v2=df1->v4=curdupin;
@@ -5964,11 +7063,11 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
curdupface++;
if(v2==v3){
- df1->v1=edgesplit[mf->v1*totvert+mf->v2];
- df3->v1=df1->v2=df1->v3=edgesplit[mf->v2*totvert+mf->v3];
- df2->v1=df1->v4=edgesplit[mf->v1*totvert+mf->v4];
+ df1->v1=edgesplit_get(edgehash, mf->v1, mf->v2);
+ df3->v1=df1->v2=df1->v3=edgesplit_get(edgehash, mf->v2, mf->v3);
+ df2->v1=df1->v4=edgesplit_get(edgehash, mf->v1, mf->v4);
- df3->v3=df2->v3=edgesplit[mf->v3*totvert+mf->v4];
+ df3->v3=df2->v3=edgesplit_get(edgehash, mf->v3, mf->v4);
df3->v2=mf->v3;
df3->v4=0;
@@ -5982,11 +7081,11 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
facepa[curdupface-1]=v3;
}
else{
- df3->v1=df2->v1=df1->v2=edgesplit[mf->v1*totvert+mf->v2];
- df2->v4=df1->v3=edgesplit[mf->v3*totvert+mf->v4];
- df1->v4=edgesplit[mf->v1*totvert+mf->v4];
+ df3->v1=df2->v1=df1->v2=edgesplit_get(edgehash, mf->v1, mf->v2);
+ df2->v4=df1->v3=edgesplit_get(edgehash, mf->v3, mf->v4);
+ df1->v4=edgesplit_get(edgehash, mf->v1, mf->v4);
- df3->v3=df2->v2=edgesplit[mf->v2*totvert+mf->v3];
+ df3->v3=df2->v2=edgesplit_get(edgehash, mf->v2, mf->v3);
df3->v4=0;
@@ -6010,7 +7109,7 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
}
}
- MEM_freeN(edgesplit);
+ BLI_edgehash_free(edgehash, NULL);
MEM_freeN(facesplit);
MEM_freeN(vertpa);
@@ -6018,19 +7117,20 @@ static DerivedMesh * explodeModifier_splitEdges(ExplodeModifierData *emd, Derive
}
static DerivedMesh * explodeModifier_explodeMesh(ExplodeModifierData *emd,
- ParticleSystemModifierData *psmd, Object *ob,
- DerivedMesh *to_explode)
+ ParticleSystemModifierData *psmd, Object *ob,
+ DerivedMesh *to_explode)
{
DerivedMesh *explode, *dm=to_explode;
MFace *mf=0;
- MVert *dupvert=0;
ParticleSettings *part=psmd->psys->part;
- ParticleData *pa, *pars=psmd->psys->particles;
+ ParticleData *pa=NULL, *pars=psmd->psys->particles;
ParticleKey state;
+ EdgeHash *vertpahash;
+ EdgeHashIterator *ehi;
float *vertco=0, imat[4][4];
float loc0[3], nor[3];
float timestep, cfra;
- int *facepa=emd->facepa, *vertpa=0;
+ int *facepa=emd->facepa;
int totdup=0,totvert=0,totface=0,totpart=0;
int i, j, v, mindex=0;
@@ -6045,81 +7145,87 @@ static DerivedMesh * explodeModifier_explodeMesh(ExplodeModifierData *emd,
else
cfra=bsystem_time(ob,(float)G.scene->r.cfra,0.0);
- /* table for vertice <-> particle relations (row totpart+1 is for yet unexploded verts) */
- vertpa = MEM_callocN(sizeof(int)*(totpart+1)*totvert, "explode_vertpatab");
- for(i=0; i<(totpart+1)*totvert; i++)
- vertpa[i] = -1;
+ /* hash table for vertice <-> particle relations */
+ vertpahash= BLI_edgehash_new();
for (i=0; i<totface; i++) {
+ /* do mindex + totvert to ensure the vertex index to be the first
+ * with BLI_edgehashIterator_getKey */
if(facepa[i]==totpart || cfra <= (pars+facepa[i])->time)
- mindex = totpart*totvert;
+ mindex = totvert+totpart;
else
- mindex = facepa[i]*totvert;
+ mindex = totvert+facepa[i];
mf=CDDM_get_face(dm,i);
- /*set face vertices to exist in particle group*/
- vertpa[mindex+mf->v1] = 1;
- vertpa[mindex+mf->v2] = 1;
- vertpa[mindex+mf->v3] = 1;
+ /* set face vertices to exist in particle group */
+ BLI_edgehash_insert(vertpahash, mf->v1, mindex, NULL);
+ BLI_edgehash_insert(vertpahash, mf->v2, mindex, NULL);
+ BLI_edgehash_insert(vertpahash, mf->v3, mindex, NULL);
if(mf->v4)
- vertpa[mindex+mf->v4] = 1;
+ BLI_edgehash_insert(vertpahash, mf->v4, mindex, NULL);
}
- /*make new vertice indexes & count total vertices after duplication*/
- for(i=0; i<(totpart+1)*totvert; i++){
- if(vertpa[i] != -1)
- vertpa[i] = totdup++;
+ /* make new vertice indexes & count total vertices after duplication */
+ ehi= BLI_edgehashIterator_new(vertpahash);
+ for(; !BLI_edgehashIterator_isDone(ehi); BLI_edgehashIterator_step(ehi)) {
+ BLI_edgehashIterator_setValue(ehi, SET_INT_IN_POINTER(totdup));
+ totdup++;
}
+ BLI_edgehashIterator_free(ehi);
- /*the final duplicated vertices*/
+ /* the final duplicated vertices */
explode= CDDM_from_template(dm, totdup, 0,totface);
- dupvert= CDDM_get_verts(explode);
+ /*dupvert= CDDM_get_verts(explode);*/
/* getting back to object space */
Mat4Invert(imat,ob->obmat);
psmd->psys->lattice = psys_get_lattice(ob, psmd->psys);
- /*duplicate & displace vertices*/
- for(i=0, pa=pars; i<=totpart; i++, pa++){
- if(i!=totpart){
- psys_particle_on_emitter(ob, psmd,part->from,pa->num,-1,pa->fuv,pa->foffset,loc0,nor,0,0,0,0);
- Mat4MulVecfl(ob->obmat,loc0);
+ /* duplicate & displace vertices */
+ ehi= BLI_edgehashIterator_new(vertpahash);
+ for(; !BLI_edgehashIterator_isDone(ehi); BLI_edgehashIterator_step(ehi)) {
+ MVert source;
+ MVert *dest;
- state.time=cfra;
- psys_get_particle_state(ob,psmd->psys,i,&state,1);
- }
+ /* get particle + vertex from hash */
+ BLI_edgehashIterator_getKey(ehi, &j, &i);
+ i -= totvert;
+ v= GET_INT_FROM_POINTER(BLI_edgehashIterator_getValue(ehi));
- for(j=0; j<totvert; j++){
- v=vertpa[i*totvert+j];
- if(v != -1) {
- MVert source;
- MVert *dest;
+ dm->getVert(dm, j, &source);
+ dest = CDDM_get_vert(explode,v);
- dm->getVert(dm, j, &source);
- dest = CDDM_get_vert(explode,v);
+ DM_copy_vert_data(dm,explode,j,v,1);
+ *dest = source;
- DM_copy_vert_data(dm,explode,j,v,1);
- *dest = source;
+ if(i!=totpart) {
+ /* get particle */
+ pa= pars+i;
- if(i!=totpart){
- vertco=CDDM_get_vert(explode,v)->co;
-
- Mat4MulVecfl(ob->obmat,vertco);
+ /* get particle state */
+ psys_particle_on_emitter(psmd,part->from,pa->num,-1,pa->fuv,pa->foffset,loc0,nor,0,0,0,0);
+ Mat4MulVecfl(ob->obmat,loc0);
- VECSUB(vertco,vertco,loc0);
+ state.time=cfra;
+ psys_get_particle_state(ob,psmd->psys,i,&state,1);
- /* apply rotation, size & location */
- QuatMulVecf(state.rot,vertco);
- VecMulf(vertco,pa->size);
- VECADD(vertco,vertco,state.co);
+ vertco=CDDM_get_vert(explode,v)->co;
+
+ Mat4MulVecfl(ob->obmat,vertco);
- Mat4MulVecfl(imat,vertco);
- }
- }
+ VECSUB(vertco,vertco,loc0);
+
+ /* apply rotation, size & location */
+ QuatMulVecf(state.rot,vertco);
+ VecMulf(vertco,pa->size);
+ VECADD(vertco,vertco,state.co);
+
+ Mat4MulVecfl(imat,vertco);
}
}
+ BLI_edgehashIterator_free(ehi);
/*map new vertices to faces*/
for (i=0; i<totface; i++) {
@@ -6141,15 +7247,15 @@ static DerivedMesh * explodeModifier_explodeMesh(ExplodeModifierData *emd,
orig_v4 = source.v4;
if(facepa[i]!=totpart && cfra <= pa->time)
- mindex = totpart*totvert;
+ mindex = totvert+totpart;
else
- mindex = facepa[i]*totvert;
+ mindex = totvert+facepa[i];
- source.v1 = vertpa[mindex+source.v1];
- source.v2 = vertpa[mindex+source.v2];
- source.v3 = vertpa[mindex+source.v3];
+ source.v1 = edgesplit_get(vertpahash, source.v1, mindex);
+ source.v2 = edgesplit_get(vertpahash, source.v2, mindex);
+ source.v3 = edgesplit_get(vertpahash, source.v3, mindex);
if(source.v4)
- source.v4 = vertpa[mindex+source.v4];
+ source.v4 = edgesplit_get(vertpahash, source.v4, mindex);
DM_copy_face_data(dm,explode,i,i,1);
@@ -6158,9 +7264,10 @@ static DerivedMesh * explodeModifier_explodeMesh(ExplodeModifierData *emd,
test_index_face(mf, &explode->faceData, i, (mf->v4 ? 4 : 3));
}
+ MEM_printmemlist_stats();
/* cleanup */
- if(vertpa) MEM_freeN(vertpa);
+ BLI_edgehash_free(vertpahash, NULL);
/* finalization */
CDDM_calc_edges(explode);
@@ -6186,8 +7293,8 @@ static ParticleSystemModifierData * explodeModifier_findPrecedingParticlesystem(
return psmd;
}
static DerivedMesh * explodeModifier_applyModifier(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- int useRenderParams, int isFinalCalc)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
{
DerivedMesh *dm = derivedData;
ExplodeModifierData *emd= (ExplodeModifierData*) md;
@@ -6198,12 +7305,13 @@ static DerivedMesh * explodeModifier_applyModifier(
if(psys==0 || psys->totpart==0) return derivedData;
if(psys->part==0 || psys->particles==0) return derivedData;
+ if(psmd->dm==0) return derivedData;
/* 1. find faces to be exploded if needed */
if(emd->facepa==0
- || psmd->flag&eParticleSystemFlag_Pars
- || emd->flag&eExplodeFlag_CalcFaces
- || MEM_allocN_len(emd->facepa)/sizeof(int) != dm->getNumFaces(dm)){
+ || psmd->flag&eParticleSystemFlag_Pars
+ || emd->flag&eExplodeFlag_CalcFaces
+ || MEM_allocN_len(emd->facepa)/sizeof(int) != dm->getNumFaces(dm)){
if(psmd->flag & eParticleSystemFlag_Pars)
psmd->flag &= ~eParticleSystemFlag_Pars;
@@ -6211,24 +7319,111 @@ static DerivedMesh * explodeModifier_applyModifier(
emd->flag &= ~eExplodeFlag_CalcFaces;
explodeModifier_createFacepa(emd,psmd,ob,derivedData);
- }
+ }
+
+ /* 2. create new mesh */
+ if(emd->flag & eExplodeFlag_EdgeSplit){
+ int *facepa = emd->facepa;
+ DerivedMesh *splitdm=explodeModifier_splitEdges(emd,dm);
+ DerivedMesh *explode=explodeModifier_explodeMesh(emd,psmd,ob,splitdm);
+
+ MEM_freeN(emd->facepa);
+ emd->facepa=facepa;
+ splitdm->release(splitdm);
+ return explode;
+ }
+ else
+ return explodeModifier_explodeMesh(emd,psmd,ob,derivedData);
+ }
+ return derivedData;
+}
- /* 2. create new mesh */
- if(emd->flag & eExplodeFlag_EdgeSplit){
- int *facepa = emd->facepa;
- DerivedMesh *splitdm=explodeModifier_splitEdges(emd,dm);
- DerivedMesh *explode=explodeModifier_explodeMesh(emd,psmd,ob,splitdm);
+/* Fluidsim */
+static void fluidsimModifier_initData(ModifierData *md)
+{
+ FluidsimModifierData *fluidmd= (FluidsimModifierData*) md;
+
+ fluidsim_init(fluidmd);
+}
+static void fluidsimModifier_freeData(ModifierData *md)
+{
+ FluidsimModifierData *fluidmd= (FluidsimModifierData*) md;
+
+ fluidsim_free(fluidmd);
+}
- MEM_freeN(emd->facepa);
- emd->facepa=facepa;
- splitdm->release(splitdm);
- return explode;
- }
- else
- return explodeModifier_explodeMesh(emd,psmd,ob,derivedData);
+static void fluidsimModifier_copyData(ModifierData *md, ModifierData *target)
+{
+ FluidsimModifierData *fluidmd= (FluidsimModifierData*) md;
+ FluidsimModifierData *tfluidmd= (FluidsimModifierData*) target;
+
+ if(tfluidmd->fss)
+ MEM_freeN(tfluidmd->fss);
+
+ tfluidmd->fss = MEM_dupallocN(fluidmd->fss);
+}
+
+static DerivedMesh * fluidsimModifier_applyModifier(
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ int useRenderParams, int isFinalCalc)
+{
+ FluidsimModifierData *fluidmd= (FluidsimModifierData*) md;
+ DerivedMesh *result = NULL;
+
+ /* check for alloc failing */
+ if(!fluidmd->fss)
+ {
+ fluidsimModifier_initData(md);
+
+ if(!fluidmd->fss)
+ return derivedData;
+ }
+
+ result = fluidsimModifier_do(fluidmd, ob, derivedData, useRenderParams, isFinalCalc);
+
+ if(result)
+ {
+ return result;
}
+
return derivedData;
}
+
+static void fluidsimModifier_updateDepgraph(
+ ModifierData *md, DagForest *forest,
+ Object *ob, DagNode *obNode)
+{
+ FluidsimModifierData *fluidmd= (FluidsimModifierData*) md;
+ Base *base;
+
+ if(fluidmd && fluidmd->fss)
+ {
+ if(fluidmd->fss->type == OB_FLUIDSIM_DOMAIN)
+ {
+ for(base = G.scene->base.first; base; base= base->next)
+ {
+ Object *ob1= base->object;
+ if(ob1 != ob)
+ {
+ FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType(ob1, eModifierType_Fluidsim);
+
+ // only put dependancies from NON-DOMAIN fluids in here
+ if(fluidmdtmp && fluidmdtmp->fss && (fluidmdtmp->fss->type!=OB_FLUIDSIM_DOMAIN))
+ {
+ DagNode *curNode = dag_get_node(forest, ob1);
+ dag_add_relation(forest, curNode, obNode, DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Fluidsim Object");
+ }
+ }
+ }
+ }
+ }
+}
+
+static int fluidsimModifier_dependsOnTime(ModifierData *md)
+{
+ return 1;
+}
+
/* MeshDeform */
static void meshdeformModifier_initData(ModifierData *md)
@@ -6277,9 +7472,9 @@ static int meshdeformModifier_isDisabled(ModifierData *md)
}
static void meshdeformModifier_foreachObjectLink(
- ModifierData *md, Object *ob,
- void (*walk)(void *userData, Object *ob, Object **obpoin),
- void *userData)
+ ModifierData *md, Object *ob,
+ void (*walk)(void *userData, Object *ob, Object **obpoin),
+ void *userData)
{
MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
@@ -6287,8 +7482,8 @@ static void meshdeformModifier_foreachObjectLink(
}
static void meshdeformModifier_updateDepgraph(
- ModifierData *md, DagForest *forest, Object *ob,
- DagNode *obNode)
+ ModifierData *md, DagForest *forest, Object *ob,
+ DagNode *obNode)
{
MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
@@ -6296,7 +7491,8 @@ static void meshdeformModifier_updateDepgraph(
DagNode *curNode = dag_get_node(forest, mmd->object);
dag_add_relation(forest, curNode, obNode,
- DAG_RL_DATA_DATA|DAG_RL_OB_DATA|DAG_RL_DATA_OB|DAG_RL_OB_OB);
+ DAG_RL_DATA_DATA|DAG_RL_OB_DATA|DAG_RL_DATA_OB|DAG_RL_OB_OB,
+ "Mesh Deform Modifier");
}
}
@@ -6353,11 +7549,11 @@ static float meshdeform_dynamic_bind(MeshDeformModifierData *mmd, float (*dco)[3
}
static void meshdeformModifier_do(
- ModifierData *md, Object *ob, DerivedMesh *dm,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *dm,
+ float (*vertexCos)[3], int numVerts)
{
MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
- float imat[4][4], cagemat[4][4], icagemat[4][4], iobmat[3][3];
+ float imat[4][4], cagemat[4][4], iobmat[4][4], icagemat[3][3], cmat[4][4];
float weight, totweight, fac, co[3], *weights, (*dco)[3], (*bindcos)[3];
int a, b, totvert, totcagevert, defgrp_index;
DerivedMesh *tmpdm, *cagedm;
@@ -6380,15 +7576,24 @@ static void meshdeformModifier_do(
if(!cagedm)
return;
- /* compute matrices to go in and out of cage object space */
+ /* compute matrices to go in and out of cage object space */
Mat4Invert(imat, mmd->object->obmat);
Mat4MulMat4(cagemat, ob->obmat, imat);
- Mat4Invert(icagemat, cagemat);
- Mat3CpyMat4(iobmat, icagemat);
+ Mat4MulMat4(cmat, cagemat, mmd->bindmat);
+ Mat4Invert(iobmat, cmat);
+ Mat3CpyMat4(icagemat, iobmat);
/* bind weights if needed */
- if(!mmd->bindcos)
- //XXX harmonic_coordinates_bind(mmd, vertexCos, numVerts, cagemat);
+ if(!mmd->bindcos) {
+ static int recursive = 0;
+
+ /* progress bar redraw can make this recursive .. */
+ if(!recursive) {
+ recursive = 1;
+ //XXX harmonic_coordinates_bind(mmd, vertexCos, numVerts, cagemat);
+ recursive = 0;
+ }
+ }
/* verify we have compatible weights */
totvert= numVerts;
@@ -6482,11 +7687,11 @@ static void meshdeformModifier_do(
if(totweight > 0.0f) {
VecMulf(co, fac/totweight);
- Mat3MulVecfl(iobmat, co);
+ Mat3MulVecfl(icagemat, co);
if(G.rt != 527)
VECADD(vertexCos[b], vertexCos[b], co)
- else
- VECCOPY(vertexCos[b], co)
+ else
+ VECCOPY(vertexCos[b], co)
}
}
@@ -6496,8 +7701,8 @@ static void meshdeformModifier_do(
}
static void meshdeformModifier_deformVerts(
- ModifierData *md, Object *ob, DerivedMesh *derivedData,
- float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, DerivedMesh *derivedData,
+ float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm;
@@ -6515,8 +7720,8 @@ static void meshdeformModifier_deformVerts(
}
static void meshdeformModifier_deformVertsEM(
- ModifierData *md, Object *ob, EditMesh *editData,
- DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+ ModifierData *md, Object *ob, EditMesh *editData,
+ DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
{
DerivedMesh *dm;
@@ -6531,6 +7736,235 @@ static void meshdeformModifier_deformVertsEM(
dm->release(dm);
}
+
+/* Shrinkwrap */
+
+static void shrinkwrapModifier_initData(ModifierData *md)
+{
+ ShrinkwrapModifierData *smd = (ShrinkwrapModifierData*) md;
+ smd->shrinkType = MOD_SHRINKWRAP_NEAREST_SURFACE;
+ smd->shrinkOpts = MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR;
+ smd->keepDist = 0.0f;
+
+ smd->target = NULL;
+ smd->auxTarget = NULL;
+}
+
+static void shrinkwrapModifier_copyData(ModifierData *md, ModifierData *target)
+{
+ ShrinkwrapModifierData *smd = (ShrinkwrapModifierData*)md;
+ ShrinkwrapModifierData *tsmd = (ShrinkwrapModifierData*)target;
+
+ tsmd->target = smd->target;
+ tsmd->auxTarget = smd->auxTarget;
+
+ strcpy(tsmd->vgroup_name, smd->vgroup_name);
+
+ tsmd->keepDist = smd->keepDist;
+ tsmd->shrinkType= smd->shrinkType;
+ tsmd->shrinkOpts= smd->shrinkOpts;
+ tsmd->projAxis = smd->projAxis;
+ tsmd->subsurfLevels = smd->subsurfLevels;
+}
+
+CustomDataMask shrinkwrapModifier_requiredDataMask(ModifierData *md)
+{
+ ShrinkwrapModifierData *smd = (ShrinkwrapModifierData *)md;
+ CustomDataMask dataMask = 0;
+
+ /* ask for vertexgroups if we need them */
+ if(smd->vgroup_name[0])
+ dataMask |= (1 << CD_MDEFORMVERT);
+
+ if(smd->shrinkType == MOD_SHRINKWRAP_PROJECT
+ && smd->projAxis == MOD_SHRINKWRAP_PROJECT_OVER_NORMAL)
+ dataMask |= (1 << CD_MVERT);
+
+ return dataMask;
+}
+
+static int shrinkwrapModifier_isDisabled(ModifierData *md)
+{
+ ShrinkwrapModifierData *smd = (ShrinkwrapModifierData*) md;
+ return !smd->target;
+}
+
+
+static void shrinkwrapModifier_foreachObjectLink(ModifierData *md, Object *ob, ObjectWalkFunc walk, void *userData)
+{
+ ShrinkwrapModifierData *smd = (ShrinkwrapModifierData*) md;
+
+ walk(userData, ob, &smd->target);
+ walk(userData, ob, &smd->auxTarget);
+}
+
+static void shrinkwrapModifier_deformVerts(ModifierData *md, Object *ob, DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+{
+ DerivedMesh *dm = NULL;
+ CustomDataMask dataMask = shrinkwrapModifier_requiredDataMask(md);
+
+ /* We implement requiredDataMask but thats not really usefull since mesh_calc_modifiers pass a NULL derivedData or without the modified vertexs applied */
+ if(dataMask)
+ {
+ if(derivedData) dm = CDDM_copy(derivedData);
+ else if(ob->type==OB_MESH) dm = CDDM_from_mesh(ob->data, ob);
+ else if(ob->type==OB_LATTICE) dm = NULL;
+ else return;
+
+ if(dm != NULL && (dataMask & CD_MVERT))
+ {
+ CDDM_apply_vert_coords(dm, vertexCos);
+ CDDM_calc_normals(dm);
+ }
+ }
+
+ shrinkwrapModifier_deform((ShrinkwrapModifierData*)md, ob, dm, vertexCos, numVerts);
+
+ if(dm)
+ dm->release(dm);
+}
+
+static void shrinkwrapModifier_deformVertsEM(ModifierData *md, Object *ob, EditMesh *editData, DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+{
+ DerivedMesh *dm = NULL;
+ CustomDataMask dataMask = shrinkwrapModifier_requiredDataMask(md);
+
+ if(dataMask)
+ {
+ if(derivedData) dm = CDDM_copy(derivedData);
+ else if(ob->type==OB_MESH) dm = CDDM_from_editmesh(editData, ob->data);
+ else if(ob->type==OB_LATTICE) dm = NULL;
+ else return;
+
+ if(dm != NULL && (dataMask & CD_MVERT))
+ {
+ CDDM_apply_vert_coords(dm, vertexCos);
+ CDDM_calc_normals(dm);
+ }
+ }
+
+ shrinkwrapModifier_deform((ShrinkwrapModifierData*)md, ob, dm, vertexCos, numVerts);
+
+ if(dm)
+ dm->release(dm);
+}
+
+static void shrinkwrapModifier_updateDepgraph(ModifierData *md, DagForest *forest, Object *ob, DagNode *obNode)
+{
+ ShrinkwrapModifierData *smd = (ShrinkwrapModifierData*) md;
+
+ if (smd->target)
+ dag_add_relation(forest, dag_get_node(forest, smd->target), obNode, DAG_RL_OB_DATA | DAG_RL_DATA_DATA, "Shrinkwrap Modifier");
+
+ if (smd->auxTarget)
+ dag_add_relation(forest, dag_get_node(forest, smd->auxTarget), obNode, DAG_RL_OB_DATA | DAG_RL_DATA_DATA, "Shrinkwrap Modifier");
+}
+
+/* SimpleDeform */
+static void simpledeformModifier_initData(ModifierData *md)
+{
+ SimpleDeformModifierData *smd = (SimpleDeformModifierData*) md;
+
+ smd->mode = MOD_SIMPLEDEFORM_MODE_TWIST;
+ smd->axis = 0;
+
+ smd->origin = NULL;
+ smd->factor = 0.35f;
+ smd->limit[0] = 0.0f;
+ smd->limit[1] = 1.0f;
+}
+
+static void simpledeformModifier_copyData(ModifierData *md, ModifierData *target)
+{
+ SimpleDeformModifierData *smd = (SimpleDeformModifierData*)md;
+ SimpleDeformModifierData *tsmd = (SimpleDeformModifierData*)target;
+
+ tsmd->mode = smd->mode;
+ tsmd->axis = smd->axis;
+ tsmd->origin= smd->origin;
+ tsmd->factor= smd->factor;
+ memcpy(tsmd->limit, smd->limit, sizeof(tsmd->limit));
+}
+
+static CustomDataMask simpledeformModifier_requiredDataMask(ModifierData *md)
+{
+ SimpleDeformModifierData *smd = (SimpleDeformModifierData *)md;
+ CustomDataMask dataMask = 0;
+
+ /* ask for vertexgroups if we need them */
+ if(smd->vgroup_name[0])
+ dataMask |= (1 << CD_MDEFORMVERT);
+
+ return dataMask;
+}
+
+static void simpledeformModifier_foreachObjectLink(ModifierData *md, Object *ob, void (*walk)(void *userData, Object *ob, Object **obpoin), void *userData)
+{
+ SimpleDeformModifierData *smd = (SimpleDeformModifierData*)md;
+ walk(userData, ob, &smd->origin);
+}
+
+static void simpledeformModifier_updateDepgraph(ModifierData *md, DagForest *forest, Object *ob, DagNode *obNode)
+{
+ SimpleDeformModifierData *smd = (SimpleDeformModifierData*)md;
+
+ if (smd->origin)
+ dag_add_relation(forest, dag_get_node(forest, smd->origin), obNode, DAG_RL_OB_DATA, "SimpleDeform Modifier");
+}
+
+static void simpledeformModifier_deformVerts(ModifierData *md, Object *ob, DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+{
+ DerivedMesh *dm = NULL;
+ CustomDataMask dataMask = simpledeformModifier_requiredDataMask(md);
+
+ /* We implement requiredDataMask but thats not really usefull since mesh_calc_modifiers pass a NULL derivedData or without the modified vertexs applied */
+ if(dataMask)
+ {
+ if(derivedData) dm = CDDM_copy(derivedData);
+ else if(ob->type==OB_MESH) dm = CDDM_from_mesh(ob->data, ob);
+ else if(ob->type==OB_LATTICE) dm = NULL;
+ else return;
+
+ if(dm != NULL && (dataMask & CD_MVERT))
+ {
+ CDDM_apply_vert_coords(dm, vertexCos);
+ CDDM_calc_normals(dm);
+ }
+ }
+
+ SimpleDeformModifier_do((SimpleDeformModifierData*)md, ob, dm, vertexCos, numVerts);
+
+ if(dm)
+ dm->release(dm);
+
+}
+
+static void simpledeformModifier_deformVertsEM(ModifierData *md, Object *ob, EditMesh *editData, DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
+{
+ DerivedMesh *dm = NULL;
+ CustomDataMask dataMask = simpledeformModifier_requiredDataMask(md);
+
+ /* We implement requiredDataMask but thats not really usefull since mesh_calc_modifiers pass a NULL derivedData or without the modified vertexs applied */
+ if(dataMask)
+ {
+ if(derivedData) dm = CDDM_copy(derivedData);
+ else if(ob->type==OB_MESH) dm = CDDM_from_editmesh(editData, ob->data);
+ else if(ob->type==OB_LATTICE) dm = NULL;
+ else return;
+
+ if(dm != NULL && (dataMask & CD_MVERT))
+ {
+ CDDM_apply_vert_coords(dm, vertexCos);
+ CDDM_calc_normals(dm);
+ }
+ }
+
+ SimpleDeformModifier_do((SimpleDeformModifierData*)md, ob, dm, vertexCos, numVerts);
+
+ if(dm)
+ dm->release(dm);
+}
+
/***/
static ModifierTypeInfo typeArr[NUM_MODIFIER_TYPES];
@@ -6545,15 +7979,15 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
/* Initialize and return the appropriate type info structure,
* assumes that modifier has:
- * name == typeName,
- * structName == typeName + 'ModifierData'
- */
+ * name == typeName,
+ * structName == typeName + 'ModifierData'
+ */
#define INIT_TYPE(typeName) \
(strcpy(typeArr[eModifierType_##typeName].name, #typeName), \
strcpy(typeArr[eModifierType_##typeName].structName, \
- #typeName "ModifierData"), \
+#typeName "ModifierData"), \
typeArr[eModifierType_##typeName].structSize = \
- sizeof(typeName##ModifierData), \
+ sizeof(typeName##ModifierData), \
&typeArr[eModifierType_##typeName])
mti = &typeArr[eModifierType_None];
@@ -6562,13 +7996,13 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti->structSize = sizeof(ModifierData);
mti->type = eModifierType_None;
mti->flags = eModifierTypeFlag_AcceptsMesh
- | eModifierTypeFlag_AcceptsCVs;
+ | eModifierTypeFlag_AcceptsCVs;
mti->isDisabled = noneModifier_isDisabled;
mti = INIT_TYPE(Curve);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsCVs
- | eModifierTypeFlag_SupportsEditmode;
+ | eModifierTypeFlag_SupportsEditmode;
mti->initData = curveModifier_initData;
mti->copyData = curveModifier_copyData;
mti->requiredDataMask = curveModifier_requiredDataMask;
@@ -6581,7 +8015,7 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(Lattice);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsCVs
- | eModifierTypeFlag_SupportsEditmode;
+ | eModifierTypeFlag_SupportsEditmode;
mti->copyData = latticeModifier_copyData;
mti->requiredDataMask = latticeModifier_requiredDataMask;
mti->isDisabled = latticeModifier_isDisabled;
@@ -6593,9 +8027,9 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(Subsurf);
mti->type = eModifierTypeType_Constructive;
mti->flags = eModifierTypeFlag_AcceptsMesh
- | eModifierTypeFlag_SupportsMapping
- | eModifierTypeFlag_SupportsEditmode
- | eModifierTypeFlag_EnableInEditmode;
+ | eModifierTypeFlag_SupportsMapping
+ | eModifierTypeFlag_SupportsEditmode
+ | eModifierTypeFlag_EnableInEditmode;
mti->initData = subsurfModifier_initData;
mti->copyData = subsurfModifier_copyData;
mti->freeData = subsurfModifier_freeData;
@@ -6609,13 +8043,22 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti->copyData = buildModifier_copyData;
mti->dependsOnTime = buildModifier_dependsOnTime;
mti->applyModifier = buildModifier_applyModifier;
+
+ mti = INIT_TYPE(Mask);
+ mti->type = eModifierTypeType_Nonconstructive;
+ mti->flags = eModifierTypeFlag_AcceptsMesh;
+ mti->copyData = maskModifier_copyData;
+ mti->requiredDataMask= maskModifier_requiredDataMask;
+ mti->foreachObjectLink = maskModifier_foreachObjectLink;
+ mti->updateDepgraph = maskModifier_updateDepgraph;
+ mti->applyModifier = maskModifier_applyModifier;
mti = INIT_TYPE(Array);
mti->type = eModifierTypeType_Constructive;
mti->flags = eModifierTypeFlag_AcceptsMesh
- | eModifierTypeFlag_SupportsMapping
- | eModifierTypeFlag_SupportsEditmode
- | eModifierTypeFlag_EnableInEditmode;
+ | eModifierTypeFlag_SupportsMapping
+ | eModifierTypeFlag_SupportsEditmode
+ | eModifierTypeFlag_EnableInEditmode;
mti->initData = arrayModifier_initData;
mti->copyData = arrayModifier_copyData;
mti->foreachObjectLink = arrayModifier_foreachObjectLink;
@@ -6626,9 +8069,9 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(Mirror);
mti->type = eModifierTypeType_Constructive;
mti->flags = eModifierTypeFlag_AcceptsMesh
- | eModifierTypeFlag_SupportsMapping
- | eModifierTypeFlag_SupportsEditmode
- | eModifierTypeFlag_EnableInEditmode;
+ | eModifierTypeFlag_SupportsMapping
+ | eModifierTypeFlag_SupportsEditmode
+ | eModifierTypeFlag_EnableInEditmode;
mti->initData = mirrorModifier_initData;
mti->copyData = mirrorModifier_copyData;
mti->foreachObjectLink = mirrorModifier_foreachObjectLink;
@@ -6639,20 +8082,32 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(EdgeSplit);
mti->type = eModifierTypeType_Constructive;
mti->flags = eModifierTypeFlag_AcceptsMesh
- | eModifierTypeFlag_SupportsMapping
- | eModifierTypeFlag_SupportsEditmode
- | eModifierTypeFlag_EnableInEditmode;
+ | eModifierTypeFlag_SupportsMapping
+ | eModifierTypeFlag_SupportsEditmode
+ | eModifierTypeFlag_EnableInEditmode;
mti->initData = edgesplitModifier_initData;
mti->copyData = edgesplitModifier_copyData;
mti->applyModifier = edgesplitModifier_applyModifier;
mti->applyModifierEM = edgesplitModifier_applyModifierEM;
+ mti = INIT_TYPE(Bevel);
+ mti->type = eModifierTypeType_Constructive;
+ mti->flags = eModifierTypeFlag_AcceptsMesh
+ | eModifierTypeFlag_SupportsEditmode
+ | eModifierTypeFlag_EnableInEditmode;
+ mti->initData = bevelModifier_initData;
+ mti->copyData = bevelModifier_copyData;
+ mti->requiredDataMask = bevelModifier_requiredDataMask;
+ mti->applyModifier = bevelModifier_applyModifier;
+ mti->applyModifierEM = bevelModifier_applyModifierEM;
+
mti = INIT_TYPE(Displace);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsMesh|eModifierTypeFlag_SupportsEditmode;
mti->initData = displaceModifier_initData;
mti->copyData = displaceModifier_copyData;
mti->requiredDataMask = displaceModifier_requiredDataMask;
+ mti->dependsOnTime = displaceModifier_dependsOnTime;
mti->foreachObjectLink = displaceModifier_foreachObjectLink;
mti->foreachIDLink = displaceModifier_foreachIDLink;
mti->updateDepgraph = displaceModifier_updateDepgraph;
@@ -6663,9 +8118,9 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(UVProject);
mti->type = eModifierTypeType_Nonconstructive;
mti->flags = eModifierTypeFlag_AcceptsMesh
- | eModifierTypeFlag_SupportsMapping
- | eModifierTypeFlag_SupportsEditmode
- | eModifierTypeFlag_EnableInEditmode;
+ | eModifierTypeFlag_SupportsMapping
+ | eModifierTypeFlag_SupportsEditmode
+ | eModifierTypeFlag_EnableInEditmode;
mti->initData = uvprojectModifier_initData;
mti->copyData = uvprojectModifier_copyData;
mti->requiredDataMask = uvprojectModifier_requiredDataMask;
@@ -6685,7 +8140,7 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(Smooth);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsMesh
- | eModifierTypeFlag_SupportsEditmode;
+ | eModifierTypeFlag_SupportsEditmode;
mti->initData = smoothModifier_initData;
mti->copyData = smoothModifier_copyData;
mti->requiredDataMask = smoothModifier_requiredDataMask;
@@ -6695,7 +8150,7 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(Cast);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsCVs
- | eModifierTypeFlag_SupportsEditmode;
+ | eModifierTypeFlag_SupportsEditmode;
mti->initData = castModifier_initData;
mti->copyData = castModifier_copyData;
mti->requiredDataMask = castModifier_requiredDataMask;
@@ -6707,7 +8162,7 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(Wave);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsCVs
- | eModifierTypeFlag_SupportsEditmode;
+ | eModifierTypeFlag_SupportsEditmode;
mti->initData = waveModifier_initData;
mti->copyData = waveModifier_copyData;
mti->dependsOnTime = waveModifier_dependsOnTime;
@@ -6721,7 +8176,7 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(Armature);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsCVs
- | eModifierTypeFlag_SupportsEditmode;
+ | eModifierTypeFlag_SupportsEditmode;
mti->initData = armatureModifier_initData;
mti->copyData = armatureModifier_copyData;
mti->requiredDataMask = armatureModifier_requiredDataMask;
@@ -6735,7 +8190,7 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(Hook);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsCVs
- | eModifierTypeFlag_SupportsEditmode;
+ | eModifierTypeFlag_SupportsEditmode;
mti->initData = hookModifier_initData;
mti->copyData = hookModifier_copyData;
mti->requiredDataMask = hookModifier_requiredDataMask;
@@ -6749,14 +8204,36 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(Softbody);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsCVs
- | eModifierTypeFlag_RequiresOriginalData;
+ | eModifierTypeFlag_RequiresOriginalData;
mti->deformVerts = softbodyModifier_deformVerts;
+ mti->dependsOnTime = softbodyModifier_dependsOnTime;
+
+ mti = INIT_TYPE(Cloth);
+ mti->type = eModifierTypeType_Nonconstructive;
+ mti->initData = clothModifier_initData;
+ mti->flags = eModifierTypeFlag_AcceptsMesh
+ | eModifierTypeFlag_UsesPointCache;
+ mti->dependsOnTime = clothModifier_dependsOnTime;
+ mti->freeData = clothModifier_freeData;
+ mti->requiredDataMask = clothModifier_requiredDataMask;
+ mti->copyData = clothModifier_copyData;
+ mti->applyModifier = clothModifier_applyModifier;
+ mti->updateDepgraph = clothModifier_updateDepgraph;
+
+ mti = INIT_TYPE(Collision);
+ mti->type = eModifierTypeType_OnlyDeform;
+ mti->initData = collisionModifier_initData;
+ mti->flags = eModifierTypeFlag_AcceptsMesh;
+ mti->dependsOnTime = collisionModifier_dependsOnTime;
+ mti->freeData = collisionModifier_freeData;
+ mti->deformVerts = collisionModifier_deformVerts;
+ // mti->copyData = collisionModifier_copyData;
mti = INIT_TYPE(Boolean);
mti->type = eModifierTypeType_Nonconstructive;
mti->flags = eModifierTypeFlag_AcceptsMesh
- | eModifierTypeFlag_RequiresOriginalData
- | eModifierTypeFlag_UsesPointCache;
+ | eModifierTypeFlag_RequiresOriginalData
+ | eModifierTypeFlag_UsesPointCache;
mti->copyData = booleanModifier_copyData;
mti->isDisabled = booleanModifier_isDisabled;
mti->applyModifier = booleanModifier_applyModifier;
@@ -6766,7 +8243,7 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(MeshDeform);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsCVs
- | eModifierTypeFlag_SupportsEditmode;
+ | eModifierTypeFlag_SupportsEditmode;
mti->initData = meshdeformModifier_initData;
mti->freeData = meshdeformModifier_freeData;
mti->copyData = meshdeformModifier_copyData;
@@ -6780,11 +8257,11 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(ParticleSystem);
mti->type = eModifierTypeType_OnlyDeform;
mti->flags = eModifierTypeFlag_AcceptsMesh
- | eModifierTypeFlag_SupportsMapping
- | eModifierTypeFlag_UsesPointCache;
+ | eModifierTypeFlag_SupportsMapping
+ | eModifierTypeFlag_UsesPointCache;
#if 0
- | eModifierTypeFlag_SupportsEditmode;
- |eModifierTypeFlag_EnableInEditmode;
+ | eModifierTypeFlag_SupportsEditmode;
+ |eModifierTypeFlag_EnableInEditmode;
#endif
mti->initData = particleSystemModifier_initData;
mti->freeData = particleSystemModifier_freeData;
@@ -6798,9 +8275,9 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti = INIT_TYPE(ParticleInstance);
mti->type = eModifierTypeType_Constructive;
mti->flags = eModifierTypeFlag_AcceptsMesh
- | eModifierTypeFlag_SupportsMapping
- | eModifierTypeFlag_SupportsEditmode
- | eModifierTypeFlag_EnableInEditmode;
+ | eModifierTypeFlag_SupportsMapping
+ | eModifierTypeFlag_SupportsEditmode
+ | eModifierTypeFlag_EnableInEditmode;
mti->initData = particleInstanceModifier_initData;
mti->copyData = particleInstanceModifier_copyData;
mti->dependsOnTime = particleInstanceModifier_dependsOnTime;
@@ -6818,6 +8295,46 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
mti->dependsOnTime = explodeModifier_dependsOnTime;
mti->requiredDataMask = explodeModifier_requiredDataMask;
mti->applyModifier = explodeModifier_applyModifier;
+
+ mti = INIT_TYPE(Fluidsim);
+ mti->type = eModifierTypeType_Nonconstructive
+ | eModifierTypeFlag_RequiresOriginalData;
+ mti->flags = eModifierTypeFlag_AcceptsMesh;
+ mti->initData = fluidsimModifier_initData;
+ mti->freeData = fluidsimModifier_freeData;
+ mti->copyData = fluidsimModifier_copyData;
+ mti->dependsOnTime = fluidsimModifier_dependsOnTime;
+ mti->applyModifier = fluidsimModifier_applyModifier;
+ mti->updateDepgraph = fluidsimModifier_updateDepgraph;
+
+ mti = INIT_TYPE(Shrinkwrap);
+ mti->type = eModifierTypeType_OnlyDeform;
+ mti->flags = eModifierTypeFlag_AcceptsMesh
+ | eModifierTypeFlag_AcceptsCVs
+ | eModifierTypeFlag_SupportsEditmode
+ | eModifierTypeFlag_EnableInEditmode;
+ mti->initData = shrinkwrapModifier_initData;
+ mti->copyData = shrinkwrapModifier_copyData;
+ mti->requiredDataMask = shrinkwrapModifier_requiredDataMask;
+ mti->isDisabled = shrinkwrapModifier_isDisabled;
+ mti->foreachObjectLink = shrinkwrapModifier_foreachObjectLink;
+ mti->deformVerts = shrinkwrapModifier_deformVerts;
+ mti->deformVertsEM = shrinkwrapModifier_deformVertsEM;
+ mti->updateDepgraph = shrinkwrapModifier_updateDepgraph;
+
+ mti = INIT_TYPE(SimpleDeform);
+ mti->type = eModifierTypeType_OnlyDeform;
+ mti->flags = eModifierTypeFlag_AcceptsMesh
+ | eModifierTypeFlag_AcceptsCVs
+ | eModifierTypeFlag_SupportsEditmode
+ | eModifierTypeFlag_EnableInEditmode;
+ mti->initData = simpledeformModifier_initData;
+ mti->copyData = simpledeformModifier_copyData;
+ mti->requiredDataMask = simpledeformModifier_requiredDataMask;
+ mti->deformVerts = simpledeformModifier_deformVerts;
+ mti->deformVertsEM = simpledeformModifier_deformVertsEM;
+ mti->foreachObjectLink = simpledeformModifier_foreachObjectLink;
+ mti->updateDepgraph = simpledeformModifier_updateDepgraph;
typeArrInit = 0;
#undef INIT_TYPE
@@ -6841,7 +8358,7 @@ ModifierData *modifier_new(int type)
md->type = type;
md->mode = eModifierMode_Realtime
- | eModifierMode_Render | eModifierMode_Expanded;
+ | eModifierMode_Render | eModifierMode_Expanded;
if (mti->flags & eModifierTypeFlag_EnableInEditmode)
md->mode |= eModifierMode_Editmode;
@@ -6873,7 +8390,7 @@ int modifier_supportsMapping(ModifierData *md)
ModifierTypeInfo *mti = modifierType_getInfo(md->type);
return (mti->type==eModifierTypeType_OnlyDeform ||
- (mti->flags & eModifierTypeFlag_SupportsMapping));
+ (mti->flags & eModifierTypeFlag_SupportsMapping));
}
ModifierData *modifiers_findByType(Object *ob, ModifierType type)
@@ -6905,7 +8422,7 @@ void modifiers_clearErrors(Object *ob)
}
void modifiers_foreachObjectLink(Object *ob, ObjectWalkFunc walk,
- void *userData)
+ void *userData)
{
ModifierData *md = ob->modifiers.first;
@@ -6948,9 +8465,9 @@ int modifier_couldBeCage(ModifierData *md)
ModifierTypeInfo *mti = modifierType_getInfo(md->type);
return ( (md->mode & eModifierMode_Realtime) &&
- (md->mode & eModifierMode_Editmode) &&
- (!mti->isDisabled || !mti->isDisabled(md)) &&
- modifier_supportsMapping(md));
+ (md->mode & eModifierMode_Editmode) &&
+ (!mti->isDisabled || !mti->isDisabled(md)) &&
+ modifier_supportsMapping(md));
}
void modifier_setError(ModifierData *md, char *format, ...)
@@ -6981,7 +8498,7 @@ int modifiers_getCageIndex(Object *ob, int *lastPossibleCageIndex_r)
ModifierData *md = ob->modifiers.first;
int i, cageIndex = -1;
- /* Find the last modifier acting on the cage. */
+ /* Find the last modifier acting on the cage. */
for (i=0; md; i++,md=md->next) {
ModifierTypeInfo *mti = modifierType_getInfo(md->type);
@@ -7010,6 +8527,13 @@ int modifiers_isSoftbodyEnabled(Object *ob)
return (md && md->mode & (eModifierMode_Realtime | eModifierMode_Render));
}
+int modifiers_isClothEnabled(Object *ob)
+{
+ ModifierData *md = modifiers_findByType(ob, eModifierType_Cloth);
+
+ return (md && md->mode & (eModifierMode_Realtime | eModifierMode_Render));
+}
+
int modifiers_isParticleEnabled(Object *ob)
{
ModifierData *md = modifiers_findByType(ob, eModifierType_ParticleSystem);
@@ -7033,11 +8557,11 @@ LinkNode *modifiers_calcDataMasks(ModifierData *md, CustomDataMask dataMask)
}
/* build the list of required data masks - each mask in the list must
- * include all elements of the masks that follow it
- *
- * note the list is currently in reverse order, so "masks that follow it"
- * actually means "masks that precede it" at the moment
- */
+ * include all elements of the masks that follow it
+ *
+ * note the list is currently in reverse order, so "masks that follow it"
+ * actually means "masks that precede it" at the moment
+ */
for(curr = dataMasks, prev = NULL; curr; prev = curr, curr = curr->next) {
if(prev) {
CustomDataMask prev_mask = (CustomDataMask)prev->link;
@@ -7060,8 +8584,8 @@ LinkNode *modifiers_calcDataMasks(ModifierData *md, CustomDataMask dataMask)
ModifierData *modifiers_getVirtualModifierList(Object *ob)
{
/* Kinda hacky, but should be fine since we are never
- * reentrant and avoid free hassles.
- */
+ * reentrant and avoid free hassles.
+ */
static ArmatureModifierData amd;
static CurveModifierData cmd;
static LatticeModifierData lmd;
@@ -7119,7 +8643,7 @@ Object *modifiers_isDeformedByArmature(Object *ob)
ArmatureModifierData *amd= NULL;
/* return the first selected armature, this lets us use multiple armatures
- */
+ */
for (; md; md=md->next) {
if (md->type==eModifierType_Armature) {
amd = (ArmatureModifierData*) md;
@@ -7144,7 +8668,7 @@ Object *modifiers_isDeformedByLattice(Object *ob)
LatticeModifierData *lmd= NULL;
/* return the first selected armature, this lets us use multiple armatures
- */
+ */
for (; md; md=md->next) {
if (md->type==eModifierType_Lattice) {
lmd = (LatticeModifierData*) md;
@@ -7234,3 +8758,4 @@ void modifier_freeTemporaryData(ModifierData *md)
}
+
diff --git a/source/blender/blenkernel/intern/multires-firstlevel.c b/source/blender/blenkernel/intern/multires-firstlevel.c
index b27d1c4b156..8c667a9ecf0 100644
--- a/source/blender/blenkernel/intern/multires-firstlevel.c
+++ b/source/blender/blenkernel/intern/multires-firstlevel.c
@@ -1,5 +1,5 @@
/*
- * $Id: multires-firstlevel.c 13001 2007-12-26 09:39:15Z nicholasbishop $
+ * $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -73,7 +73,7 @@ char type_ok(const int type)
}
/* Copy vdata or fdata from Mesh or EditMesh to Multires. */
-void multires_update_customdata(MultiresLevel *lvl1, CustomData *src, CustomData *dst, const int type)
+void multires_update_customdata(MultiresLevel *lvl1, EditMesh *em, CustomData *src, CustomData *dst, const int type)
{
if(src && dst && type_ok(type)) {
const int tot= (type == CD_MDEFORMVERT ? lvl1->totvert : lvl1->totface);
@@ -82,7 +82,7 @@ void multires_update_customdata(MultiresLevel *lvl1, CustomData *src, CustomData
CustomData_free(dst, tot);
if(CustomData_has_layer(src, type)) {
- if(G.obedit) {
+ if(em) {
EditVert *eve= G.editMesh->verts.first;
EditFace *efa= G.editMesh->faces.first;
CustomData_copy(src, dst, cdmask(type), CD_CALLOC, tot);
@@ -225,9 +225,9 @@ void multires_del_lower_customdata(Multires *mr, MultiresLevel *cr_lvl)
void multires_update_first_level(Mesh *me, EditMesh *em)
{
if(me && me->mr && me->mr->current == 1) {
- multires_update_customdata(me->mr->levels.first, em ? &em->vdata : &me->vdata,
+ multires_update_customdata(me->mr->levels.first, em, em ? &em->vdata : &me->vdata,
&me->mr->vdata, CD_MDEFORMVERT);
- multires_update_customdata(me->mr->levels.first, em ? &em->fdata : &me->fdata,
+ multires_update_customdata(me->mr->levels.first, em, em ? &em->fdata : &me->fdata,
&me->mr->fdata, CD_MTFACE);
multires_update_edge_flags(me, em);
}
diff --git a/source/blender/blenkernel/intern/multires.c b/source/blender/blenkernel/intern/multires.c
index a3c1d9ef19d..96e81c604fa 100644
--- a/source/blender/blenkernel/intern/multires.c
+++ b/source/blender/blenkernel/intern/multires.c
@@ -205,7 +205,7 @@ static void multires_get_edge(MultiresEdge *e, EditEdge *eed, MEdge *m, short *f
}
}
-static void multires_get_face(MultiresFace *f, EditFace *efa, MFace *m)
+static void multires_get_face(MultiresFace *f, CustomData *fdata, int findex, EditFace *efa, MFace *m)
{
if(efa) {
MFace tmp;
@@ -215,7 +215,7 @@ static void multires_get_face(MultiresFace *f, EditFace *efa, MFace *m)
tmp.v3= efa->v3->tmp.l;
tmp.v4= 0;
if(efa->v4) tmp.v4= efa->v4->tmp.l;
- //XXX test_index_face(&tmp, NULL, 0, efa->v4?4:3);
+ //XXX test_index_face(&tmp, fdata, findex, efa->v4?4:3);
for(j=0; j<4; ++j) f->v[j]= (&tmp.v1)[j];
/* Flags */
@@ -370,7 +370,7 @@ void multires_create(Object *ob, Mesh *me)
/* Load vertices and vdata (MDeformVerts) */
lvl->totvert= em ? BLI_countlist(&em->verts) : me->totvert;
me->mr->verts= MEM_callocN(sizeof(MVert)*lvl->totvert,"multires verts");
- multires_update_customdata(me->mr->levels.first, em ? &em->vdata : &me->vdata,
+ multires_update_customdata(me->mr->levels.first, em, em ? &em->vdata : &me->vdata,
&me->mr->vdata, CD_MDEFORMVERT);
if(em) eve= em->verts.first;
for(i=0; i<lvl->totvert; ++i) {
@@ -381,11 +381,11 @@ void multires_create(Object *ob, Mesh *me)
/* Load faces and fdata (MTFaces) */
lvl->totface= em ? BLI_countlist(&em->faces) : me->totface;
lvl->faces= MEM_callocN(sizeof(MultiresFace)*lvl->totface,"multires faces");
- multires_update_customdata(me->mr->levels.first, em ? &em->fdata : &me->fdata,
+ multires_update_customdata(me->mr->levels.first, em, em ? &em->fdata : &me->fdata,
&me->mr->fdata, CD_MTFACE);
if(em) efa= em->faces.first;
for(i=0; i<lvl->totface; ++i) {
- multires_get_face(&lvl->faces[i], efa, &me->mface[i]);
+ multires_get_face(&lvl->faces[i], &me->mr->fdata, i, efa, &me->mface[i]);
if(em) efa= efa->next;
}
@@ -639,6 +639,10 @@ static void multires_update_vertices(Mesh *me, EditMesh *em)
MultiApplyData data;
int i, j;
+ /* XXX added this to prevent crash, but if it works? (ton) */
+ if(me->mr->verts==NULL)
+ return;
+
/* Prepare deltas */
pr_deltas= MEM_callocN(sizeof(vec3f)*last_lvl->totvert, "multires deltas 1");
cr_deltas= MEM_callocN(sizeof(vec3f)*last_lvl->totvert, "multires deltas 2");
@@ -762,7 +766,7 @@ static void multires_update_faces(Mesh *me, EditMesh *em)
if(em) efa= em->faces.first;
for(i=0; i<cr_lvl->totface; ++i) {
MultiresFace mftmp;
- multires_get_face(&mftmp, efa, &me->mface[i]);
+ multires_get_face(&mftmp, &me->mr->fdata, i, efa, &me->mface[i]);
if(cr_lvl->faces[i].flag != mftmp.flag)
cr_flag_damaged[i]= 1;
if(cr_lvl->faces[i].mat_nr != mftmp.mat_nr)
@@ -1284,7 +1288,7 @@ void multires_edge_level_update(Object *ob, Mesh *me)
if(!G.obedit) {
MultiresLevel *cr_lvl= BLI_findlink(&me->mr->levels,me->mr->current-1);
MultiresLevel *edge_lvl= BLI_findlink(&me->mr->levels,me->mr->edgelvl-1);
- const int threshold= edge_lvl->totedge * powf(2, me->mr->current - me->mr->edgelvl);
+ const int threshold= edge_lvl->totedge * pow(2, me->mr->current - me->mr->edgelvl);
unsigned i;
for(i=0; i<cr_lvl->totedge; ++i) {
diff --git a/source/blender/blenkernel/intern/node.c b/source/blender/blenkernel/intern/node.c
index 5c9b609bbaf..8d60b1b4359 100644
--- a/source/blender/blenkernel/intern/node.c
+++ b/source/blender/blenkernel/intern/node.c
@@ -27,6 +27,10 @@
* ***** END GPL LICENSE BLOCK *****
*/
+#ifndef DISABLE_PYTHON
+#include <Python.h>
+#endif
+
#include <stdlib.h>
#include <string.h>
@@ -34,6 +38,7 @@
#include "DNA_image_types.h"
#include "DNA_node_types.h"
#include "DNA_material_types.h"
+#include "DNA_text_types.h"
#include "DNA_scene_types.h"
#include "BKE_blender.h"
@@ -44,6 +49,7 @@
#include "BKE_main.h"
#include "BKE_node.h"
#include "BKE_texture.h"
+#include "BKE_text.h"
#include "BKE_utildefines.h"
#include "BLI_arithb.h"
@@ -61,10 +67,12 @@
#include "RE_render_ext.h" /* <- ibuf_sample() */
#include "CMP_node.h"
+#include "intern/CMP_util.h" /* stupid include path... */
+
#include "SHD_node.h"
-/* not very important, but the stack solver likes to know a maximum */
-#define MAX_SOCKET 64
+#include "GPU_extensions.h"
+#include "GPU_material.h"
static ListBase empty_list = {NULL, NULL};
ListBase node_all_composit = {NULL, NULL};
@@ -72,7 +80,7 @@ ListBase node_all_shaders = {NULL, NULL};
/* ************** Type stuff ********** */
-static bNodeType *node_get_type(bNodeTree *ntree, int type, bNodeTree *ngroup)
+static bNodeType *node_get_type(bNodeTree *ntree, int type, bNodeTree *ngroup, ID *id)
{
if(type==NODE_GROUP) {
if(ngroup && GS(ngroup->id.name)==ID_NT) {
@@ -83,7 +91,7 @@ static bNodeType *node_get_type(bNodeTree *ntree, int type, bNodeTree *ngroup)
else {
bNodeType *ntype = ntree->alltypes.first;
for(; ntype; ntype= ntype->next)
- if(ntype->type==type)
+ if(ntype->type==type && id==ntype->id )
return ntype;
return NULL;
@@ -105,7 +113,27 @@ void ntreeInitTypes(bNodeTree *ntree)
for(node= ntree->nodes.first; node; node= next) {
next= node->next;
- node->typeinfo= node_get_type(ntree, node->type, (bNodeTree *)node->id);
+ if(node->type==NODE_DYNAMIC) {
+ bNodeType *stype= NULL;
+ if(node->id==NULL) { /* empty script node */
+ stype= node_get_type(ntree, node->type, NULL, NULL);
+ } else { /* not an empty script node */
+ stype= node_get_type(ntree, node->type, NULL, node->id);
+ if(!stype) {
+ stype= node_get_type(ntree, node->type, NULL, NULL);
+ /* needed info if the pynode script fails now: */
+ if (node->id) node->storage= ntree;
+ } else {
+ node->custom1= 0;
+ node->custom1= BSET(node->custom1,NODE_DYNAMIC_ADDEXIST);
+ }
+ }
+ node->typeinfo= stype;
+ node->typeinfo->initfunc(node);
+ } else {
+ node->typeinfo= node_get_type(ntree, node->type, (bNodeTree *)node->id, NULL);
+ }
+
if(node->typeinfo==NULL) {
printf("Error: Node type %s doesn't exist anymore, removed\n", node->name);
nodeFreeNode(ntree, node);
@@ -115,6 +143,18 @@ void ntreeInitTypes(bNodeTree *ntree)
ntree->init |= NTREE_TYPE_INIT;
}
+/* updates node with (modified) bNodeType.. this should be done for all trees */
+void ntreeUpdateType(bNodeTree *ntree, bNodeType *ntype)
+{
+ bNode *node;
+
+ for(node= ntree->nodes.first; node; node= node->next) {
+ if(node->typeinfo== ntype) {
+ nodeUpdateType(ntree, node, ntype);
+ }
+ }
+}
+
/* only used internal... we depend on type definitions! */
static bNodeSocket *node_add_socket_type(ListBase *lb, bNodeSocketType *stype)
{
@@ -137,7 +177,7 @@ static bNodeSocket *node_add_socket_type(ListBase *lb, bNodeSocketType *stype)
if(lb)
BLI_addtail(lb, sock);
-
+
return sock;
}
@@ -483,6 +523,28 @@ bNode *nodeMakeGroupFromSelected(bNodeTree *ntree)
BLI_addtail(&ngroup->nodes, node);
node->locx-= 0.5f*(min[0]+max[0]);
node->locy-= 0.5f*(min[1]+max[1]);
+
+ /* set selin and selout of the nodetree */
+ for(sock= node->inputs.first; sock; sock= sock->next) {
+ if(sock->flag & SOCK_SEL) {
+ ngroup->selin= sock;
+ break;
+ }
+ }
+ for(sock= node->outputs.first; sock; sock= sock->next) {
+ if(sock->flag & SOCK_SEL) {
+ ngroup->selout= sock;
+ break;
+ }
+ }
+
+ /* set socket own_index to zero since it can still have a value
+ * from being in a group before, otherwise it doesn't get a unique
+ * index in group_verify_own_indices */
+ for(sock= node->inputs.first; sock; sock= sock->next)
+ sock->own_index= 0;
+ for(sock= node->outputs.first; sock; sock= sock->next)
+ sock->own_index= 0;
}
}
@@ -499,7 +561,7 @@ bNode *nodeMakeGroupFromSelected(bNodeTree *ntree)
ntreeMakeOwnType(ngroup);
/* make group node */
- gnode= nodeAddNodeType(ntree, NODE_GROUP, ngroup);
+ gnode= nodeAddNodeType(ntree, NODE_GROUP, ngroup, NULL);
gnode->locx= 0.5f*(min[0]+max[0]);
gnode->locy= 0.5f*(min[1]+max[1]);
@@ -538,6 +600,10 @@ bNode *nodeMakeGroupFromSelected(bNodeTree *ntree)
}
}
}
+
+ /* update node levels */
+ ntreeSolveOrder(ntree);
+
return gnode;
}
@@ -653,7 +719,8 @@ void nodeGroupSocketUseFlags(bNodeTree *ngroup)
}
}
-static void find_node_with_socket(bNodeTree *ntree, bNodeSocket *sock, bNode **nodep, int *sockindex)
+/* finds a node based on given socket */
+int nodeFindNode(bNodeTree *ntree, bNodeSocket *sock, bNode **nodep, int *sockindex)
{
bNode *node;
bNodeSocket *tsock;
@@ -671,13 +738,15 @@ static void find_node_with_socket(bNodeTree *ntree, bNodeSocket *sock, bNode **n
if(tsock)
break;
}
+
if(node) {
*nodep= node;
- *sockindex= index;
- }
- else {
- *nodep= NULL;
+ if(sockindex) *sockindex= index;
+ return 1;
}
+
+ *nodep= NULL;
+ return 0;
}
/* returns 1 if its OK */
@@ -717,7 +786,7 @@ int nodeGroupUnGroup(bNodeTree *ntree, bNode *gnode)
for(link= ntree->links.first; link; link= link->next) {
if(link->tonode==gnode) {
/* link->tosock->tosock is on the node we look for */
- find_node_with_socket(ngroup, link->tosock->tosock, &nextn, &index);
+ nodeFindNode(ngroup, link->tosock->tosock, &nextn, &index);
if(nextn==NULL) printf("wrong stuff!\n");
else if(nextn->new_node==NULL) printf("wrong stuff too!\n");
else {
@@ -727,7 +796,7 @@ int nodeGroupUnGroup(bNodeTree *ntree, bNode *gnode)
}
else if(link->fromnode==gnode) {
/* link->fromsock->tosock is on the node we look for */
- find_node_with_socket(ngroup, link->fromsock->tosock, &nextn, &index);
+ nodeFindNode(ngroup, link->fromsock->tosock, &nextn, &index);
if(nextn==NULL) printf("1 wrong stuff!\n");
else if(nextn->new_node==NULL) printf("1 wrong stuff too!\n");
else {
@@ -749,30 +818,28 @@ int nodeGroupUnGroup(bNodeTree *ntree, bNode *gnode)
return 1;
}
-/* ************** Add stuff ********** */
+void nodeCopyGroup(bNode *gnode)
+{
+ bNodeSocket *sock;
+
+ gnode->id->us--;
+ gnode->id= (ID *)ntreeCopyTree((bNodeTree *)gnode->id, 0);
-bNode *nodeAddNodeType(bNodeTree *ntree, int type, bNodeTree *ngroup)
+ /* new_sock was set in nodeCopyNode */
+ for(sock=gnode->inputs.first; sock; sock=sock->next)
+ if(sock->tosock)
+ sock->tosock= sock->tosock->new_sock;
+
+ for(sock=gnode->outputs.first; sock; sock=sock->next)
+ if(sock->tosock)
+ sock->tosock= sock->tosock->new_sock;
+}
+
+/* ************** Add stuff ********** */
+void nodeAddSockets(bNode *node, bNodeType *ntype)
{
- bNode *node;
- bNodeType *ntype= node_get_type(ntree, type, ngroup);
bNodeSocketType *stype;
-
- node= MEM_callocN(sizeof(bNode), "new node");
- BLI_addtail(&ntree->nodes, node);
- node->typeinfo= ntype;
-
- if(ngroup)
- BLI_strncpy(node->name, ngroup->id.name+2, NODE_MAXSTR);
- else
- BLI_strncpy(node->name, ntype->name, NODE_MAXSTR);
- node->type= ntype->type;
- node->flag= NODE_SELECT|ntype->flag;
- node->width= ntype->width;
- node->miniwidth= 42.0f; /* small value only, allows print of first chars */
-
- if(type==NODE_GROUP)
- node->id= (ID *)ngroup;
-
+
if(ntype->inputs) {
stype= ntype->inputs;
while(stype->type != -1) {
@@ -787,34 +854,111 @@ bNode *nodeAddNodeType(bNodeTree *ntree, int type, bNodeTree *ngroup)
stype++;
}
}
-
+}
+
+
+bNode *nodeAddNodeType(bNodeTree *ntree, int type, bNodeTree *ngroup, ID *id)
+{
+ bNode *node= NULL;
+ bNodeType *ntype= NULL;
+
+ if(type>=NODE_DYNAMIC_MENU) {
+ int a=0, idx= type-NODE_DYNAMIC_MENU;
+ ntype= ntree->alltypes.first;
+ while(ntype) {
+ if(ntype->type==NODE_DYNAMIC) {
+ if(a==idx)
+ break;
+ a++;
+ }
+ ntype= ntype->next;
+ }
+ } else
+ ntype= node_get_type(ntree, type, ngroup, id);
+
+ node= MEM_callocN(sizeof(bNode), "new node");
+ BLI_addtail(&ntree->nodes, node);
+ node->typeinfo= ntype;
+ if(type>=NODE_DYNAMIC_MENU)
+ node->custom2= type; /* for node_dynamic_init */
+
+ if(ngroup)
+ BLI_strncpy(node->name, ngroup->id.name+2, NODE_MAXSTR);
+ else if(type>NODE_DYNAMIC_MENU) {
+ BLI_strncpy(node->name, ntype->id->name+2, NODE_MAXSTR);
+ }
+ else
+ BLI_strncpy(node->name, ntype->name, NODE_MAXSTR);
+ node->type= ntype->type;
+ node->flag= NODE_SELECT|ntype->flag;
+ node->width= ntype->width;
+ node->miniwidth= 42.0f; /* small value only, allows print of first chars */
+
+ if(type==NODE_GROUP)
+ node->id= (ID *)ngroup;
+
/* need init handler later? */
- /* got it-bob*/
- if(ntype->initfunc!=NULL)
- ntype->initfunc(node);
+ /* got it-bob*/
+ if(ntype->initfunc!=NULL)
+ ntype->initfunc(node);
+
+ nodeAddSockets(node, ntype);
+
+ return node;
+}
+
+void nodeMakeDynamicType(bNode *node)
+{
+ /* find SH_DYNAMIC_NODE ntype */
+ bNodeType *ntype= node_all_shaders.first;
+ while(ntype) {
+ if(ntype->type==NODE_DYNAMIC && ntype->id==NULL)
+ break;
+ ntype= ntype->next;
+ }
+
+ /* make own type struct to fill */
+ if(ntype) {
+ /*node->typeinfo= MEM_dupallocN(ntype);*/
+ bNodeType *newtype= MEM_callocN(sizeof(bNodeType), "dynamic bNodeType");
+ *newtype= *ntype;
+ newtype->name= BLI_strdup(ntype->name);
+ node->typeinfo= newtype;
+ }
+}
- return node;
+void nodeUpdateType(bNodeTree *ntree, bNode* node, bNodeType *ntype)
+{
+ verify_socket_list(ntree, &node->inputs, ntype->inputs);
+ verify_socket_list(ntree, &node->outputs, ntype->outputs);
}
/* keep socket listorder identical, for copying links */
/* ntree is the target tree */
-bNode *nodeCopyNode(struct bNodeTree *ntree, struct bNode *node)
+bNode *nodeCopyNode(struct bNodeTree *ntree, struct bNode *node, int internal)
{
bNode *nnode= MEM_callocN(sizeof(bNode), "dupli node");
- bNodeSocket *sock;
+ bNodeSocket *sock, *oldsock;
*nnode= *node;
BLI_addtail(&ntree->nodes, nnode);
BLI_duplicatelist(&nnode->inputs, &node->inputs);
- for(sock= nnode->inputs.first; sock; sock= sock->next)
- sock->own_index= 0;
+ oldsock= node->inputs.first;
+ for(sock= nnode->inputs.first; sock; sock= sock->next, oldsock= oldsock->next) {
+ oldsock->new_sock= sock;
+ if(internal)
+ sock->own_index= 0;
+ }
BLI_duplicatelist(&nnode->outputs, &node->outputs);
- for(sock= nnode->outputs.first; sock; sock= sock->next) {
- sock->own_index= 0;
+ oldsock= node->outputs.first;
+ for(sock= nnode->outputs.first; sock; sock= sock->next, oldsock= oldsock->next) {
+ if(internal)
+ sock->own_index= 0;
sock->stack_index= 0;
sock->ns.data= NULL;
+ oldsock->new_sock= sock;
}
if(nnode->id)
@@ -892,12 +1036,34 @@ bNodeTree *ntreeCopyTree(bNodeTree *ntree, int internal_select)
node->new_node= NULL;
if(internal_select==0 || (node->flag & NODE_SELECT)) {
- nnode= nodeCopyNode(newtree, node); /* sets node->new */
+ nnode= nodeCopyNode(newtree, node, internal_select); /* sets node->new */
if(internal_select) {
node->flag &= ~NODE_SELECT;
nnode->flag |= NODE_SELECT;
}
node->flag &= ~NODE_ACTIVE;
+
+ /* deselect original sockets */
+ for(sock= node->inputs.first; sock; sock= sock->next) {
+ if(sock->flag & SOCK_SEL) sock->flag&= ~SOCK_SEL;
+ }
+ for(sock= node->outputs.first; sock; sock= sock->next) {
+ if(sock->flag & SOCK_SEL) sock->flag&= ~SOCK_SEL;
+ }
+
+ /* set tree selin and selout to new sockets */
+ for(sock= nnode->inputs.first; sock; sock= sock->next) {
+ if(sock->flag & SOCK_SEL) {
+ ntree->selin= sock;
+ break;
+ }
+ }
+ for(sock= nnode->outputs.first; sock; sock= sock->next) {
+ if(sock->flag & SOCK_SEL) {
+ ntree->selout= sock;
+ break;
+ }
+ }
}
if(node==last) break;
}
@@ -941,7 +1107,7 @@ bNodeTree *ntreeCopyTree(bNodeTree *ntree, int internal_select)
/* ************** Free stuff ********** */
/* goes over entire tree */
-static void node_unlink_node(bNodeTree *ntree, bNode *node)
+void nodeUnlinkNode(bNodeTree *ntree, bNode *node)
{
bNodeLink *link, *next;
bNodeSocket *sock;
@@ -985,7 +1151,7 @@ static void composit_free_node_cache(bNode *node)
void nodeFreeNode(bNodeTree *ntree, bNode *node)
{
- node_unlink_node(ntree, node);
+ nodeUnlinkNode(ntree, node);
BLI_remlink(&ntree->nodes, node);
/* since it is called while free database, node->id is undefined */
@@ -1003,6 +1169,7 @@ void nodeFreeNode(bNodeTree *ntree, bNode *node)
if(node->typeinfo && node->typeinfo->freestoragefunc) {
node->typeinfo->freestoragefunc(node);
}
+
MEM_freeN(node);
}
@@ -1204,11 +1371,21 @@ bNode *nodeGetActiveID(bNodeTree *ntree, short idtype)
bNode *node;
if(ntree==NULL) return NULL;
+
+ /* check for group edit */
+ for(node= ntree->nodes.first; node; node= node->next)
+ if(node->flag & NODE_GROUP_EDIT)
+ break;
+
+ if(node)
+ ntree= (bNodeTree*)node->id;
+ /* now find active node with this id */
for(node= ntree->nodes.first; node; node= node->next)
if(node->id && GS(node->id->name)==idtype)
if(node->flag & NODE_ACTIVE_ID)
break;
+
return node;
}
@@ -1629,7 +1806,7 @@ static void composit_begin_exec(bNodeTree *ntree, int is_group)
if(is_group==0) {
for(sock= node->outputs.first; sock; sock= sock->next) {
- bNodeStack *ns= ntree->stack[0] + sock->stack_index;
+ bNodeStack *ns= ntree->stack + sock->stack_index;
if(sock->ns.data) {
ns->data= sock->ns.data;
@@ -1662,7 +1839,7 @@ static void composit_end_exec(bNodeTree *ntree, int is_group)
bNodeSocket *sock;
for(sock= node->outputs.first; sock; sock= sock->next) {
- ns= ntree->stack[0] + sock->stack_index;
+ ns= ntree->stack + sock->stack_index;
if(ns->data) {
sock->ns.data= ns->data;
ns->data= NULL;
@@ -1680,7 +1857,7 @@ static void composit_end_exec(bNodeTree *ntree, int is_group)
if(is_group==0) {
/* internally, group buffers are not stored */
- for(ns= ntree->stack[0], a=0; a<ntree->stacksize; a++, ns++) {
+ for(ns= ntree->stack, a=0; a<ntree->stacksize; a++, ns++) {
if(ns->data) {
printf("freed leftover buffer from stack\n");
free_compbuf(ns->data);
@@ -1721,15 +1898,47 @@ static void group_tag_used_outputs(bNode *gnode, bNodeStack *stack)
/* per tree (and per group) unique indices are created */
/* the index_ext we need to be able to map from groups to the group-node own stack */
+typedef struct bNodeThreadStack {
+ struct bNodeThreadStack *next, *prev;
+ bNodeStack *stack;
+ int used;
+} bNodeThreadStack;
+
+static bNodeThreadStack *ntreeGetThreadStack(bNodeTree *ntree, int thread)
+{
+ ListBase *lb= &ntree->threadstack[thread];
+ bNodeThreadStack *nts;
+
+ for(nts=lb->first; nts; nts=nts->next) {
+ if(!nts->used) {
+ nts->used= 1;
+ return nts;
+ }
+ }
+
+ nts= MEM_callocN(sizeof(bNodeThreadStack), "bNodeThreadStack");
+ nts->stack= MEM_dupallocN(ntree->stack);
+ nts->used= 1;
+ BLI_addtail(lb, nts);
+
+ return nts;
+}
+
+static void ntreeReleaseThreadStack(bNodeThreadStack *nts)
+{
+ nts->used= 0;
+}
+
void ntreeBeginExecTree(bNodeTree *ntree)
{
/* let's make it sure */
if(ntree->init & NTREE_EXEC_INIT)
return;
-
- /* allocate the stack pointer array */
- ntree->stack= MEM_callocN(BLENDER_MAX_THREADS*sizeof(void *), "stack array");
-
+
+ /* allocate the thread stack listbase array */
+ if(ntree->type!=NTREE_COMPOSIT)
+ ntree->threadstack= MEM_callocN(BLENDER_MAX_THREADS*sizeof(ListBase), "thread stack array");
+
/* goes recursive over all groups */
ntree->stacksize= ntree_begin_exec_tree(ntree);
@@ -1739,7 +1948,7 @@ void ntreeBeginExecTree(bNodeTree *ntree)
int a;
/* allocate the base stack */
- ns=ntree->stack[0]= MEM_callocN(ntree->stacksize*sizeof(bNodeStack), "node stack");
+ ns=ntree->stack= MEM_callocN(ntree->stacksize*sizeof(bNodeStack), "node stack");
/* tag inputs, the get_stack() gives own socket stackdata if not in use */
for(a=0; a<ntree->stacksize; a++, ns++) ns->hasinput= 1;
@@ -1749,7 +1958,7 @@ void ntreeBeginExecTree(bNodeTree *ntree)
bNodeSocket *sock;
for(sock= node->inputs.first; sock; sock= sock->next) {
if(sock->link) {
- ns= ntree->stack[0] + sock->link->fromsock->stack_index;
+ ns= ntree->stack + sock->link->fromsock->stack_index;
ns->hasoutput= 1;
ns->sockettype= sock->link->fromsock->type;
}
@@ -1757,16 +1966,11 @@ void ntreeBeginExecTree(bNodeTree *ntree)
sock->ns.sockettype= sock->type;
}
if(node->type==NODE_GROUP && node->id)
- group_tag_used_outputs(node, ntree->stack[0]);
+ group_tag_used_outputs(node, ntree->stack);
}
- /* composite does 1 node per thread, so no multiple stacks needed */
if(ntree->type==NTREE_COMPOSIT)
composit_begin_exec(ntree, 0);
- else {
- for(a=1; a<BLENDER_MAX_THREADS; a++)
- ntree->stack[a]= MEM_dupallocN(ntree->stack[0]);
- }
}
ntree->init |= NTREE_EXEC_INIT;
@@ -1776,6 +1980,7 @@ void ntreeEndExecTree(bNodeTree *ntree)
{
if(ntree->init & NTREE_EXEC_INIT) {
+ bNodeThreadStack *nts;
int a;
/* another callback candidate! */
@@ -1783,14 +1988,21 @@ void ntreeEndExecTree(bNodeTree *ntree)
composit_end_exec(ntree, 0);
if(ntree->stack) {
- for(a=0; a<BLENDER_MAX_THREADS; a++)
- if(ntree->stack[a])
- MEM_freeN(ntree->stack[a]);
-
MEM_freeN(ntree->stack);
ntree->stack= NULL;
}
+ if(ntree->threadstack) {
+ for(a=0; a<BLENDER_MAX_THREADS; a++) {
+ for(nts=ntree->threadstack[a].first; nts; nts=nts->next)
+ if (nts->stack) MEM_freeN(nts->stack);
+ BLI_freelistN(&ntree->threadstack[a]);
+ }
+
+ MEM_freeN(ntree->threadstack);
+ ntree->threadstack= NULL;
+ }
+
ntree->init &= ~NTREE_EXEC_INIT;
}
}
@@ -1819,12 +2031,20 @@ void ntreeExecTree(bNodeTree *ntree, void *callerdata, int thread)
bNodeStack *nsin[MAX_SOCKET]; /* arbitrary... watch this */
bNodeStack *nsout[MAX_SOCKET]; /* arbitrary... watch this */
bNodeStack *stack;
+ bNodeThreadStack *nts = NULL;
/* only when initialized */
if((ntree->init & NTREE_EXEC_INIT)==0)
ntreeBeginExecTree(ntree);
- stack= ntree->stack[thread];
+ /* composite does 1 node per thread, so no multiple stacks needed */
+ if(ntree->type==NTREE_COMPOSIT) {
+ stack= ntree->stack;
+ }
+ else {
+ nts= ntreeGetThreadStack(ntree, thread);
+ stack= nts->stack;
+ }
for(node= ntree->nodes.first; node; node= node->next) {
if(node->typeinfo->execfunc) {
@@ -1836,10 +2056,34 @@ void ntreeExecTree(bNodeTree *ntree, void *callerdata, int thread)
node_group_execute(stack, callerdata, node, nsin, nsout);
}
}
+
+ if(nts)
+ ntreeReleaseThreadStack(nts);
}
/* ***************************** threaded version for execute composite nodes ************* */
+/* these are nodes without input, only giving values */
+/* or nodes with only value inputs */
+static int node_only_value(bNode *node)
+{
+ bNodeSocket *sock;
+
+ if(ELEM3(node->type, CMP_NODE_TIME, CMP_NODE_VALUE, CMP_NODE_RGB))
+ return 1;
+
+ /* doing this for all node types goes wrong. memory free errors */
+ if(node->inputs.first && node->type==CMP_NODE_MAP_VALUE) {
+ int retval= 1;
+ for(sock= node->inputs.first; sock; sock= sock->next) {
+ if(sock->link)
+ retval &= node_only_value(sock->link->fromnode);
+ }
+ return retval;
+ }
+ return 0;
+}
+
/* not changing info, for thread callback */
typedef struct ThreadData {
@@ -1856,7 +2100,14 @@ static void *exec_composite_node(void *node_v)
node_get_stack(node, thd->stack, nsin, nsout);
- if(node->typeinfo->execfunc) {
+ if((node->flag & NODE_MUTED) && (!node_only_value(node))) {
+ /* viewers we execute, for feedback to user */
+ if(ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
+ node->typeinfo->execfunc(thd->rd, node, nsin, nsout);
+ else
+ node_compo_pass_on(node, nsin, nsout);
+ }
+ else if(node->typeinfo->execfunc) {
node->typeinfo->execfunc(thd->rd, node, nsin, nsout);
}
else if(node->type==NODE_GROUP && node->id) {
@@ -1867,27 +2118,6 @@ static void *exec_composite_node(void *node_v)
return 0;
}
-/* these are nodes without input, only giving values */
-/* or nodes with only value inputs */
-static int node_only_value(bNode *node)
-{
- bNodeSocket *sock;
-
- if(ELEM3(node->type, CMP_NODE_TIME, CMP_NODE_VALUE, CMP_NODE_RGB))
- return 1;
-
- /* doing this for all node types goes wrong. memory free errors */
- if(node->inputs.first && node->type==CMP_NODE_MAP_VALUE) {
- int retval= 1;
- for(sock= node->inputs.first; sock; sock= sock->next) {
- if(sock->link)
- retval &= node_only_value(sock->link->fromnode);
- }
- return retval;
- }
- return 0;
-}
-
/* return total of executable nodes, for timecursor */
/* only compositor uses it */
static int setExecutableNodes(bNodeTree *ntree, ThreadData *thd)
@@ -2010,7 +2240,7 @@ static void freeExecutableNode(bNodeTree *ntree)
for(node= ntree->nodes.first; node; node= node->next) {
if(node->exec & NODE_FREEBUFS) {
for(sock= node->outputs.first; sock; sock= sock->next) {
- bNodeStack *ns= ntree->stack[0] + sock->stack_index;
+ bNodeStack *ns= ntree->stack + sock->stack_index;
if(ns->data) {
free_compbuf(ns->data);
ns->data= NULL;
@@ -2064,7 +2294,7 @@ void ntreeCompositExecTree(bNodeTree *ntree, RenderData *rd, int do_preview)
/* setup callerdata for thread callback */
thdata.rd= rd;
- thdata.stack= ntree->stack[0];
+ thdata.stack= ntree->stack;
/* fixed seed, for example noise texture */
BLI_srandom(rd->cfra);
@@ -2128,6 +2358,117 @@ void ntreeCompositExecTree(bNodeTree *ntree, RenderData *rd, int do_preview)
ntreeEndExecTree(ntree);
}
+/* GPU material from shader nodes */
+
+static void gpu_from_node_stack(ListBase *sockets, bNodeStack **ns, GPUNodeStack *gs)
+{
+ bNodeSocket *sock;
+ int i;
+
+ for (sock=sockets->first, i=0; sock; sock=sock->next, i++) {
+ memset(&gs[i], 0, sizeof(gs[i]));
+
+ QUATCOPY(gs[i].vec, ns[i]->vec);
+ gs[i].link= ns[i]->data;
+
+ if (sock->type == SOCK_VALUE)
+ gs[i].type= GPU_FLOAT;
+ else if (sock->type == SOCK_VECTOR)
+ gs[i].type= GPU_VEC3;
+ else if (sock->type == SOCK_RGBA)
+ gs[i].type= GPU_VEC4;
+ else
+ gs[i].type= GPU_NONE;
+
+ gs[i].name = "";
+ gs[i].hasinput= ns[i]->hasinput && ns[i]->data;
+ gs[i].hasoutput= ns[i]->hasinput && ns[i]->data;
+ gs[i].sockettype= ns[i]->sockettype;
+ }
+
+ gs[i].type= GPU_NONE;
+}
+
+static void data_from_gpu_stack(ListBase *sockets, bNodeStack **ns, GPUNodeStack *gs)
+{
+ bNodeSocket *sock;
+ int i;
+
+ for (sock=sockets->first, i=0; sock; sock=sock->next, i++) {
+ ns[i]->data= gs[i].link;
+ ns[i]->hasinput= gs[i].hasinput && gs[i].link;
+ ns[i]->hasoutput= gs[i].hasoutput;
+ ns[i]->sockettype= gs[i].sockettype;
+ }
+}
+
+static void gpu_node_group_execute(bNodeStack *stack, GPUMaterial *mat, bNode *gnode, bNodeStack **in, bNodeStack **out)
+{
+ bNode *node;
+ bNodeTree *ntree= (bNodeTree *)gnode->id;
+ bNodeStack *nsin[MAX_SOCKET]; /* arbitrary... watch this */
+ bNodeStack *nsout[MAX_SOCKET]; /* arbitrary... watch this */
+ GPUNodeStack gpuin[MAX_SOCKET+1], gpuout[MAX_SOCKET+1];
+ int doit = 0;
+
+ if(ntree==NULL) return;
+
+ stack+= gnode->stack_index;
+
+ for(node= ntree->nodes.first; node; node= node->next) {
+ if(node->typeinfo->gpufunc) {
+ group_node_get_stack(node, stack, nsin, nsout, in, out);
+
+ doit = 0;
+
+ /* for groups, only execute outputs for edited group */
+ if(node->typeinfo->nclass==NODE_CLASS_OUTPUT) {
+ if(gnode->flag & NODE_GROUP_EDIT)
+ if(node->flag & NODE_DO_OUTPUT)
+ doit = 1;
+ }
+ else
+ doit = 1;
+
+ if(doit) {
+ gpu_from_node_stack(&node->inputs, nsin, gpuin);
+ gpu_from_node_stack(&node->outputs, nsout, gpuout);
+ if(node->typeinfo->gpufunc(mat, node, gpuin, gpuout))
+ data_from_gpu_stack(&node->outputs, nsout, gpuout);
+ }
+ }
+ }
+}
+
+void ntreeGPUMaterialNodes(bNodeTree *ntree, GPUMaterial *mat)
+{
+ bNode *node;
+ bNodeStack *stack;
+ bNodeStack *nsin[MAX_SOCKET]; /* arbitrary... watch this */
+ bNodeStack *nsout[MAX_SOCKET]; /* arbitrary... watch this */
+ GPUNodeStack gpuin[MAX_SOCKET+1], gpuout[MAX_SOCKET+1];
+
+ if((ntree->init & NTREE_EXEC_INIT)==0)
+ ntreeBeginExecTree(ntree);
+
+ stack= ntree->stack;
+
+ for(node= ntree->nodes.first; node; node= node->next) {
+ if(node->typeinfo->gpufunc) {
+ node_get_stack(node, stack, nsin, nsout);
+ gpu_from_node_stack(&node->inputs, nsin, gpuin);
+ gpu_from_node_stack(&node->outputs, nsout, gpuout);
+ if(node->typeinfo->gpufunc(mat, node, gpuin, gpuout))
+ data_from_gpu_stack(&node->outputs, nsout, gpuout);
+ }
+ else if(node->type==NODE_GROUP && node->id) {
+ node_get_stack(node, stack, nsin, nsout);
+ gpu_node_group_execute(stack, mat, node, nsin, nsout);
+ }
+ }
+
+ ntreeEndExecTree(ntree);
+}
/* **************** call to switch lamploop for material node ************ */
@@ -2172,6 +2513,8 @@ static void force_hidden_passes(bNode *node, int passflag)
if(!(passflag & SCE_PASS_RADIO)) sock->flag |= SOCK_UNAVAIL;
sock= BLI_findlink(&node->outputs, RRES_OUT_INDEXOB);
if(!(passflag & SCE_PASS_INDEXOB)) sock->flag |= SOCK_UNAVAIL;
+ sock= BLI_findlink(&node->outputs, RRES_OUT_MIST);
+ if(!(passflag & SCE_PASS_MIST)) sock->flag |= SOCK_UNAVAIL;
}
@@ -2281,12 +2624,12 @@ void ntreeCompositTagGenerators(bNodeTree *ntree)
/* ************* node definition init ********** */
-static bNodeType *is_nodetype_registered(ListBase *typelist, int type)
+static bNodeType *is_nodetype_registered(ListBase *typelist, int type, ID *id)
{
bNodeType *ntype= typelist->first;
for(;ntype; ntype= ntype->next )
- if(ntype->type==type)
+ if(ntype->type==type && ntype->id==id)
return ntype;
return NULL;
@@ -2295,10 +2638,10 @@ static bNodeType *is_nodetype_registered(ListBase *typelist, int type)
/* type can be from a static array, we make copy for duplicate types (like group) */
void nodeRegisterType(ListBase *typelist, const bNodeType *ntype)
{
- bNodeType *found= is_nodetype_registered(typelist, ntype->type);
+ bNodeType *found= is_nodetype_registered(typelist, ntype->type, ntype->id);
if(found==NULL) {
- bNodeType *ntypen= MEM_mallocN(sizeof(bNodeType), "node type");
+ bNodeType *ntypen= MEM_callocN(sizeof(bNodeType), "node type");
*ntypen= *ntype;
BLI_addtail(typelist, ntypen);
}
@@ -2335,6 +2678,8 @@ static void registerCompositNodes(ListBase *ntypelist)
nodeRegisterType(ntypelist, &cmp_node_filter);
nodeRegisterType(ntypelist, &cmp_node_blur);
+ nodeRegisterType(ntypelist, &cmp_node_dblur);
+ nodeRegisterType(ntypelist, &cmp_node_bilateralblur);
nodeRegisterType(ntypelist, &cmp_node_vecblur);
nodeRegisterType(ntypelist, &cmp_node_dilateerode);
nodeRegisterType(ntypelist, &cmp_node_defocus);
@@ -2352,6 +2697,7 @@ static void registerCompositNodes(ListBase *ntypelist)
nodeRegisterType(ntypelist, &cmp_node_combyuva);
nodeRegisterType(ntypelist, &cmp_node_sepycca);
nodeRegisterType(ntypelist, &cmp_node_combycca);
+ nodeRegisterType(ntypelist, &cmp_node_premulkey);
nodeRegisterType(ntypelist, &cmp_node_diff_matte);
nodeRegisterType(ntypelist, &cmp_node_chroma);
@@ -2366,7 +2712,6 @@ static void registerCompositNodes(ListBase *ntypelist)
nodeRegisterType(ntypelist, &cmp_node_crop);
nodeRegisterType(ntypelist, &cmp_node_displace);
nodeRegisterType(ntypelist, &cmp_node_mapuv);
-
nodeRegisterType(ntypelist, &cmp_node_glare);
nodeRegisterType(ntypelist, &cmp_node_tonemap);
nodeRegisterType(ntypelist, &cmp_node_lensdist);
@@ -2393,12 +2738,46 @@ static void registerShaderNodes(ListBase *ntypelist)
nodeRegisterType(ntypelist, &sh_node_value);
nodeRegisterType(ntypelist, &sh_node_rgb);
nodeRegisterType(ntypelist, &sh_node_texture);
+ nodeRegisterType(ntypelist, &node_dynamic_typeinfo);
nodeRegisterType(ntypelist, &sh_node_invert);
nodeRegisterType(ntypelist, &sh_node_seprgb);
nodeRegisterType(ntypelist, &sh_node_combrgb);
nodeRegisterType(ntypelist, &sh_node_hue_sat);
}
+static void remove_dynamic_typeinfos(ListBase *list)
+{
+ bNodeType *ntype= list->first;
+ bNodeType *next= NULL;
+ while(ntype) {
+ next= ntype->next;
+ if(ntype->type==NODE_DYNAMIC && ntype->id!=NULL) {
+ BLI_remlink(list, ntype);
+ if(ntype->inputs) {
+ bNodeSocketType *sock= ntype->inputs;
+ while(sock->type!=-1) {
+ MEM_freeN(sock->name);
+ sock++;
+ }
+ MEM_freeN(ntype->inputs);
+ }
+ if(ntype->outputs) {
+ bNodeSocketType *sock= ntype->outputs;
+ while(sock->type!=-1) {
+ MEM_freeN(sock->name);
+ sock++;
+ }
+ MEM_freeN(ntype->outputs);
+ }
+ if(ntype->name) {
+ MEM_freeN(ntype->name);
+ }
+ MEM_freeN(ntype);
+ }
+ ntype= next;
+ }
+}
+
void init_nodesystem(void)
{
registerCompositNodes(&node_all_composit);
@@ -2407,8 +2786,8 @@ void init_nodesystem(void)
void free_nodesystem(void)
{
+ /*remove_dynamic_typeinfos(&node_all_composit);*/ /* unused for now */
BLI_freelistN(&node_all_composit);
+ remove_dynamic_typeinfos(&node_all_shaders);
BLI_freelistN(&node_all_shaders);
}
-
-
diff --git a/source/blender/blenkernel/intern/object.c b/source/blender/blenkernel/intern/object.c
index e5edd2239ff..2d7a5283b0c 100644
--- a/source/blender/blenkernel/intern/object.c
+++ b/source/blender/blenkernel/intern/object.c
@@ -50,6 +50,8 @@
#include "DNA_lattice_types.h"
#include "DNA_material_types.h"
#include "DNA_mesh_types.h"
+#include "DNA_meta_types.h"
+#include "DNA_curve_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_modifier_types.h"
#include "DNA_nla_types.h"
@@ -68,6 +70,7 @@
#include "BKE_armature.h"
#include "BKE_action.h"
+#include "BKE_bullet.h"
#include "BKE_colortools.h"
#include "BKE_deform.h"
#include "BKE_DerivedMesh.h"
@@ -87,7 +90,6 @@
#include "BKE_constraint.h"
#include "BKE_curve.h"
#include "BKE_displist.h"
-#include "BKE_effect.h"
#include "BKE_group.h"
#include "BKE_icons.h"
#include "BKE_ipo.h"
@@ -99,6 +101,7 @@
#include "BKE_modifier.h"
#include "BKE_object.h"
#include "BKE_particle.h"
+#include "BKE_pointcache.h"
#include "BKE_property.h"
#include "BKE_sca.h"
#include "BKE_scene.h"
@@ -107,7 +110,11 @@
#include "LBM_fluidsim.h"
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h"
+#endif
+
+#include "GPU_material.h"
/* Local function protos */
static void solve_parenting (Object *ob, Object *par, float obmat[][4], float slowmat[][4], int simul);
@@ -153,6 +160,33 @@ void update_base_layer(Object *ob)
}
}
+void object_free_particlesystems(Object *ob)
+{
+ while(ob->particlesystem.first){
+ ParticleSystem *psys = ob->particlesystem.first;
+
+ BLI_remlink(&ob->particlesystem,psys);
+
+ psys_free(ob,psys);
+ }
+}
+
+void object_free_softbody(Object *ob)
+{
+ if(ob->soft) {
+ sbFree(ob->soft);
+ ob->soft= NULL;
+ }
+}
+
+void object_free_bulletsoftbody(Object *ob)
+{
+ if(ob->bsoft) {
+ bsbFree(ob->bsoft);
+ ob->bsoft= NULL;
+ }
+}
+
void object_free_modifiers(Object *ob)
{
while (ob->modifiers.first) {
@@ -164,13 +198,10 @@ void object_free_modifiers(Object *ob)
}
/* particle modifiers were freed, so free the particlesystems as well */
- while(ob->particlesystem.first){
- ParticleSystem *psys = ob->particlesystem.first;
-
- BLI_remlink(&ob->particlesystem,psys);
+ object_free_particlesystems(ob);
- psys_free(ob,psys);
- }
+ /* same for softbody */
+ object_free_softbody(ob);
}
/* here we will collect all local displist stuff */
@@ -221,14 +252,12 @@ void free_object(Object *ob)
ob->path= 0;
if(ob->ipo) ob->ipo->id.us--;
if(ob->action) ob->action->id.us--;
+ if(ob->poselib) ob->poselib->id.us--;
if(ob->dup_group) ob->dup_group->id.us--;
if(ob->defbase.first)
BLI_freelistN(&ob->defbase);
- if(ob->pose) {
- free_pose_channels(ob->pose);
- MEM_freeN(ob->pose);
- }
- free_effects(&ob->effect);
+ if(ob->pose)
+ free_pose(ob->pose);
free_properties(&ob->prop);
object_free_modifiers(ob);
@@ -239,8 +268,10 @@ void free_object(Object *ob)
free_constraints(&ob->constraints);
free_constraint_channels(&ob->constraintChannels);
free_nlastrips(&ob->nlastrips);
-
+
+#ifndef DISABLE_PYTHON
BPY_free_scriptlink(&ob->scriptlink);
+#endif
if(ob->pd){
if(ob->pd->tex)
@@ -248,7 +279,8 @@ void free_object(Object *ob)
MEM_freeN(ob->pd);
}
if(ob->soft) sbFree(ob->soft);
- if(ob->fluidsimSettings) fluidsimSettingsFree(ob->fluidsimSettings);
+ if(ob->bsoft) bsbFree(ob->bsoft);
+ if(ob->gpulamp.first) GPU_lamp_free(ob);
}
static void unlink_object__unlinkModifierLinks(void *userData, Object *ob, Object **obpoin)
@@ -274,6 +306,7 @@ void unlink_object(Object *ob)
Camera *camera;
bConstraint *con;
bActionStrip *strip;
+ ModifierData *md;
int a;
unlink_controllers(&ob->controllers);
@@ -372,10 +405,13 @@ void unlink_object(Object *ob)
/* object is deflector or field */
if(ob->pd) {
- if(give_parteff(obt))
- obt->recalc |= OB_RECALC_DATA;
- else if(obt->soft)
+ if(obt->soft)
obt->recalc |= OB_RECALC_DATA;
+
+ /* cloth */
+ for(md=obt->modifiers.first; md; md=md->next)
+ if(md->type == eModifierType_Cloth)
+ obt->recalc |= OB_RECALC_DATA;
}
/* strips */
@@ -511,11 +547,11 @@ void unlink_object(Object *ob)
if(v3d->camera==ob) {
v3d->camera= NULL;
- if(v3d->persp>1) v3d->persp= 1;
+ if(v3d->persp==V3D_CAMOB) v3d->persp= V3D_PERSP;
}
if(v3d->localvd && v3d->localvd->camera==ob ) {
v3d->localvd->camera= NULL;
- if(v3d->localvd->persp>1) v3d->localvd->persp= 1;
+ if(v3d->localvd->persp==V3D_CAMOB) v3d->localvd->persp= V3D_PERSP;
}
}
else if(sl->spacetype==SPACE_IPO) {
@@ -602,9 +638,9 @@ Camera *copy_camera(Camera *cam)
camn= copy_libblock(cam);
id_us_plus((ID *)camn->ipo);
-
+#ifndef DISABLE_PYTHON
BPY_copy_scriptlink(&camn->scriptlink);
-
+#endif
return camn;
}
@@ -671,9 +707,11 @@ float dof_camera(Object *ob)
if (cam->dof_ob) {
/* too simple, better to return the distance on the view axis only
* return VecLenf(ob->obmat[3], cam->dof_ob->obmat[3]); */
+ float mat[4][4], obmat[4][4];
- float mat[4][4];
- Mat4Invert(ob->imat, ob->obmat);
+ Mat4CpyMat4(obmat, ob->obmat);
+ Mat4Ortho(obmat);
+ Mat4Invert(ob->imat, obmat);
Mat4MulMat4(mat, cam->dof_ob->obmat, ob->imat);
return fabs(mat[3][2]);
}
@@ -709,6 +747,22 @@ void *add_lamp(char *name)
la->preview=NULL;
la->falloff_type = LA_FALLOFF_INVLINEAR;
la->curfalloff = curvemapping_add(1, 0.0f, 1.0f, 1.0f, 0.0f);
+ la->sun_effect_type = 0;
+ la->horizon_brightness = 1.0;
+ la->spread = 1.0;
+ la->sun_brightness = 1.0;
+ la->sun_size = 1.0;
+ la->backscattered_light = 1.0;
+ la->atm_turbidity = 2.0;
+ la->atm_inscattering_factor = 1.0;
+ la->atm_extinction_factor = 1.0;
+ la->atm_distance_factor = 1.0;
+ la->sun_intensity = 1.0;
+ la->skyblendtype= MA_RAMP_ADD;
+ la->skyblendfac= 1.0f;
+ la->sky_colorspace= BLI_CS_CIE;
+ la->sky_exposure= 1.0f;
+
curvemapping_initialize(la->curfalloff);
return la;
}
@@ -733,9 +787,9 @@ Lamp *copy_lamp(Lamp *la)
id_us_plus((ID *)lan->ipo);
if (la->preview) lan->preview = BKE_previewimg_copy(la->preview);
-
+#ifndef DISABLE_PYTHON
BPY_copy_scriptlink(&la->scriptlink);
-
+#endif
return lan;
}
@@ -793,7 +847,9 @@ void make_local_lamp(Lamp *la)
void free_camera(Camera *ca)
{
+#ifndef DISABLE_PYTHON
BPY_free_scriptlink(&ca->scriptlink);
+#endif
}
void free_lamp(Lamp *la)
@@ -802,8 +858,9 @@ void free_lamp(Lamp *la)
int a;
/* scriptlinks */
-
+#ifndef DISABLE_PYTHON
BPY_free_scriptlink(&la->scriptlink);
+#endif
for(a=0; a<MAX_MTEX; a++) {
mtex= la->mtex[a];
@@ -879,10 +936,12 @@ Object *add_only_object(int type, char *name)
ob->type= type;
/* ob->transflag= OB_QUAT; */
+#if 0 /* not used yet */
QuatOne(ob->quat);
QuatOne(ob->dquat);
+#endif
- ob->col[0]= ob->col[1]= ob->col[2]= 0.0;
+ ob->col[0]= ob->col[1]= ob->col[2]= 1.0;
ob->col[3]= 1.0;
ob->loc[0]= ob->loc[1]= ob->loc[2]= 0.0;
@@ -919,8 +978,9 @@ Object *add_only_object(int type, char *name)
ob->anisotropicFriction[0] = 1.0f;
ob->anisotropicFriction[1] = 1.0f;
ob->anisotropicFriction[2] = 1.0f;
- ob->gameflag= OB_PROP;
-
+ ob->gameflag= OB_PROP|OB_COLLISION;
+ ob->margin = 0.0;
+
/* NT fluid sim defaults */
ob->fluidsimFlag = 0;
ob->fluidsimSettings = NULL;
@@ -971,11 +1031,13 @@ void base_init_from_view3d(Base *base, View3D *v3d)
if (U.flag & USER_ADD_VIEWALIGNED) {
v3d->viewquat[0]= -v3d->viewquat[0];
- if (ob->transflag & OB_QUAT) {
+
+ /* Quats arnt used yet */
+ /*if (ob->transflag & OB_QUAT) {
QUATCOPY(ob->quat, v3d->viewquat);
- } else {
+ } else {*/
QuatToEul(v3d->viewquat, ob->rot);
- }
+ /*}*/
v3d->viewquat[0]= -v3d->viewquat[0];
}
}
@@ -990,15 +1052,28 @@ SoftBody *copy_softbody(SoftBody *sb)
sbn->totspring= sbn->totpoint= 0;
sbn->bpoint= NULL;
sbn->bspring= NULL;
- sbn->ctime= 0.0f;
sbn->keys= NULL;
sbn->totkey= sbn->totpointkey= 0;
sbn->scratch= NULL;
+
+ sbn->pointcache= BKE_ptcache_copy(sb->pointcache);
+
return sbn;
}
+BulletSoftBody *copy_bulletsoftbody(BulletSoftBody *bsb)
+{
+ BulletSoftBody *bsbn;
+
+ if (bsb == NULL)
+ return NULL;
+ bsbn = MEM_dupallocN(bsb);
+ /* no pointer in this structure yet */
+ return bsbn;
+}
+
ParticleSystem *copy_particlesystem(ParticleSystem *psys)
{
ParticleSystem *psysn;
@@ -1016,23 +1091,63 @@ ParticleSystem *copy_particlesystem(ParticleSystem *psys)
pa->keys= MEM_dupallocN(pa->keys);
}
- if(psys->soft)
+ if(psys->soft) {
psysn->soft= copy_softbody(psys->soft);
+ psysn->soft->particles = psysn;
+ }
psysn->pathcache= NULL;
psysn->childcache= NULL;
psysn->edit= NULL;
psysn->effectors.first= psysn->effectors.last= 0;
+
+ psysn->pathcachebufs.first = psysn->pathcachebufs.last = NULL;
+ psysn->childcachebufs.first = psysn->childcachebufs.last = NULL;
+ psysn->reactevents.first = psysn->reactevents.last = NULL;
+ psysn->renderdata = NULL;
+
+ psysn->pointcache= BKE_ptcache_copy(psys->pointcache);
id_us_plus((ID *)psysn->part);
return psysn;
}
+void copy_object_particlesystems(Object *obn, Object *ob)
+{
+ ParticleSystemModifierData *psmd;
+ ParticleSystem *psys, *npsys;
+ ModifierData *md;
+
+ obn->particlesystem.first= obn->particlesystem.last= NULL;
+ for(psys=ob->particlesystem.first; psys; psys=psys->next) {
+ npsys= copy_particlesystem(psys);
+
+ BLI_addtail(&obn->particlesystem, npsys);
+
+ /* need to update particle modifiers too */
+ for(md=obn->modifiers.first; md; md=md->next) {
+ if(md->type==eModifierType_ParticleSystem) {
+ psmd= (ParticleSystemModifierData*)md;
+ if(psmd->psys==psys)
+ psmd->psys= npsys;
+ }
+ }
+ }
+}
+
+void copy_object_softbody(Object *obn, Object *ob)
+{
+ if(ob->soft)
+ obn->soft= copy_softbody(ob->soft);
+}
+
static void copy_object_pose(Object *obn, Object *ob)
{
bPoseChannel *chan;
+ /* note: need to clear obn->pose pointer first, so that copy_pose works (otherwise there's a crash) */
+ obn->pose= NULL;
copy_pose(&obn->pose, ob->pose, 1); /* 1 = copy constraints */
for (chan = obn->pose->chanbase.first; chan; chan=chan->next){
@@ -1045,7 +1160,10 @@ static void copy_object_pose(Object *obn, Object *ob)
ListBase targets = {NULL, NULL};
bConstraintTarget *ct;
- if(con->ipo) {
+ /* note that we can't change lib linked ipo blocks. for making
+ * proxies this still works correct however because the object
+ * is changed to object->proxy_from when evaluating the driver. */
+ if(con->ipo && !con->ipo->id.lib) {
IpoCurve *icu;
for(icu= con->ipo->curve.first; icu; icu= icu->next) {
if(icu->driver && icu->driver->ob==ob)
@@ -1072,7 +1190,6 @@ Object *copy_object(Object *ob)
{
Object *obn;
ModifierData *md;
- ParticleSystem *psys;
int a;
obn= copy_libblock(ob);
@@ -1085,7 +1202,6 @@ Object *copy_object(Object *ob)
obn->path= NULL;
obn->flag &= ~OB_FROMGROUP;
- copy_effects(&obn->effect, &ob->effect);
obn->modifiers.first = obn->modifiers.last= NULL;
for (md=ob->modifiers.first; md; md=md->next) {
@@ -1093,10 +1209,12 @@ Object *copy_object(Object *ob)
modifier_copyData(md, nmd);
BLI_addtail(&obn->modifiers, nmd);
}
-
+#ifndef DISABLE_PYTHON
BPY_copy_scriptlink(&ob->scriptlink);
-
+#endif
+ obn->prop.first = obn->prop.last = NULL;
copy_properties(&obn->prop, &ob->prop);
+
copy_sensors(&obn->sensors, &ob->sensors);
copy_controllers(&obn->controllers, &ob->controllers);
copy_actuators(&obn->actuators, &ob->actuators);
@@ -1129,32 +1247,9 @@ Object *copy_object(Object *ob)
id_us_plus(&(obn->pd->tex->id));
}
obn->soft= copy_softbody(ob->soft);
+ obn->bsoft = copy_bulletsoftbody(ob->bsoft);
- /* NT copy fluid sim setting memory */
- if(obn->fluidsimSettings) {
- obn->fluidsimSettings = fluidsimSettingsCopy(ob->fluidsimSettings);
- /* copying might fail... */
- if(obn->fluidsimSettings) {
- obn->fluidsimSettings->orgMesh = (Mesh *)obn->data;
- }
- }
-
- obn->particlesystem.first= obn->particlesystem.last= NULL;
- for(psys=ob->particlesystem.first; psys; psys=psys->next) {
- ParticleSystemModifierData *psmd;
- ParticleSystem *npsys= copy_particlesystem(psys);
-
- BLI_addtail(&obn->particlesystem, npsys);
-
- /* need to update particle modifiers too */
- for(md=obn->modifiers.first; md; md=md->next) {
- if(md->type==eModifierType_ParticleSystem) {
- psmd= (ParticleSystemModifierData*)md;
- if(psmd->psys==psys)
- psmd->psys= npsys;
- }
- }
- }
+ copy_object_particlesystems(obn, ob);
obn->derivedDeform = NULL;
obn->derivedFinal = NULL;
@@ -1163,6 +1258,7 @@ Object *copy_object(Object *ob)
obn->vnode = NULL;
#endif
+ obn->gpulamp.first = obn->gpulamp.last = NULL;
return obn;
}
@@ -1170,11 +1266,13 @@ Object *copy_object(Object *ob)
void expand_local_object(Object *ob)
{
bActionStrip *strip;
+ ParticleSystem *psys;
int a;
id_lib_extern((ID *)ob->action);
id_lib_extern((ID *)ob->ipo);
id_lib_extern((ID *)ob->data);
+ id_lib_extern((ID *)ob->dup_group);
for(a=0; a<ob->totcol; a++) {
id_lib_extern((ID *)ob->mat[a]);
@@ -1182,7 +1280,8 @@ void expand_local_object(Object *ob)
for (strip=ob->nlastrips.first; strip; strip=strip->next) {
id_lib_extern((ID *)strip->act);
}
-
+ for(psys=ob->particlesystem.first; psys; psys=psys->next)
+ id_lib_extern((ID *)psys->part);
}
void make_local_object(Object *ob)
@@ -1306,11 +1405,29 @@ void object_make_proxy(Object *ob, Object *target, Object *gob)
/* skip constraints, constraintchannels, nla? */
-
+ /* set object type and link to data */
ob->type= target->type;
ob->data= target->data;
id_us_plus((ID *)ob->data); /* ensures lib data becomes LIB_EXTERN */
+ /* copy material and index information */
+ ob->actcol= ob->totcol= 0;
+ if(ob->mat) MEM_freeN(ob->mat);
+ ob->mat = NULL;
+ if ((target->totcol) && (target->mat) && ELEM5(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL)) { //XXX OB_SUPPORT_MATERIAL
+ int i;
+ ob->colbits = target->colbits;
+
+ ob->actcol= target->actcol;
+ ob->totcol= target->totcol;
+
+ ob->mat = MEM_dupallocN(target->mat);
+ for(i=0; i<target->totcol; i++) {
+ /* dont need to run test_object_materials since we know this object is new and not used elsewhere */
+ id_us_plus((ID *)ob->mat[i]);
+ }
+ }
+
/* type conversions */
if(target->type == OB_ARMATURE) {
copy_object_pose(ob, target); /* data copy, object pointers in constraints */
@@ -1357,12 +1474,12 @@ float bsystem_time(Object *ob, float cfra, float ofs)
cfra*= G.scene->r.framelen;
if (ob) {
- if (no_speed_curve==0 && ob->ipo)
+ if (no_speed_curve==0 && ob->ipo)
cfra= calc_ipo_time(ob->ipo, cfra);
/* ofset frames */
if ((ob->ipoflag & OB_OFFS_PARENT) && (ob->partype & PARSLOW)==0)
- cfra-= ob->sf;
+ cfra-= give_timeoffset(ob);
}
cfra-= ofs;
@@ -1370,25 +1487,46 @@ float bsystem_time(Object *ob, float cfra, float ofs)
return cfra;
}
-void object_to_mat3(Object *ob, float mat[][3]) /* no parent */
+void object_scale_to_mat3(Object *ob, float mat[][3])
{
- float smat[3][3], vec[3];
- float rmat[3][3];
- float q1[4];
-
- /* size */
+ float vec[3];
if(ob->ipo) {
vec[0]= ob->size[0]+ob->dsize[0];
vec[1]= ob->size[1]+ob->dsize[1];
vec[2]= ob->size[2]+ob->dsize[2];
- SizeToMat3(vec, smat);
+ SizeToMat3(vec, mat);
}
else {
- SizeToMat3(ob->size, smat);
+ SizeToMat3(ob->size, mat);
}
+}
+
+void object_rot_to_mat3(Object *ob, float mat[][3])
+{
+ float vec[3];
+ if(ob->ipo) {
+ vec[0]= ob->rot[0]+ob->drot[0];
+ vec[1]= ob->rot[1]+ob->drot[1];
+ vec[2]= ob->rot[2]+ob->drot[2];
+ EulToMat3(vec, mat);
+ }
+ else {
+ EulToMat3(ob->rot, mat);
+ }
+}
+
+void object_to_mat3(Object *ob, float mat[][3]) /* no parent */
+{
+ float smat[3][3];
+ float rmat[3][3];
+ /*float q1[4];*/
+
+ /* size */
+ object_scale_to_mat3(ob, smat);
/* rot */
- if(ob->transflag & OB_QUAT) {
+ /* Quats arnt used yet */
+ /*if(ob->transflag & OB_QUAT) {
if(ob->ipo) {
QuatMul(q1, ob->quat, ob->dquat);
QuatToMat3(q1, rmat);
@@ -1397,17 +1535,9 @@ void object_to_mat3(Object *ob, float mat[][3]) /* no parent */
QuatToMat3(ob->quat, rmat);
}
}
- else {
- if(ob->ipo) {
- vec[0]= ob->rot[0]+ob->drot[0];
- vec[1]= ob->rot[1]+ob->drot[1];
- vec[2]= ob->rot[2]+ob->drot[2];
- EulToMat3(vec, rmat);
- }
- else {
- EulToMat3(ob->rot, rmat);
- }
- }
+ else {*/
+ object_rot_to_mat3(ob, rmat);
+ /*}*/
Mat3MulMat3(mat, rmat, smat);
}
@@ -1432,8 +1562,8 @@ int enable_cu_speed= 1;
static void ob_parcurve(Object *ob, Object *par, float mat[][4])
{
Curve *cu;
- float q[4], vec[4], dir[3], *quat, x1, ctime;
- float timeoffs= 0.0;
+ float q[4], vec[4], dir[3], quat[4], x1, ctime;
+ float timeoffs = 0.0, sf_orig = 0.0;
Mat4One(mat);
@@ -1444,7 +1574,8 @@ static void ob_parcurve(Object *ob, Object *par, float mat[][4])
/* exception, timeoffset is regarded as distance offset */
if(cu->flag & CU_OFFS_PATHDIST) {
- SWAP(float, timeoffs, ob->sf);
+ timeoffs = give_timeoffset(ob);
+ SWAP(float, sf_orig, ob->sf);
}
/* catch exceptions: feature for nla stride editing */
@@ -1461,7 +1592,7 @@ static void ob_parcurve(Object *ob, Object *par, float mat[][4])
}
}
else {
- ctime= G.scene->r.cfra - ob->sf;
+ ctime= G.scene->r.cfra - give_timeoffset(ob);
ctime /= cu->pathlen;
CLAMP(ctime, 0.0, 1.0);
@@ -1472,7 +1603,7 @@ static void ob_parcurve(Object *ob, Object *par, float mat[][4])
ctime += timeoffs/cu->path->totdist;
/* restore */
- SWAP(float, timeoffs, ob->sf);
+ SWAP(float, sf_orig, ob->sf);
}
@@ -1480,7 +1611,7 @@ static void ob_parcurve(Object *ob, Object *par, float mat[][4])
if( where_on_path(par, ctime, vec, dir) ) {
if(cu->flag & CU_FOLLOW) {
- quat= vectoquat(dir, ob->trackflag, ob->upflag);
+ vectoquat(dir, ob->trackflag, ob->upflag, quat);
/* the tilt */
Normalize(dir);
@@ -1541,7 +1672,7 @@ static void give_parvert(Object *par, int nr, float *vec)
for(eve= em->verts.first; eve; eve= eve->next) {
if(eve->keyindex==nr) {
- memcpy(vec, eve->co, 12);
+ memcpy(vec, eve->co, sizeof(float)*3);
break;
}
}
@@ -1563,9 +1694,12 @@ static void give_parvert(Object *par, int nr, float *vec)
}
}
- if(count > 0) {
+ if (count==0) {
+ /* keep as 0,0,0 */
+ } else if(count > 0) {
VecMulf(vec, 1.0f / count);
} else {
+ /* use first index if its out of range */
dm->getVertCo(dm, 0, vec);
}
}
@@ -1576,18 +1710,20 @@ static void give_parvert(Object *par, int nr, float *vec)
Curve *cu;
BPoint *bp;
BezTriple *bezt;
+ int found= 0;
cu= par->data;
nu= cu->nurb.first;
//XXX if(par==G.obedit) nu= editNurb.first;
count= 0;
- while(nu) {
+ while(nu && !found) {
if((nu->type & 7)==CU_BEZIER) {
bezt= nu->bezt;
a= nu->pntsu;
while(a--) {
if(count==nr) {
+ found= 1;
VECCOPY(vec, bezt->vec[1]);
break;
}
@@ -1600,7 +1736,8 @@ static void give_parvert(Object *par, int nr, float *vec)
a= nu->pntsu*nu->pntsv;
while(a--) {
if(count==nr) {
- memcpy(vec, bp->vec, 12);
+ found= 1;
+ memcpy(vec, bp->vec, sizeof(float)*3);
break;
}
count++;
@@ -1730,7 +1867,7 @@ void where_is_object_time(Object *ob, float ctime)
if(ob->parent) {
Object *par= ob->parent;
- if(ob->ipoflag & OB_OFFS_PARENT) ctime-= ob->sf;
+ if(ob->ipoflag & OB_OFFS_PARENT) ctime-= give_timeoffset(ob);
/* hurms, code below conflicts with depgraph... (ton) */
/* and even worse, it gives bad effects for NLA stride too (try ctime != par->ctime, with MBlur) */
@@ -1754,7 +1891,7 @@ void where_is_object_time(Object *ob, float ctime)
if(ob->partype & PARSLOW) {
// include framerate
- fac1= (1.0f/(1.0f+ fabs(ob->sf)));
+ fac1= (1.0f/(1.0f+ fabs(give_timeoffset(ob))));
if(fac1>=1.0) return;
fac2= 1.0f-fac1;
@@ -1788,10 +1925,11 @@ void where_is_object_time(Object *ob, float ctime)
constraints_clear_evalob(cob);
}
-
+#ifndef DISABLE_PYTHON
if(ob->scriptlink.totscript && !during_script()) {
if (G.f & G_DOSCRIPTLINKS) BPY_do_pyscript((ID *)ob, SCRIPT_REDRAW);
}
+#endif
/* set negative scale flag in object */
Crossf(vec, ob->obmat[0], ob->obmat[1]);
@@ -1880,13 +2018,13 @@ static void solve_parenting (Object *ob, Object *par, float obmat[][4], float sl
}
void solve_tracking (Object *ob, float targetmat[][4])
{
- float *quat;
+ float quat[4];
float vec[3];
float totmat[3][3];
float tmat[4][4];
VecSubf(vec, ob->obmat[3], targetmat[3]);
- quat= vectoquat(vec, ob->trackflag, ob->upflag);
+ vectoquat(vec, ob->trackflag, ob->upflag, quat);
QuatToMat3(quat, totmat);
if(ob->parent && (ob->transflag & OB_POWERTRACK)) {
@@ -1937,7 +2075,7 @@ for a lamp that is the child of another object */
if(ob->partype & PARSLOW) {
- fac1= (float)(1.0/(1.0+ fabs(ob->sf)));
+ fac1= (float)(1.0/(1.0+ fabs(give_timeoffset(ob))));
fac2= 1.0f-fac1;
fp1= ob->obmat[0];
fp2= slowmat[0];
@@ -1998,7 +2136,7 @@ BoundBox *unit_boundbox()
BoundBox *bb;
float min[3] = {-1,-1,-1}, max[3] = {-1,-1,-1};
- bb= MEM_mallocN(sizeof(BoundBox), "bb");
+ bb= MEM_callocN(sizeof(BoundBox), "bb");
boundbox_set_from_min_max(bb, min, max);
return bb;
@@ -2142,7 +2280,7 @@ void object_handle_update(Object *ob)
if(ob->recalc & OB_RECALC) {
if(ob->recalc & OB_RECALC_OB) {
-
+
// printf("recalcob %s\n", ob->id.name+2);
/* handle proxy copy for target */
@@ -2158,6 +2296,9 @@ void object_handle_update(Object *ob)
}
else
where_is_object(ob);
+#ifndef DISABLE_PYTHON
+ if (G.f & G_DOSCRIPTLINKS) BPY_do_pyscript((ID *)ob, SCRIPT_OBJECTUPDATE);
+#endif
}
if(ob->recalc & OB_RECALC_DATA) {
@@ -2177,6 +2318,16 @@ void object_handle_update(Object *ob)
else if(ob->type==OB_LATTICE) {
lattice_calc_modifiers(ob);
}
+ else if(ob->type==OB_CAMERA) {
+ Camera *cam = (Camera *)ob->data;
+ calc_ipo(cam->ipo, frame_to_float(G.scene->r.cfra));
+ execute_ipo(&cam->id, cam->ipo);
+ }
+ else if(ob->type==OB_LAMP) {
+ Lamp *la = (Lamp *)ob->data;
+ calc_ipo(la->ipo, frame_to_float(G.scene->r.cfra));
+ execute_ipo(&la->id, la->ipo);
+ }
else if(ob->type==OB_ARMATURE) {
/* this happens for reading old files and to match library armatures with poses */
if(ob->pose==NULL || (ob->pose->flag & POSE_RECALC))
@@ -2194,6 +2345,7 @@ void object_handle_update(Object *ob)
if(ob->particlesystem.first) {
ParticleSystem *tpsys, *psys;
+ DerivedMesh *dm;
psys= ob->particlesystem.first;
while(psys) {
@@ -2210,7 +2362,21 @@ void object_handle_update(Object *ob)
else
psys= psys->next;
}
+
+ if(G.rendering && ob->transflag & OB_DUPLIPARTS) {
+ /* this is to make sure we get render level duplis in groups:
+ * the derivedmesh must be created before init_render_mesh,
+ * since object_duplilist does dupliparticles before that */
+ dm = mesh_create_derived_render(ob, CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL);
+ dm->release(dm);
+
+ for(psys=ob->particlesystem.first; psys; psys=psys->next)
+ psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated;
+ }
}
+#ifndef DISABLE_PYTHON
+ if (G.f & G_DOSCRIPTLINKS) BPY_do_pyscript((ID *)ob, SCRIPT_OBDATAUPDATE);
+#endif
}
/* the no-group proxy case, we call update */
@@ -2230,3 +2396,78 @@ void object_handle_update(Object *ob)
// printf("set proxy pointer for later group stuff %s\n", ob->id.name);
}
}
+
+float give_timeoffset(Object *ob) {
+ if ((ob->ipoflag & OB_OFFS_PARENTADD) && ob->parent) {
+ return ob->sf + give_timeoffset(ob->parent);
+ } else {
+ return ob->sf;
+ }
+}
+
+int give_obdata_texspace(Object *ob, int **texflag, float **loc, float **size, float **rot) {
+
+ if (ob->data==NULL)
+ return 0;
+
+ switch (GS(((ID *)ob->data)->name)) {
+ case ID_ME:
+ {
+ Mesh *me= ob->data;
+ if (texflag) *texflag = &me->texflag;
+ if (loc) *loc = me->loc;
+ if (size) *size = me->size;
+ if (rot) *rot = me->rot;
+ break;
+ }
+ case ID_CU:
+ {
+ Curve *cu= ob->data;
+ if (texflag) *texflag = &cu->texflag;
+ if (loc) *loc = cu->loc;
+ if (size) *size = cu->size;
+ if (rot) *rot = cu->rot;
+ break;
+ }
+ case ID_MB:
+ {
+ MetaBall *mb= ob->data;
+ if (texflag) *texflag = &mb->texflag;
+ if (loc) *loc = mb->loc;
+ if (size) *size = mb->size;
+ if (rot) *rot = mb->rot;
+ break;
+ }
+ default:
+ return 0;
+ }
+ return 1;
+}
+
+/*
+ * Test a bounding box for ray intersection
+ * assumes the ray is already local to the boundbox space
+ */
+int ray_hit_boundbox(struct BoundBox *bb, float ray_start[3], float ray_normal[3])
+{
+ static int triangle_indexes[12][3] = {{0, 1, 2}, {0, 2, 3},
+ {3, 2, 6}, {3, 6, 7},
+ {1, 2, 6}, {1, 6, 5},
+ {5, 6, 7}, {4, 5, 7},
+ {0, 3, 7}, {0, 4, 7},
+ {0, 1, 5}, {0, 4, 5}};
+ int result = 0;
+ int i;
+
+ for (i = 0; i < 12 && result == 0; i++)
+ {
+ float lambda;
+ int v1, v2, v3;
+ v1 = triangle_indexes[i][0];
+ v2 = triangle_indexes[i][1];
+ v3 = triangle_indexes[i][2];
+ result = RayIntersectsTriangle(ray_start, ray_normal, bb->vec[v1], bb->vec[v2], bb->vec[v3], &lambda, NULL);
+ }
+
+ return result;
+}
diff --git a/source/blender/blenkernel/intern/packedFile.c b/source/blender/blenkernel/intern/packedFile.c
index ab67aa00fbd..22e4e8a8309 100644
--- a/source/blender/blenkernel/intern/packedFile.c
+++ b/source/blender/blenkernel/intern/packedFile.c
@@ -184,7 +184,7 @@ PackedFile * newPackedFile(char * filename)
// convert relative filenames to absolute filenames
strcpy(name, filename);
- BLI_convertstringcode(name, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(name, G.sce);
// open the file
// and create a PackedFile structure
@@ -285,7 +285,7 @@ int writePackedFile(char * filename, PackedFile *pf, int guimode)
if (guimode); //XXX waitcursor(1);
strcpy(name, filename);
- BLI_convertstringcode(name, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(name, G.sce);
if (BLI_exists(name)) {
for (number = 1; number <= 999; number++) {
@@ -316,11 +316,11 @@ int writePackedFile(char * filename, PackedFile *pf, int guimode)
if (remove_tmp) {
if (ret_value == RET_ERROR) {
- if (BLI_rename(tempname, name) == RET_ERROR) {
+ if (BLI_rename(tempname, name) != 0) {
if(guimode); //XXX error("Error restoring tempfile. Check files: '%s' '%s'", tempname, name);
}
} else {
- if (BLI_delete(tempname, 0, 0) == RET_ERROR) {
+ if (BLI_delete(tempname, 0, 0) != 0) {
if(guimode); //XXX error("Error deleting '%s' (ignored)");
}
}
@@ -350,7 +350,7 @@ int checkPackedFile(char * filename, PackedFile * pf)
char name[FILE_MAXDIR + FILE_MAXFILE];
strcpy(name, filename);
- BLI_convertstringcode(name, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(name, G.sce);
if (stat(name, &st)) {
ret_val = PF_NOFILE;
diff --git a/source/blender/blenkernel/intern/particle.c b/source/blender/blenkernel/intern/particle.c
index be69a0daaf7..32da154321e 100644
--- a/source/blender/blenkernel/intern/particle.c
+++ b/source/blender/blenkernel/intern/particle.c
@@ -46,6 +46,7 @@
#include "DNA_object_types.h"
#include "DNA_curve_types.h"
#include "DNA_key_types.h"
+#include "DNA_ipo_types.h"
#include "BLI_arithb.h"
#include "BLI_blenlib.h"
@@ -74,6 +75,7 @@
#include "BKE_modifier.h"
#include "BKE_mesh.h"
#include "BKE_cdderivedmesh.h"
+#include "BKE_pointcache.h"
#include "RE_render_ext.h"
@@ -149,6 +151,49 @@ char *psys_menu_string(Object *ob, int for_sb)
return str;
}
+
+/* we allocate path cache memory in chunks instead of a big continguous
+ * chunk, windows' memory allocater fails to find big blocks of memory often */
+
+#define PATH_CACHE_BUF_SIZE 1024
+
+static ParticleCacheKey **psys_alloc_path_cache_buffers(ListBase *bufs, int tot, int steps)
+{
+ LinkData *buf;
+ ParticleCacheKey **cache;
+ int i, totkey, totbufkey;
+
+ tot= MAX2(tot, 1);
+ totkey = 0;
+ cache = MEM_callocN(tot*sizeof(void*), "PathCacheArray");
+
+ while(totkey < tot) {
+ totbufkey= MIN2(tot-totkey, PATH_CACHE_BUF_SIZE);
+ buf= MEM_callocN(sizeof(LinkData), "PathCacheLinkData");
+ buf->data= MEM_callocN(sizeof(ParticleCacheKey)*totbufkey*steps, "ParticleCacheKey");
+
+ for(i=0; i<totbufkey; i++)
+ cache[totkey+i] = ((ParticleCacheKey*)buf->data) + i*steps;
+
+ totkey += totbufkey;
+ BLI_addtail(bufs, buf);
+ }
+
+ return cache;
+}
+
+static void psys_free_path_cache_buffers(ParticleCacheKey **cache, ListBase *bufs)
+{
+ LinkData *buf;
+
+ if(cache)
+ MEM_freeN(cache);
+
+ for(buf= bufs->first; buf; buf=buf->next)
+ MEM_freeN(buf->data);
+ BLI_freelistN(bufs);
+}
+
/************************************************/
/* Getting stuff */
/************************************************/
@@ -199,7 +244,7 @@ Object *psys_get_lattice(Object *ob, ParticleSystem *psys)
{
Object *lattice=0;
- if(!psys_in_edit_mode(psys)==0){
+ if(psys_in_edit_mode(psys)==0){
ModifierData *md = (ModifierData*)psys_get_modifier(ob,psys);
@@ -221,14 +266,14 @@ void psys_disable_all(Object *ob)
ParticleSystem *psys=ob->particlesystem.first;
for(; psys; psys=psys->next)
- psys->flag &= ~PSYS_ENABLED;
+ psys->flag |= PSYS_DISABLED;
}
void psys_enable_all(Object *ob)
{
ParticleSystem *psys=ob->particlesystem.first;
for(; psys; psys=psys->next)
- psys->flag |= PSYS_ENABLED;
+ psys->flag &= ~PSYS_DISABLED;
}
int psys_ob_has_hair(Object *ob)
{
@@ -247,10 +292,17 @@ int psys_in_edit_mode(ParticleSystem *psys)
int psys_check_enabled(Object *ob, ParticleSystem *psys)
{
ParticleSystemModifierData *psmd;
+ Mesh *me;
- if(!(psys->flag & PSYS_ENABLED))
+ if(psys->flag & PSYS_DISABLED || psys->flag & PSYS_DELETE)
return 0;
+ if(ob->type == OB_MESH) {
+ me= (Mesh*)ob->data;
+ if(me->mr && me->mr->current != 1)
+ return 0;
+ }
+
psmd= psys_get_modifier(ob, psys);
if(psys->renderdata) {
if(!(psmd->modifier.mode & eModifierMode_Render))
@@ -267,10 +319,17 @@ int psys_check_enabled(Object *ob, ParticleSystem *psys)
/************************************************/
void psys_free_settings(ParticleSettings *part)
{
- if(part->pd)
+ if(part->pd) {
MEM_freeN(part->pd);
+ part->pd = NULL;
+ }
+ if(part->pd2) {
+ MEM_freeN(part->pd2);
+ part->pd2 = NULL;
+ }
}
-void free_hair(ParticleSystem *psys)
+
+void free_hair(ParticleSystem *psys, int softbody)
{
ParticleData *pa;
int i, totpart=psys->totpart;
@@ -282,6 +341,11 @@ void free_hair(ParticleSystem *psys)
}
psys->flag &= ~PSYS_HAIR_DONE;
+
+ if(softbody && psys->soft) {
+ sbFree(psys->soft);
+ psys->soft = NULL;
+ }
}
void free_keyed_keys(ParticleSystem *psys)
{
@@ -290,39 +354,41 @@ void free_keyed_keys(ParticleSystem *psys)
}
void free_child_path_cache(ParticleSystem *psys)
{
- if(psys->childcache){
- if(psys->childcache[0])
- MEM_freeN(psys->childcache[0]);
-
- MEM_freeN(psys->childcache);
-
- psys->childcache = NULL;
- psys->totchildcache = 0;
- }
+ psys_free_path_cache_buffers(psys->childcache, &psys->childcachebufs);
+ psys->childcache = NULL;
+ psys->totchildcache = 0;
}
void psys_free_path_cache(ParticleSystem *psys)
{
- if(psys->pathcache){
- if(psys->pathcache[0])
- MEM_freeN(psys->pathcache[0]);
-
- MEM_freeN(psys->pathcache);
+ psys_free_path_cache_buffers(psys->pathcache, &psys->pathcachebufs);
+ psys->pathcache= NULL;
+ psys->totcached= 0;
- psys->pathcache = NULL;
- psys->totcached = 0;
+ free_child_path_cache(psys);
+}
+void psys_free_children(ParticleSystem *psys)
+{
+ if(psys->child) {
+ MEM_freeN(psys->child);
+ psys->child=0;
+ psys->totchild=0;
}
+
free_child_path_cache(psys);
}
/* free everything */
void psys_free(Object *ob, ParticleSystem * psys)
-{
+{
if(psys){
+ int nr = 0;
+ ParticleSystem * tpsys;
+
if(ob->particlesystem.first == NULL && G.f & G_PARTICLEEDIT)
G.f &= ~G_PARTICLEEDIT;
psys_free_path_cache(psys);
- free_hair(psys);
+ free_hair(psys, 1);
free_keyed_keys(psys);
@@ -342,17 +408,33 @@ void psys_free(Object *ob, ParticleSystem * psys)
if(psys->effectors.first)
psys_end_effectors(psys);
+
+ // check if we are last non-visible particle system
+ for(tpsys=ob->particlesystem.first; tpsys; tpsys=tpsys->next){
+ if(tpsys->part)
+ {
+ if(ELEM(tpsys->part->draw_as,PART_DRAW_OB,PART_DRAW_GR))
+ {
+ nr++;
+ break;
+ }
+ }
+ }
+ // clear do-not-draw-flag
+ if(!nr)
+ ob->transflag &= ~OB_DUPLIPARTS;
if(psys->part){
psys->part->id.us--;
psys->part=0;
}
- if(psys->soft){
- sbFree(psys->soft);
- psys->soft = 0;
- }
+ if(psys->reactevents.first)
+ BLI_freelistN(&psys->reactevents);
+ if(psys->pointcache)
+ BKE_ptcache_free(psys->pointcache);
+
MEM_freeN(psys);
}
}
@@ -362,7 +444,7 @@ void psys_free(Object *ob, ParticleSystem * psys)
* removing the previous data. this should be solved properly once */
typedef struct ParticleRenderElem {
- int curchild, totchild;
+ int curchild, totchild, reduce;
float lambda, t, scalemin, scalemax;
} ParticleRenderElem;
@@ -379,6 +461,7 @@ typedef struct ParticleRenderData {
int winx, winy;
int dosimplify;
+ int timeoffset;
ParticleRenderElem *elems;
int *origindex;
} ParticleRenderData;
@@ -391,7 +474,7 @@ static float psys_render_viewport_falloff(double rate, float dist, float width)
static float psys_render_projected_area(ParticleSystem *psys, float *center, float area, double vprate, float *viewport)
{
ParticleRenderData *data= psys->renderdata;
- float co[3], view[3], ortho1[3], ortho2[2], w, dx, dy, radius;
+ float co[4], view[3], ortho1[3], ortho2[3], w, dx, dy, radius;
/* transform to view space */
VECCOPY(co, center);
@@ -440,13 +523,15 @@ static float psys_render_projected_area(ParticleSystem *psys, float *center, flo
return area;
}
-void psys_render_set(Object *ob, ParticleSystem *psys, float viewmat[][4], float winmat[][4], int winx, int winy)
+void psys_render_set(Object *ob, ParticleSystem *psys, float viewmat[][4], float winmat[][4], int winx, int winy, int timeoffset)
{
ParticleRenderData*data;
ParticleSystemModifierData *psmd= psys_get_modifier(ob, psys);
if(!G.rendering)
return;
+ if(psys->renderdata)
+ return;
data= MEM_callocN(sizeof(ParticleRenderData), "ParticleRenderData");
@@ -474,6 +559,8 @@ void psys_render_set(Object *ob, ParticleSystem *psys, float viewmat[][4], float
data->winx= winx;
data->winy= winy;
+ data->timeoffset= timeoffset;
+
psys->renderdata= data;
}
@@ -515,8 +602,8 @@ void psys_render_restore(Object *ob, ParticleSystem *psys)
psmd->totdmface= data->totdmface;
psmd->flag &= ~eParticleSystemFlag_psys_updated;
- if(psys->part->from==PART_FROM_FACE && psmd->dm)
- psys_calc_dmfaces(ob, psmd->dm, psys);
+ if(psmd->dm)
+ psys_calc_dmcache(ob, psmd->dm, psys);
MEM_freeN(data);
psys->renderdata= NULL;
@@ -531,7 +618,7 @@ int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot)
ParticleRenderData *data;
ParticleRenderElem *elems, *elem;
ParticleSettings *part= ctx->psys->part;
- float *facearea, (*facecenter)[3], size[3], fac, powrate;
+ float *facearea, (*facecenter)[3], size[3], fac, powrate, scaleclamp;
float co1[3], co2[3], co3[3], co4[3], lambda, arearatio, t, area, viewport;
double vprate;
int *origindex, *facetotvert;
@@ -539,7 +626,13 @@ int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot)
if(part->draw_as!=PART_DRAW_PATH || !(part->draw & PART_DRAW_REN_STRAND))
return tot;
- if(!ctx->psys->renderdata || !(part->simplify_flag & PART_SIMPLIFY_ENABLE))
+ if(!ctx->psys->renderdata)
+ return tot;
+
+ data= ctx->psys->renderdata;
+ if(data->timeoffset)
+ return 0;
+ if(!(part->simplify_flag & PART_SIMPLIFY_ENABLE))
return tot;
mvert= dm->getVertArray(dm);
@@ -556,7 +649,9 @@ int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot)
facetotvert= MEM_callocN(sizeof(int)*totorigface, "SimplifyFaceArea");
elems= MEM_callocN(sizeof(ParticleRenderElem)*totorigface, "SimplifyFaceElem");
- data= ctx->psys->renderdata;
+ if(data->elems)
+ MEM_freeN(data->elems);
+
data->dosimplify= 1;
data->elems= elems;
data->origindex= origindex;
@@ -614,19 +709,30 @@ int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot)
area = psys_render_projected_area(ctx->psys, facecenter[a], facearea[a], vprate, &viewport);
arearatio= fac*area/facearea[a];
- if(arearatio < 1.0f || viewport < 1.0f) {
+ if((arearatio < 1.0f || viewport < 1.0f) && elem->totchild) {
/* lambda is percentage of elements to keep */
lambda= (arearatio < 1.0f)? pow(arearatio, powrate): 1.0f;
lambda *= viewport;
+ lambda= MAX2(lambda, 1.0f/elem->totchild);
+
/* compute transition region */
t= part->simplify_transition;
elem->t= (lambda-t < 0.0f)? lambda: (lambda+t > 1.0f)? 1.0f-lambda: t;
+ elem->reduce= 1;
/* scale at end and beginning of the transition region */
elem->scalemax= (lambda+t < 1.0f)? 1.0f/lambda: 1.0f/(1.0f - elem->t*elem->t/t);
elem->scalemin= (lambda+t < 1.0f)? 0.0f: elem->scalemax*(1.0f-elem->t/t);
+ elem->scalemin= sqrt(elem->scalemin);
+ elem->scalemax= sqrt(elem->scalemax);
+
+ /* clamp scaling */
+ scaleclamp= MIN2(elem->totchild, 10.0f);
+ elem->scalemin= MIN2(scaleclamp, elem->scalemin);
+ elem->scalemax= MIN2(scaleclamp, elem->scalemax);
+
/* extend lambda to include transition */
lambda= lambda + elem->t;
if(lambda > 1.0f)
@@ -637,6 +743,7 @@ int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot)
elem->scalemax= 1.0f; //sqrt(lambda);
elem->scalemin= 1.0f; //sqrt(lambda);
+ elem->reduce= 0;
}
elem->lambda= lambda;
@@ -698,7 +805,7 @@ int psys_render_simplify_params(ParticleSystem *psys, ChildParticle *cpa, float
scalemin= elem->scalemin;
scalemax= elem->scalemax;
- if(lambda >= 1.0f) {
+ if(!elem->reduce) {
scale= scalemin;
alpha= 1.0f;
}
@@ -746,7 +853,7 @@ static void weighted_particle_vector(float *v1, float *v2, float *v3, float *v4,
vec[1]= weights[0]*v1[1] + weights[1]*v2[1] + weights[2]*v3[1] + weights[3]*v4[1];
vec[2]= weights[0]*v1[2] + weights[1]*v2[2] + weights[2]*v3[2] + weights[3]*v4[2];
}
-static void interpolate_particle(short type, ParticleKey keys[4], float dt, ParticleKey *result)
+static void interpolate_particle(short type, ParticleKey keys[4], float dt, ParticleKey *result, int velocity)
{
float t[4];
@@ -758,18 +865,20 @@ static void interpolate_particle(short type, ParticleKey keys[4], float dt, Part
weighted_particle_vector(keys[0].co, keys[1].co, keys[2].co, keys[3].co, t, result->co);
- //if(ve){
- // if(dt>0.999f){
- // set_four_ipo(dt+0.001f,t,ipo_type);
- // weighted_particle_vector(key0->co,key1->co,key2->co,key3->co,t,temp);
- // VECSUB(ve,temp,co);
- // }
- // else{
- // set_four_ipo(dt-0.001f,t,ipo_type);
- // weighted_particle_vector(key0->co,key1->co,key2->co,key3->co,t,temp);
- // VECSUB(ve,co,temp);
- // }
- //}
+ if(velocity){
+ float temp[3];
+
+ if(dt>0.999f){
+ set_four_ipo(dt-0.001f, t, type);
+ weighted_particle_vector(keys[0].co, keys[1].co, keys[2].co, keys[3].co, t, temp);
+ VECSUB(result->vel, result->co, temp);
+ }
+ else{
+ set_four_ipo(dt+0.001f, t, type);
+ weighted_particle_vector(keys[0].co, keys[1].co, keys[2].co, keys[3].co, t, temp);
+ VECSUB(result->vel, temp, result->co);
+ }
+ }
}
}
@@ -910,7 +1019,8 @@ void psys_interpolate_face(MVert *mvert, MFace *mface, MTFace *tface, float (*or
}
}
}
-void psys_interpolate_uvs(MTFace *tface, int quad, float *w, float *uvco){
+void psys_interpolate_uvs(MTFace *tface, int quad, float *w, float *uvco)
+{
float v10= tface->uv[0][0];
float v11= tface->uv[0][1];
float v20= tface->uv[1][0];
@@ -931,9 +1041,35 @@ void psys_interpolate_uvs(MTFace *tface, int quad, float *w, float *uvco){
uvco[1]= w[0]*v11 + w[1]*v21 + w[2]*v31;
}
}
+
+void psys_interpolate_mcol(MCol *mcol, int quad, float *w, MCol *mc)
+{
+ char *cp, *cp1, *cp2, *cp3, *cp4;
+
+ cp= (char *)mc;
+ cp1= (char *)&mcol[0];
+ cp2= (char *)&mcol[1];
+ cp3= (char *)&mcol[2];
+
+ if(quad) {
+ cp4= (char *)&mcol[3];
+
+ cp[0]= (int)(w[0]*cp1[0] + w[1]*cp2[0] + w[2]*cp3[0] + w[3]*cp4[0]);
+ cp[1]= (int)(w[0]*cp1[1] + w[1]*cp2[1] + w[2]*cp3[1] + w[3]*cp4[1]);
+ cp[2]= (int)(w[0]*cp1[2] + w[1]*cp2[2] + w[2]*cp3[2] + w[3]*cp4[2]);
+ cp[3]= (int)(w[0]*cp1[3] + w[1]*cp2[3] + w[2]*cp3[3] + w[3]*cp4[3]);
+ }
+ else {
+ cp[0]= (int)(w[0]*cp1[0] + w[1]*cp2[0] + w[2]*cp3[0]);
+ cp[1]= (int)(w[0]*cp1[1] + w[1]*cp2[1] + w[2]*cp3[1]);
+ cp[2]= (int)(w[0]*cp1[2] + w[1]*cp2[2] + w[2]*cp3[2]);
+ cp[3]= (int)(w[0]*cp1[3] + w[1]*cp2[3] + w[2]*cp3[3]);
+ }
+}
+
float psys_interpolate_value_from_verts(DerivedMesh *dm, short from, int index, float *fw, float *values)
{
- if(values==0)
+ if(values==0 || index==-1)
return 0.0;
switch(from){
@@ -979,8 +1115,8 @@ static void psys_origspace_to_w(OrigSpaceFace *osface, int quad, float *w, float
}
}
-/* find the derived mesh face for a particle, set the mf passed.
-This is slow, can be optimized but only for many lookups, return the face lookup index*/
+/* find the derived mesh face for a particle, set the mf passed. this is slow
+ * and can be optimized but only for many lookups. returns the face index. */
int psys_particle_dm_face_lookup(Object *ob, DerivedMesh *dm, int index, float *fw, struct LinkNode *node)
{
Mesh *me= (Mesh*)ob->data;
@@ -1013,7 +1149,7 @@ int psys_particle_dm_face_lookup(Object *ob, DerivedMesh *dm, int index, float *
if(node) { /* we have a linked list of faces that we use, faster! */
for(;node; node=node->next) {
- findex= (int)node->link;
+ findex= GET_INT_FROM_POINTER(node->link);
faceuv= osface[findex].uv;
quad= mface[findex].v4;
@@ -1048,131 +1184,142 @@ int psys_particle_dm_face_lookup(Object *ob, DerivedMesh *dm, int index, float *
return DMCACHE_NOTFOUND;
}
-/* interprets particle data to get a point on a mesh in object space */
-#define PARTICLE_ERROR(_nor, _vec) _vec[0]=_vec[1]=_vec[2]=0.0; if(_nor){ _nor[0]=_nor[1]=0.0; _nor[2]=1.0; }
-void psys_particle_on_dm(Object *ob, DerivedMesh *dm, int from, int index, int index_dmcache, float *fw, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor)
+static int psys_map_index_on_dm(DerivedMesh *dm, int from, int index, int index_dmcache, float *fw, float foffset, int *mapindex, float *mapfw)
{
- float (*orcodata)[3];
-
- if(index < 0){ /* 'no dm' error has happened! */
- PARTICLE_ERROR(nor, vec);
- return;
- }
- orcodata= dm->getVertDataArray(dm, CD_ORCO);
+ if(index < 0)
+ return 0;
if (dm->deformedOnly || index_dmcache == DMCACHE_ISCHILD) {
- /* this works for meshes with deform verts only - constructive modifiers wont work properly*/
- float temp1[3];
-
+ /* for meshes that are either only defined or for child particles, the
+ * index and fw do not require any mapping, so we can directly use it */
if(from == PART_FROM_VERT) {
- if(index >= dm->getNumVerts(dm)) {
- PARTICLE_ERROR(nor, vec);
- return;
- }
-
- dm->getVertCo(dm,index,vec);
- if(nor){
- dm->getVertNo(dm,index,nor);
- Normalize(nor);
- }
- if(orco)
- VECCOPY(orco, orcodata[index])
- if(ornor) {
- dm->getVertNo(dm,index,nor);
- Normalize(nor);
- }
- }
- else { /* PART_FROM_FACE / PART_FROM_VOLUME */
- MFace *mface;
- MTFace *mtface=0;
- MVert *mvert;
- int uv_index;
-
- if(index >= dm->getNumFaces(dm)) {
- PARTICLE_ERROR(nor, vec);
- return;
- }
-
- mface=dm->getFaceData(dm,index,CD_MFACE);
- mvert=dm->getVertDataArray(dm,CD_MVERT);
- uv_index=CustomData_get_active_layer_index(&dm->faceData,CD_MTFACE);
+ if(index >= dm->getNumVerts(dm))
+ return 0;
- if(uv_index>=0){
- CustomDataLayer *layer=&dm->faceData.layers[uv_index];
- mtface= &((MTFace*)layer->data)[index];
- }
+ *mapindex = index;
+ }
+ else { /* FROM_FACE/FROM_VOLUME */
+ if(index >= dm->getNumFaces(dm))
+ return 0;
- if(from==PART_FROM_VOLUME){
- psys_interpolate_face(mvert,mface,mtface,orcodata,fw,vec,temp1,utan,vtan,orco,ornor);
- if(nor)
- VECCOPY(nor,temp1);
- Normalize(temp1);
- VecMulf(temp1,-foffset);
- VECADD(vec,vec,temp1);
- }
- else
- psys_interpolate_face(mvert,mface,mtface,orcodata,fw,vec,nor,utan,vtan,orco,ornor);
+ *mapindex = index;
+ QUATCOPY(mapfw, fw);
}
} else {
- /* Need to support constructive modifiers, this is a bit more tricky
- we need a customdata layer like UV's so we can position the particle */
-
- /* Only face supported at the moment */
- if (from==PART_FROM_FACE) {
+ /* for other meshes that have been modified, we try to map the particle
+ * to their new location, which means a different index, and for faces
+ * also a new face interpolation weights */
+ if(from == PART_FROM_VERT) {
+ if (index_dmcache == DMCACHE_NOTFOUND || index_dmcache > dm->getNumVerts(dm))
+ return 0;
+
+ *mapindex = index_dmcache;
+ }
+ else { /* FROM_FACE/FROM_VOLUME */
/* find a face on the derived mesh that uses this face */
- Mesh *me= (Mesh*)ob->data;
- MVert *mvert;
MFace *mface;
- MTFace *mtface;
OrigSpaceFace *osface;
- int *origindex;
- float fw_mod[4];
- int i, totface;
-
- mvert= dm->getVertDataArray(dm,CD_MVERT);
+ int i;
+
+ i = index_dmcache;
+
+ if(i== DMCACHE_NOTFOUND || i >= dm->getNumFaces(dm))
+ return 0;
+
+ *mapindex = i;
+ /* modify the original weights to become
+ * weights for the derived mesh face */
osface= dm->getFaceDataArray(dm, CD_ORIGSPACE);
- origindex= dm->getFaceDataArray(dm, CD_ORIGINDEX);
+ mface= dm->getFaceData(dm, i, CD_MFACE);
- /* For this to work we need origindex and OrigSpace coords */
- if(origindex==NULL || osface==NULL || index>=me->totface) {
- PARTICLE_ERROR(nor, vec);
- return;
- }
-
- if (index_dmcache == DMCACHE_NOTFOUND)
- i = psys_particle_dm_face_lookup(ob, dm, index, fw, (LinkNode*)NULL);
+ if(osface == NULL)
+ mapfw[0]= mapfw[1]= mapfw[2]= mapfw[3]= 0.0f;
else
- i = index_dmcache;
+ psys_origspace_to_w(&osface[i], mface->v4, fw, mapfw);
+ }
+ }
- totface = dm->getNumFaces(dm);
+ return 1;
+}
- /* Any time this happens, and the face has not been removed,
- * its a BUG watch out for this error! */
- if (i==-1) {
- printf("Cannot find original face %i\n", index);
- PARTICLE_ERROR(nor, vec);
- return;
- }
- else if(i >= totface)
- return;
+/* interprets particle data to get a point on a mesh in object space */
+void psys_particle_on_dm(DerivedMesh *dm, int from, int index, int index_dmcache, float *fw, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor)
+{
+ float tmpnor[3], mapfw[4];
+ float (*orcodata)[3];
+ int mapindex;
- mface= dm->getFaceData(dm, i, CD_MFACE);
- mtface= dm->getFaceData(dm, i, CD_MTFACE);
- osface += i;
+ if(!psys_map_index_on_dm(dm, from, index, index_dmcache, fw, foffset, &mapindex, mapfw)) {
+ if(vec) { vec[0]=vec[1]=vec[2]=0.0; }
+ if(nor) { nor[0]=nor[1]=0.0; nor[2]=1.0; }
+ if(orco) { orco[0]=orco[1]=orco[2]=0.0; }
+ if(ornor) { ornor[0]=ornor[1]=0.0; ornor[2]=1.0; }
+ if(utan) { utan[0]=utan[1]=utan[2]=0.0; }
+ if(vtan) { vtan[0]=vtan[1]=vtan[2]=0.0; }
- /* we need to modify the original weights to become weights for
- * the derived mesh face */
- psys_origspace_to_w(osface, mface->v4, fw, fw_mod);
- psys_interpolate_face(mvert,mface,mtface,orcodata,fw_mod,vec,nor,utan,vtan,orco,ornor);
+ return;
+ }
+
+ orcodata= dm->getVertDataArray(dm, CD_ORCO);
+
+ if(from == PART_FROM_VERT) {
+ dm->getVertCo(dm,mapindex,vec);
+
+ if(nor) {
+ dm->getVertNo(dm,mapindex,nor);
+ Normalize(nor);
}
- else {
- /* TODO PARTICLE - support verts and volume */
- PARTICLE_ERROR(nor, vec);
+
+ if(orco)
+ VECCOPY(orco, orcodata[mapindex])
+
+ if(ornor) {
+ dm->getVertNo(dm,mapindex,nor);
+ Normalize(nor);
}
+
+ if(utan && vtan) {
+ utan[0]= utan[1]= utan[2]= 0.0f;
+ vtan[0]= vtan[1]= vtan[2]= 0.0f;
+ }
+ }
+ else { /* PART_FROM_FACE / PART_FROM_VOLUME */
+ MFace *mface;
+ MTFace *mtface;
+ MVert *mvert;
+
+ mface=dm->getFaceData(dm,mapindex,CD_MFACE);
+ mvert=dm->getVertDataArray(dm,CD_MVERT);
+ mtface=CustomData_get_layer(&dm->faceData,CD_MTFACE);
+
+ if(mtface)
+ mtface += mapindex;
+
+ if(from==PART_FROM_VOLUME) {
+ psys_interpolate_face(mvert,mface,mtface,orcodata,mapfw,vec,tmpnor,utan,vtan,orco,ornor);
+ if(nor)
+ VECCOPY(nor,tmpnor);
+
+ Normalize(tmpnor);
+ VecMulf(tmpnor,-foffset);
+ VECADD(vec,vec,tmpnor);
+ }
+ else
+ psys_interpolate_face(mvert,mface,mtface,orcodata,mapfw,vec,nor,utan,vtan,orco,ornor);
}
}
-#undef PARTICLE_ERROR
+
+float psys_particle_value_from_verts(DerivedMesh *dm, short from, ParticleData *pa, float *values)
+{
+ float mapfw[4];
+ int mapindex;
+
+ if(!psys_map_index_on_dm(dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, &mapindex, mapfw))
+ return 0.0f;
+
+ return psys_interpolate_value_from_verts(dm, from, mapindex, mapfw, values);
+}
ParticleSystemModifierData *psys_get_modifier(Object *ob, ParticleSystem *psys)
{
@@ -1193,7 +1340,7 @@ ParticleSystemModifierData *psys_get_modifier(Object *ob, ParticleSystem *psys)
/* Particles on a shape */
/************************************************/
/* ready for future use */
-void psys_particle_on_shape(int distr, int index, float *fuv, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor)
+static void psys_particle_on_shape(int distr, int index, float *fuv, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor)
{
/* TODO */
float zerovec[3]={0.0f,0.0f,0.0f};
@@ -1219,16 +1366,16 @@ void psys_particle_on_shape(int distr, int index, float *fuv, float *vec, float
/************************************************/
/* Particles on emitter */
/************************************************/
-void psys_particle_on_emitter(Object *ob, ParticleSystemModifierData *psmd, int from, int index, int index_dmcache, float *fuv, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor){
+void psys_particle_on_emitter(ParticleSystemModifierData *psmd, int from, int index, int index_dmcache, float *fuv, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor){
if(psmd){
- if(psmd->psys->part->distr==PART_DISTR_GRID){
+ if(psmd->psys->part->distr==PART_DISTR_GRID && psmd->psys->part->from != PART_FROM_VERT){
if(vec){
VECCOPY(vec,fuv);
}
return;
}
/* we cant use the num_dmcache */
- psys_particle_on_dm(ob, psmd->dm,from,index,index_dmcache,fuv,foffset,vec,nor,utan,vtan,orco,ornor);
+ psys_particle_on_dm(psmd->dm,from,index,index_dmcache,fuv,foffset,vec,nor,utan,vtan,orco,ornor);
}
else
psys_particle_on_shape(from,index,fuv,vec,nor,utan,vtan,orco,ornor);
@@ -1263,7 +1410,7 @@ static float vert_weight(MDeformVert *dvert, int group)
}
static void do_prekink(ParticleKey *state, ParticleKey *par, float *par_rot, float time, float freq, float shape, float amplitude, short type, short axis, float obmat[][4])
{
- float vec[3]={0.0,0.0,0.0}, q1[4]={1,0,0,0},*q2;
+ float vec[3]={0.0,0.0,0.0}, q1[4]={1,0,0,0},q2[4];
float t;
CLAMP(time,0.0,1.0);
@@ -1285,10 +1432,9 @@ static void do_prekink(ParticleKey *state, ParticleKey *par, float *par_rot, flo
case PART_KINK_CURL:
vec[axis]=1.0;
if(par_rot)
- q2=par_rot;
- else{
- q2=vectoquat(par->vel,axis,(axis+1)%3);
- }
+ QUATCOPY(q2,par_rot)
+ else
+ vectoquat(par->vel,axis,(axis+1)%3, q2);
QuatMulVecf(q2,vec);
VecMulf(vec,amplitude);
VECADD(state->co,state->co,vec);
@@ -1335,9 +1481,9 @@ static void do_prekink(ParticleKey *state, ParticleKey *par, float *par_rot, flo
float inp_y,inp_z,length;
if(par_rot)
- q2=par_rot;
+ QUATCOPY(q2,par_rot)
else
- q2=vectoquat(par->vel,axis,(axis+1)%3);
+ vectoquat(par->vel,axis,(axis+1)%3,q2);
QuatMulVecf(q2,y_vec);
QuatMulVecf(q2,z_vec);
@@ -1394,59 +1540,6 @@ static void do_prekink(ParticleKey *state, ParticleKey *par, float *par_rot, flo
}
}
break;
- //case PART_KINK_ROT:
- // vec[axis]=1.0;
-
- // QuatMulVecf(par->rot,vec);
-
- // VecMulf(vec,amplitude*(float)sin(t));
-
- // VECADD(state->co,state->co,vec);
- // break;
- }
-}
-static void do_postkink(ParticleKey *state, ParticleKey *par, float *par_rot, float time, float freq, float shape, float amplitude, short type, short axis, float obmat[][4])
-{
- static ParticleKey first;
- static float q[4];
- float vec[3]={0.0,0.0,0.0};
- float t;
-
- CLAMP(time,0.0,1.0);
-
- t=time;
-
- t*=(float)M_PI*freq;
-
- if(par==0) return;
-
- switch(type){
- case PART_KINK_ROLL:
- if(time<(0.5+shape/2.0f)){
- float *q2;
- memcpy(&first,state,sizeof(ParticleKey));
- Normalize(first.vel);
- if(par_rot)
- q2=par_rot;
- else
- q2=vectoquat(par->vel,axis,(axis+1)%3);
- QUATCOPY(q,q2);
- }
- else{
- float fac;
- shape=0.5f+shape/2.0f;
- t-=(float)M_PI*(shape*freq + 0.5f);
-
- vec[axis]=1.0;
-
- QuatMulVecf(q,vec);
-
- fac=amplitude*(1.0f+((1.0f-time)/(1.0f-shape)*(float)sin(t)));
- VECADDFAC(state->co,first.co,vec,fac);
- fac=amplitude*((1.0f-time)/(1.0f-shape)*(float)cos(t));
- VECADDFAC(state->co,state->co,first.vel,fac);
- }
- break;
}
}
static void do_clump(ParticleKey *state, ParticleKey *par, float time, float clumpfac, float clumppow, float pa_clump)
@@ -1539,7 +1632,7 @@ int do_guide(ParticleKey *state, int pa_num, float time, ListBase *lb)
VecRotToQuat(guidedir,guidevec[3]-ec->firstloc[3],rot2);
QuatMulVecf(rot2,pa_loc);
- //q=vectoquat(guidedir, pd->kink_axis, (pd->kink_axis+1)%3);
+ //vectoquat(guidedir, pd->kink_axis, (pd->kink_axis+1)%3, q);
//QuatMul(par.rot,rot2,q);
}
//else{
@@ -1553,13 +1646,11 @@ int do_guide(ParticleKey *state, int pa_num, float time, ListBase *lb)
/* TODO */
//else{
///* curve size*/
- // calc_curve_subdiv_radius(cu,cu->nurb.first,((Nurb*)cu->nurb.first)->
//}
par.co[0]=par.co[1]=par.co[2]=0.0f;
VECCOPY(key.co,pa_loc);
do_prekink(&key, &par, 0, guidetime, pd->kink_freq, pd->kink_shape, pd->kink_amp, pd->kink, pd->kink_axis, 0);
do_clump(&key, &par, guidetime, pd->clump_fac, pd->clump_pow, 1.0f);
- do_postkink(&key, &par, 0, guidetime, pd->kink_freq, pd->kink_shape, pd->kink_amp, pd->kink, pd->kink_axis, 0);
VECCOPY(pa_loc,key.co);
VECADD(pa_loc,pa_loc,guidevec);
@@ -1626,40 +1717,46 @@ static void do_rough_end(float *loc, float t, float fac, float shape, ParticleKe
VECADD(state->co,state->co,rough);
}
+static void do_path_effectors(Object *ob, ParticleSystem *psys, int i, ParticleCacheKey *ca, int k, int steps, float *rootco, float effector, float dfra, float cfra, float *length, float *vec)
+{
+ float force[3] = {0.0f,0.0f,0.0f}, vel[3] = {0.0f,0.0f,0.0f};
+ ParticleKey eff_key;
+ ParticleData *pa;
+
+ VECCOPY(eff_key.co,(ca-1)->co);
+ VECCOPY(eff_key.vel,(ca-1)->vel);
+ QUATCOPY(eff_key.rot,(ca-1)->rot);
+
+ pa= psys->particles+i;
+ do_effectors(i, pa, &eff_key, ob, psys, rootco, force, vel, dfra, cfra);
+
+ VecMulf(force, effector*pow((float)k / (float)steps, 100.0f * psys->part->eff_hair) / (float)steps);
+
+ VecAddf(force, force, vec);
+
+ Normalize(force);
+
+ if(k < steps) {
+ VecSubf(vec, (ca+1)->co, ca->co);
+ *length = VecLength(vec);
+ }
+
+ VECADDFAC(ca->co, (ca-1)->co, force, *length);
+}
static int check_path_length(int k, ParticleCacheKey *keys, ParticleCacheKey *state, float max_length, float *cur_length, float length, float *dvec)
{
if(*cur_length + length > max_length){
- //if(p<totparent){
- // if(k<=(int)cache[totpart+p]->time){
- // /* parents need to be calculated fully first so that they don't mess up their children */
- // /* we'll make a note of where we got to though so that they're easy to finish later */
- // state->time=(max_length-*cur_length)/length;
- // cache[totpart+p]->time=(float)k;
- // }
- //}
- //else{
VecMulf(dvec, (max_length - *cur_length) / length);
VECADD(state->co, (state - 1)->co, dvec);
keys->steps = k;
/* something over the maximum step value */
return k=100000;
- //}
}
else {
*cur_length+=length;
return k;
}
}
-static void finalize_path_length(ParticleCacheKey *keys)
-{
- ParticleCacheKey *state = keys;
- float dvec[3];
- state += state->steps;
-
- VECSUB(dvec, state->co, (state - 1)->co);
- VecMulf(dvec, state->steps);
- VECADD(state->co, (state - 1)->co, dvec);
-}
static void offset_child(ChildParticle *cpa, ParticleKey *par, ParticleKey *child, float flat, float radius)
{
VECCOPY(child->co,cpa->fuv);
@@ -1709,14 +1806,14 @@ void psys_find_parents(Object *ob, ParticleSystemModifierData *psmd, ParticleSys
tree=BLI_kdtree_new(totparent);
for(p=0,cpa=psys->child; p<totparent; p++,cpa++){
- psys_particle_on_emitter(ob,psmd,from,cpa->num,-1,cpa->fuv,cpa->foffset,co,0,0,0,orco,0);
+ psys_particle_on_emitter(psmd,from,cpa->num,-1,cpa->fuv,cpa->foffset,co,0,0,0,orco,0);
BLI_kdtree_insert(tree, p, orco, NULL);
}
BLI_kdtree_balance(tree);
for(; p<totchild; p++,cpa++){
- psys_particle_on_emitter(ob,psmd,from,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co,0,0,0,orco,0);
+ psys_particle_on_emitter(psmd,from,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co,0,0,0,orco,0);
cpa->parent=BLI_kdtree_find_nearest(tree, orco, NULL, NULL);
}
@@ -1817,6 +1914,8 @@ int psys_threads_init_path(ParticleThread *threads, float cfra, int editupdate)
ctx->vg_rough1 = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGH1);
ctx->vg_rough2 = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGH2);
ctx->vg_roughe = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGHE);
+ if(psys->part->flag & PART_CHILD_EFFECT)
+ ctx->vg_effector = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_EFFECTOR);
}
/* set correct ipo timing */
@@ -1838,14 +1937,15 @@ void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa,
ParticleCacheKey **cache= psys->childcache;
ParticleCacheKey **pcache= psys->pathcache;
ParticleCacheKey *state, *par = NULL, *key[4];
- ParticleData *pa;
+ ParticleData *pa=NULL;
ParticleTexture ptex;
float *cpa_fuv=0;
float co[3], orco[3], ornor[3], t, rough_t, cpa_1st[3], dvec[3];
float branch_begin, branch_end, branch_prob, branchfac, rough_rand;
float pa_rough1, pa_rough2, pa_roughe;
- float length, pa_length, pa_clump, pa_kink;
+ float length, pa_length, pa_clump, pa_kink, pa_effector;
float max_length = 1.0f, cur_length = 0.0f;
+ float eff_length, eff_vec[3];
int k, cpa_num, guided=0;
short cpa_from;
@@ -1905,7 +2005,7 @@ void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa,
cpa_fuv = cpa->fuv;
cpa_from = PART_FROM_FACE;
- psys_particle_on_emitter(ob,ctx->psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa->fuv,foffset,co,ornor,0,0,orco,0);
+ psys_particle_on_emitter(ctx->psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa->fuv,foffset,co,ornor,0,0,orco,0);
/* we need to save the actual root position of the child for positioning it accurately to the surface of the emitter */
VECCOPY(cpa_1st,co);
@@ -1931,7 +2031,7 @@ void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa,
cpa_num=pa->num;
cpa_fuv=pa->fuv;
- psys_particle_on_emitter(ob,ctx->psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa_fuv,pa->foffset,co,ornor,0,0,orco,0);
+ psys_particle_on_emitter(ctx->psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa_fuv,pa->foffset,co,ornor,0,0,orco,0);
}
keys->steps = ctx->steps;
@@ -1958,6 +2058,7 @@ void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa,
pa_rough1=ptex.rough;
pa_rough2=ptex.rough;
pa_roughe=ptex.rough;
+ pa_effector= 1.0f;
if(ctx->vg_length)
pa_length*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_length);
@@ -1971,16 +2072,17 @@ void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa,
pa_rough2*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_rough2);
if(ctx->vg_roughe)
pa_roughe*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_roughe);
+ if(ctx->vg_effector)
+ pa_effector*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_effector);
/* create the child path */
for(k=0,state=keys; k<=ctx->steps; k++,state++){
- t=(float)k/(float)ctx->steps;
-
if(ctx->between){
int w=0;
state->co[0] = state->co[1] = state->co[2] = 0.0f;
state->vel[0] = state->vel[1] = state->vel[2] = 0.0f;
+ state->rot[0] = state->rot[1] = state->rot[2] = state->rot[3] = 0.0f;
//QUATCOPY(state->rot,key[0]->rot);
@@ -2009,6 +2111,23 @@ void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa,
key[0]++;
}
+ }
+
+ /* apply effectors */
+ if(part->flag & PART_CHILD_EFFECT) {
+ for(k=0,state=keys; k<=ctx->steps; k++,state++) {
+ if(k) {
+ do_path_effectors(ob, psys, cpa->pa[0], state, k, ctx->steps, keys->co, pa_effector, 0.0f, ctx->cfra, &eff_length, eff_vec);
+ }
+ else {
+ VecSubf(eff_vec,(state+1)->co,state->co);
+ eff_length= VecLength(eff_vec);
+ }
+ }
+ }
+
+ for(k=0,state=keys; k<=ctx->steps; k++,state++){
+ t=(float)k/(float)ctx->steps;
if(ctx->totparent){
if(i>=ctx->totparent)
@@ -2023,8 +2142,9 @@ void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa,
}
/* apply different deformations to the child path */
- if(part->flag & PART_CHILD_GUIDE)
- guided = do_guide((ParticleKey*)state, i, t, &(psys->effectors)); //safe to cast, since only co and vel are used
+ if(part->flag & PART_CHILD_EFFECT)
+ /* state is safe to cast, since only co and vel are used */
+ guided = do_guide((ParticleKey*)state, cpa->parent, t, &(psys->effectors));
if(guided==0){
if(part->kink)
@@ -2032,10 +2152,6 @@ void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa,
part->kink_freq * pa_kink, part->kink_shape, part->kink_amp, part->kink, part->kink_axis, ob->obmat);
do_clump((ParticleKey*)state, (ParticleKey*)par, t, part->clumpfac, part->clumppow, pa_clump);
-
- if(part->kink)
- do_postkink((ParticleKey*)state, (ParticleKey*)par, par->rot, t,
- part->kink_freq * pa_kink, part->kink_shape, part->kink_amp, part->kink, part->kink_axis, ob->obmat);
}
if(part->flag & PART_BRANCHING && ctx->between == 0 && part->flag & PART_ANIM_BRANCHING)
@@ -2044,7 +2160,7 @@ void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa,
rough_t = t;
if(part->rough1 != 0.0 && pa_rough1 != 0.0)
- do_rough(orco, rough_t, pa_rough1*part->rough1, part->rough1_size, 0.0, (ParticleKey*)state);
+ do_rough(orco, rough_t, pa_rough1*part->rough1, part->rough1_size, 0.0, (ParticleKey*)state);
if(part->rough2 != 0.0 && pa_rough2 != 0.0)
do_rough(cpa->rand, rough_t, pa_rough2*part->rough2, part->rough2_size, part->rough2_thres, (ParticleKey*)state);
@@ -2122,13 +2238,9 @@ void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa,
get_strand_normal(ctx->ma, ornor, cur_length, state->vel);
}
}
-
- /* now let's finalise the interpolated parents that we might have left half done before */
- if(i<ctx->totparent)
- finalize_path_length(keys);
}
-void *exec_child_path_cache(void *data)
+static void *exec_child_path_cache(void *data)
{
ParticleThread *thread= (ParticleThread*)data;
ParticleThreadContext *ctx= thread->ctx;
@@ -2149,11 +2261,11 @@ void psys_cache_child_paths(Object *ob, ParticleSystem *psys, float cfra, int ed
ParticleSettings *part = psys->part;
ParticleThread *pthreads;
ParticleThreadContext *ctx;
- ParticleCacheKey **cache, *tcache;
+ ParticleCacheKey **cache;
ListBase threads;
int i, totchild, totparent, totthread;
- pthreads= psys_threads_create(ob, psys, G.scene->r.threads);
+ pthreads= psys_threads_create(ob, psys);
if(!psys_threads_init_path(pthreads, cfra, editupdate)) {
psys_threads_free(pthreads);
@@ -2170,12 +2282,7 @@ void psys_cache_child_paths(Object *ob, ParticleSystem *psys, float cfra, int ed
else {
/* clear out old and create new empty path cache */
free_child_path_cache(psys);
-
- cache = psys->childcache = MEM_callocN(totchild*sizeof(void *), "Child path cache array");
- tcache = MEM_callocN(totchild * (ctx->steps + 1) * sizeof(ParticleCacheKey), "Child path cache");
- for(i=0; i<totchild; i++)
- cache[i] = tcache + i * (ctx->steps + 1);
-
+ psys->childcache= psys_alloc_path_cache_buffers(&psys->childcachebufs, totchild, ctx->steps+1);
psys->totchildcache = totchild;
}
@@ -2204,6 +2311,7 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
ParticleCacheKey *ca, **cache=psys->pathcache;
ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys);
ParticleEditSettings *pset = &G.scene->toolsettings->particle;
+ ParticleSettings *part = psys->part;
ParticleData *pa;
ParticleKey keys[4], result, *kkey[2] = {NULL, NULL};
@@ -2218,7 +2326,7 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
Material *ma;
float birthtime = 0.0, dietime = 0.0;
- float t, time, keytime, dfra = 1.0, frs_sec = G.scene->r.frs_sec;
+ float t, time = 0.0, keytime = 0.0, dfra = 1.0, frs_sec = G.scene->r.frs_sec;
float col[3] = {0.5f, 0.5f, 0.5f};
float prev_tangent[3], hairmat[4][4];
int k,i;
@@ -2227,6 +2335,10 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
char nosel[4], sel[4];
float sel_col[3];
float nosel_col[3];
+ float length, vec[3];
+ float *vg_effector= NULL, effector=0.0f;
+ float *vg_length= NULL, pa_length=1.0f, max_length=1.0f, cur_length=0.0f;
+ float len, dvec[3];
/* we don't have anything valid to create paths from so let's quit here */
if((psys->flag & PSYS_HAIR_DONE)==0 && (psys->flag & PSYS_KEYED)==0)
@@ -2260,21 +2372,28 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
else {
/* clear out old and create new empty path cache */
psys_free_path_cache(psys);
-
- /* allocate cache array for fast access and set pointers to contiguous mem block */
- cache = psys->pathcache = MEM_callocN(MAX2(1, totpart) * sizeof(void *), "Path cache array");
- cache[0] = MEM_callocN(totpart * (steps + 1) * sizeof(ParticleCacheKey), "Path cache");
- for(i=1; i<totpart; i++)
- cache[i] = cache[0] + i * (steps + 1);
+ cache= psys_alloc_path_cache_buffers(&psys->pathcachebufs, totpart, steps+1);
+ psys->pathcache= cache;
}
- if(edit==NULL && psys->soft && psys->softflag & OB_SB_ENABLE)
+ if(edit==NULL && psys->soft && psys->softflag & OB_SB_ENABLE) {
soft = psys->soft;
+ if(!soft->bpoint)
+ soft= NULL;
+ }
psys->lattice = psys_get_lattice(ob, psys);
ma= give_current_material(ob, psys->part->omat);
if(ma && (psys->part->draw & PART_DRAW_MAT_COL))
VECCOPY(col, &ma->r)
+
+ if(psys->part->from!=PART_FROM_PARTICLE) {
+ if(!(psys->part->flag & PART_CHILD_EFFECT))
+ vg_effector = psys_cache_vgroup(psmd->dm, psys, PSYS_VG_EFFECTOR);
+
+ if(!edit && !psys->totchild)
+ vg_length = psys_cache_vgroup(psmd->dm, psys, PSYS_VG_LENGTH);
+ }
/*---first main loop: create all actual particles' paths---*/
for(i=0,pa=psys->particles; i<totpart; i++, pa++){
@@ -2287,6 +2406,12 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
if(editupdate && !(pa->flag & PARS_EDIT_RECALC)) continue;
else memset(cache[i], 0, sizeof(*cache[i])*(steps+1));
+ if(!edit && !psys->totchild) {
+ pa_length = part->length * (1.0f - part->randlength*pa->r_ave[0]);
+ if(vg_length)
+ pa_length *= psys_particle_value_from_verts(psmd->dm,part->from,pa,vg_length);
+ }
+
cache[i]->steps = steps;
if(edit)
@@ -2368,7 +2493,7 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
if(soft) {
if(hkey[1] != pa->hair + pa->totkey - 1)
- bp_to_particle(keys + 3, bp[1], hkey[1] + 1);
+ bp_to_particle(keys + 3, bp[1] + 1, hkey[1] + 1);
else
bp_to_particle(keys + 3, bp[1], hkey[1]);
}
@@ -2393,8 +2518,7 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
/* now we should have in chronologiacl order k1<=k2<=t<=k3<=k4 with keytime between [0,1]->[k2,k3] (k1 & k4 used for cardinal & bspline interpolation)*/
interpolate_particle((psys->flag & PSYS_KEYED) ? -1 /* signal for cubic interpolation */
: ((psys->part->flag & PART_HAIR_BSPLINE) ? KEY_BSPLINE : KEY_CARDINAL)
- ,keys, keytime, &result);
-
+ ,keys, keytime, &result, 0);
/* the velocity needs to be converted back from cubic interpolation */
if(psys->flag & PSYS_KEYED){
@@ -2403,38 +2527,92 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
else if(soft==NULL) { /* softbody and keyed are allready in global space */
Mat4MulVecfl(hairmat, result.co);
}
-
+
+ VECCOPY(ca->co, result.co);
+
+ /* selection coloring in edit mode */
+ if(edit){
+ if(pset->brushtype==PE_BRUSH_WEIGHT){
+ if(k==steps)
+ VecLerpf(ca->col, nosel_col, sel_col, hkey[0]->weight);
+ else
+ VecLerpf(ca->col, nosel_col, sel_col,
+ (1.0f - keytime) * hkey[0]->weight + keytime * hkey[1]->weight);
+ }
+ else{
+ if((ekey + (hkey[0] - pa->hair))->flag & PEK_SELECT){
+ if((ekey + (hkey[1] - pa->hair))->flag & PEK_SELECT){
+ VECCOPY(ca->col, sel_col);
+ }
+ else{
+ VecLerpf(ca->col, sel_col, nosel_col, keytime);
+ }
+ }
+ else{
+ if((ekey + (hkey[1] - pa->hair))->flag & PEK_SELECT){
+ VecLerpf(ca->col, nosel_col, sel_col, keytime);
+ }
+ else{
+ VECCOPY(ca->col, nosel_col);
+ }
+ }
+ }
+ }
+ else{
+ VECCOPY(ca->col, col);
+ }
+ }
+
+ /*--modify paths--*/
+
+ VecSubf(vec,(cache[i]+1)->co,cache[i]->co);
+ length = VecLength(vec);
+
+ effector= 1.0f;
+ if(vg_effector)
+ effector*= psys_particle_value_from_verts(psmd->dm,psys->part->from,pa,vg_effector);
+
+ for(k=0, ca=cache[i]; k<=steps; k++, ca++) {
+ /* apply effectors */
+ if(!(psys->part->flag & PART_CHILD_EFFECT) && edit==0 && k)
+ do_path_effectors(ob, psys, i, ca, k, steps, cache[i]->co, effector, dfra, cfra, &length, vec);
/* apply guide curves to path data */
- if(edit==0 && psys->effectors.first && (psys->part->flag & PART_CHILD_GUIDE)==0)
- do_guide(&result, i, time, &psys->effectors);
+ if(edit==0 && psys->effectors.first && (psys->part->flag & PART_CHILD_EFFECT)==0)
+ /* ca is safe to cast, since only co and vel are used */
+ do_guide((ParticleKey*)ca, i, (float)k/(float)steps, &psys->effectors);
+
+ /* apply lattice */
+ if(psys->lattice && edit==0)
+ calc_latt_deform(ca->co, 1.0f);
/* figure out rotation */
if(k) {
- float angle, tangent[3], normal[3], q[4];
+ float cosangle, angle, tangent[3], normal[3], q[4];
if(k == 1) {
- float *q2;
-
- VECSUB(tangent, result.co, (ca - 1)->co);
+ VECSUB(tangent, ca->co, (ca - 1)->co);
- q2 = vectoquat(tangent, OB_POSX, OB_POSZ);
-
- QUATCOPY((ca - 1)->rot, q2);
+ vectoquat(tangent, OB_POSX, OB_POSZ, (ca-1)->rot);
VECCOPY(prev_tangent, tangent);
Normalize(prev_tangent);
}
else {
- VECSUB(tangent, result.co, (ca - 1)->co);
+ VECSUB(tangent, ca->co, (ca - 1)->co);
Normalize(tangent);
- angle = saacos(Inpf(tangent, prev_tangent));
- if((angle > -0.000001) && (angle < 0.000001)){
+ cosangle= Inpf(tangent, prev_tangent);
+
+ /* note we do the comparison on cosangle instead of
+ * angle, since floating point accuracy makes it give
+ * different results across platforms */
+ if(cosangle > 0.999999f) {
QUATCOPY((ca - 1)->rot, (ca - 2)->rot);
}
- else{
+ else {
+ angle= saacos(cosangle);
Crossf(normal, prev_tangent, tangent);
VecRotToQuat(normal, angle, q);
QuatMul((ca - 1)->rot, q, (ca - 2)->rot);
@@ -2443,13 +2621,13 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
VECCOPY(prev_tangent, tangent);
}
- if(k == steps) {
+ if(k == steps)
QUATCOPY(ca->rot, (ca - 1)->rot);
- }
}
- VECCOPY(ca->co, result.co);
+ /* set velocity */
+
if(k){
VECSUB(ca->vel, ca->co, (ca-1)->co);
@@ -2459,40 +2637,27 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
}
- /* selection coloring in edit mode */
- if(edit){
- if(pset->brushtype==PE_BRUSH_WEIGHT){
- if(k==steps)
- VecLerpf(ca->col, nosel_col, sel_col, hkey[0]->weight);
+ if(!edit && !psys->totchild) {
+ /* check if path needs to be cut before actual end of data points */
+ if(k){
+ VECSUB(dvec,ca->co,(ca-1)->co);
+ if(part->flag&PART_ABS_LENGTH)
+ len=VecLength(dvec);
else
- VecLerpf(ca->col,nosel_col,sel_col,
- (1.0f - keytime) * hkey[0]->weight + keytime * hkey[1]->weight);
+ len=1.0f/(float)steps;
+
+ k=check_path_length(k,cache[i],ca,max_length,&cur_length,len,dvec);
}
else{
- if((ekey + (hkey[0] - pa->hair))->flag & PEK_SELECT){
- if((ekey + (hkey[1] - pa->hair))->flag & PEK_SELECT){
- VECCOPY(ca->col, sel_col);
- }
- else{
- VecLerpf(ca->col, sel_col, nosel_col, keytime);
- }
- }
- else{
- if((ekey + (hkey[1] - pa->hair))->flag & PEK_SELECT){
- VecLerpf(ca->col, nosel_col, sel_col, keytime);
- }
- else{
- VECCOPY(ca->col, nosel_col);
- }
- }
+ /* initialize length calculation */
+ if(part->flag&PART_ABS_LENGTH)
+ max_length= part->abslength*pa_length;
+ else
+ max_length= pa_length;
+
+ cur_length= 0.0f;
}
}
- else{
- VECCOPY(ca->col, col);
- }
-
- if(psys->lattice && edit==0)
- calc_latt_deform(ca->co, 1.0f);
}
}
@@ -2502,6 +2667,12 @@ void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupda
end_latt_deform();
psys->lattice=0;
}
+
+ if(vg_effector)
+ MEM_freeN(vg_effector);
+
+ if(vg_length)
+ MEM_freeN(vg_length);
}
/************************************************/
/* Particle Key handling */
@@ -2640,7 +2811,7 @@ void psys_mat_hair_to_object(Object *ob, DerivedMesh *dm, short from, ParticleDa
float vec[3];
psys_face_mat(0, dm, pa, hairmat, 0);
- psys_particle_on_dm(ob, dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, vec, 0, 0, 0, 0, 0);
+ psys_particle_on_dm(dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, vec, 0, 0, 0, 0, 0);
VECCOPY(hairmat[3],vec);
}
@@ -2649,62 +2820,14 @@ void psys_mat_hair_to_orco(Object *ob, DerivedMesh *dm, short from, ParticleData
float vec[3], orco[3];
psys_face_mat(ob, dm, pa, hairmat, 1);
- psys_particle_on_dm(ob, dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, vec, 0, 0, 0, orco, 0);
+ psys_particle_on_dm(dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, vec, 0, 0, 0, orco, 0);
/* see psys_face_mat for why this function is called */
transform_mesh_orco_verts(ob->data, &orco, 1, 1);
VECCOPY(hairmat[3],orco);
}
-/*
-void psys_key_to_geometry(DerivedMesh *dm, ParticleData *pa, ParticleKey *key)
-{
- float q[4], v1[3], v2[3], v3[3];
-
- dm->getVertCo(dm,pa->verts[0],v1);
- dm->getVertCo(dm,pa->verts[1],v2);
- dm->getVertCo(dm,pa->verts[2],v3);
-
- triatoquat(v1, v2, v3, q);
-
- QuatInv(q);
-
- VECSUB(key->co,key->co,v1);
-
- VECADD(key->vel,key->vel,key->co);
-
- QuatMulVecf(q, key->co);
- QuatMulVecf(q, key->vel);
-
- VECSUB(key->vel,key->vel,key->co);
-
- QuatMul(key->rot,q,key->rot);
-}
-
-void psys_key_from_geometry(DerivedMesh *dm, ParticleData *pa, ParticleKey *key)
-{
- float q[4], v1[3], v2[3], v3[3];
-
- dm->getVertCo(dm,pa->verts[0],v1);
- dm->getVertCo(dm,pa->verts[1],v2);
- dm->getVertCo(dm,pa->verts[2],v3);
-
- triatoquat(v1, v2, v3, q);
-
- VECADD(key->vel,key->vel,key->co);
-
- QuatMulVecf(q, key->co);
- QuatMulVecf(q, key->vel);
-
- VECSUB(key->vel,key->vel,key->co);
-
- VECADD(key->co,key->co,v1);
-
- QuatMul(key->rot,q,key->rot);
-}
-*/
-
-void psys_vec_rot_to_face(DerivedMesh *dm, ParticleData *pa, float *vec)//to_geometry(DerivedMesh *dm, ParticleData *pa, float *vec)
+void psys_vec_rot_to_face(DerivedMesh *dm, ParticleData *pa, float *vec)
{
float mat[4][4];
@@ -2713,36 +2836,6 @@ void psys_vec_rot_to_face(DerivedMesh *dm, ParticleData *pa, float *vec)//to_geo
Mat4Mul3Vecfl(mat, vec);
}
-/* unused */
-#if 0
-static void psys_vec_rot_from_face(DerivedMesh *dm, ParticleData *pa, float *vec)//from_geometry(DerivedMesh *dm, ParticleData *pa, float *vec)
-{
- float q[4], v1[3], v2[3], v3[3];
- /*
- dm->getVertCo(dm,pa->verts[0],v1);
- dm->getVertCo(dm,pa->verts[1],v2);
- dm->getVertCo(dm,pa->verts[2],v3);
- */
- /* replace with this */
- MFace *mface;
- int i; // = psys_particle_dm_face_lookup(dm, pa->num, pa->fuv, pa->foffset, (LinkNode*)NULL);
- i = pa->num_dmcache==DMCACHE_NOTFOUND ? pa->num : pa->num_dmcache;
- if (i==-1 || i >= dm->getNumFaces(dm)) { vec[0] = vec[1] = 0; vec[2] = 1; return; }
- mface=dm->getFaceData(dm,i,CD_MFACE);
-
- dm->getVertCo(dm,mface->v1,v1);
- dm->getVertCo(dm,mface->v2,v2);
- dm->getVertCo(dm,mface->v3,v3);
- /* done */
-
- triatoquat(v1, v2, v3, q);
-
- QuatMulVecf(q, vec);
-
- //VECADD(vec,vec,v1);
-}
-#endif
-
void psys_mat_hair_to_global(Object *ob, DerivedMesh *dm, short from, ParticleData *pa, float hairmat[][4])
{
float facemat[4][4];
@@ -2779,10 +2872,10 @@ static void default_particle_settings(ParticleSettings *part)
part->integrator= PART_INT_MIDPOINT;
part->phystype= PART_PHYS_NEWTON;
- part->hair_step= 10;
+ part->hair_step= 5;
part->keys_step= 5;
- part->draw_step= 4;
- part->ren_step= 6;
+ part->draw_step= 2;
+ part->ren_step= 3;
part->adapt_angle= 5;
part->adapt_pix= 3;
part->kink_axis= 2;
@@ -2790,7 +2883,6 @@ static void default_particle_settings(ParticleSettings *part)
part->disp=100;
part->from= PART_FROM_FACE;
part->length= 1.0;
- part->rotfac= 1.0;
part->nbetween= 4;
part->boidneighbours= 5;
@@ -2853,11 +2945,12 @@ ParticleSettings *psys_copy_settings(ParticleSettings *part)
partn= copy_libblock(part);
if(partn->pd) partn->pd= MEM_dupallocN(part->pd);
+ if(partn->pd2) partn->pd2= MEM_dupallocN(part->pd2);
return partn;
}
-void psys_make_local_settings(ParticleSettings *part)
+void make_local_particlesettings(ParticleSettings *part)
{
Object *ob;
ParticleSettings *par;
@@ -2943,7 +3036,7 @@ void psys_flush_settings(ParticleSettings *part, int event, int hair_recalc)
tpsys=BLI_findlink(&tob->particlesystem,psys->target_psys-1);
if(tpsys && tpsys->part==part){
- psys->flag |= event;
+ psys->recalc |= event;
flush++;
}
}
@@ -2953,9 +3046,86 @@ void psys_flush_settings(ParticleSettings *part, int event, int hair_recalc)
}
}
}
+
+LinkNode *psys_using_settings(ParticleSettings *part, int flush_update)
+{
+ Object *ob, *tob;
+ ParticleSystem *psys, *tpsys;
+ LinkNode *node= NULL;
+ int found;
+
+ /* update all that have same particle settings */
+ for(ob=G.main->object.first; ob; ob=ob->id.next) {
+ found= 0;
+
+ for(psys=ob->particlesystem.first; psys; psys=psys->next) {
+ if(psys->part == part) {
+ BLI_linklist_append(&node, psys);
+ found++;
+ }
+ else if(psys->part->type == PART_REACTOR){
+ tob= (psys->target_ob)? psys->target_ob: ob;
+ tpsys= BLI_findlink(&tob->particlesystem, psys->target_psys-1);
+
+ if(tpsys && tpsys->part==part) {
+ BLI_linklist_append(&node, tpsys);
+ found++;
+ }
+ }
+ }
+
+ if(flush_update && found)
+ DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
+ }
+
+ return node;
+}
+
+
/************************************************/
/* Textures */
/************************************************/
+
+static int get_particle_uv(DerivedMesh *dm, ParticleData *pa, int face_index, float *fuv, char *name, float *texco)
+{
+ MFace *mf;
+ MTFace *tf;
+ int i;
+
+ tf= CustomData_get_layer_named(&dm->faceData, CD_MTFACE, name);
+
+ if(tf == NULL)
+ tf= CustomData_get_layer(&dm->faceData, CD_MTFACE);
+
+ if(tf == NULL)
+ return 0;
+
+ if(pa) {
+ i= (pa->num_dmcache==DMCACHE_NOTFOUND)? pa->num: pa->num_dmcache;
+ if(i >= dm->getNumFaces(dm))
+ i = -1;
+ }
+ else
+ i= face_index;
+
+ if (i==-1) {
+ texco[0]= 0.0f;
+ texco[1]= 0.0f;
+ texco[2]= 0.0f;
+ }
+ else {
+ mf= dm->getFaceData(dm, i, CD_MFACE);
+
+ psys_interpolate_uvs(&tf[i], mf->v4, fuv, texco);
+
+ texco[0]= texco[0]*2.0f - 1.0f;
+ texco[1]= texco[1]*2.0f - 1.0f;
+ texco[2]= 0.0f;
+ }
+
+ return 1;
+}
+
static void get_cpa_texture(DerivedMesh *dm, Material *ma, int face_index, float *fw, float *orco, ParticleTexture *ptex, int event)
{
MTex *mtex;
@@ -2965,31 +3135,18 @@ static void get_cpa_texture(DerivedMesh *dm, Material *ma, int face_index, float
if(ma) for(m=0; m<MAX_MTEX; m++){
mtex=ma->mtex[m];
if(mtex && (ma->septex & (1<<m))==0){
+ float def=mtex->def_var;
float var=mtex->varfac;
short blend=mtex->blendtype;
short neg=mtex->pmaptoneg;
- if(mtex->texco & TEXCO_UV && fw){
- int uv_index=CustomData_get_named_layer_index(&dm->faceData,CD_MTFACE,mtex->uvname);
- if(uv_index<0){
- uv_index=CustomData_get_active_layer_index(&dm->faceData,CD_MTFACE);
- }
- if(uv_index>=0){
- CustomDataLayer *layer=&dm->faceData.layers[uv_index];
- MTFace *mtface= &((MTFace*)layer->data)[face_index];
- MFace *mf=dm->getFaceData(dm,face_index,CD_MFACE);
- psys_interpolate_uvs(mtface,mf->v4,fw,texco);
- texco[0]*=2.0;
- texco[1]*=2.0;
- texco[0]-=1.0;
- texco[1]-=1.0;
- }
- else
+ if((mtex->texco & TEXCO_UV) && fw) {
+ if(!get_particle_uv(dm, NULL, face_index, fw, mtex->uvname, texco))
VECCOPY(texco,orco);
}
- else{
+ else
VECCOPY(texco,orco);
- }
+
externtex(mtex, texco, &value, rgba, rgba+1, rgba+2, rgba+3);
if((event & mtex->pmapto) & MAP_PA_TIME){
if((setvars&MAP_PA_TIME)==0){
@@ -2999,13 +3156,13 @@ static void get_cpa_texture(DerivedMesh *dm, Material *ma, int face_index, float
ptex->time= texture_value_blend(mtex->def_var,ptex->time,value,var,blend,neg & MAP_PA_TIME);
}
if((event & mtex->pmapto) & MAP_PA_LENGTH)
- ptex->length= texture_value_blend(value,ptex->length,value,var,blend,neg & MAP_PA_LENGTH);
+ ptex->length= texture_value_blend(def,ptex->length,value,var,blend,neg & MAP_PA_LENGTH);
if((event & mtex->pmapto) & MAP_PA_CLUMP)
- ptex->clump= texture_value_blend(value,ptex->clump,value,var,blend,neg & MAP_PA_CLUMP);
+ ptex->clump= texture_value_blend(def,ptex->clump,value,var,blend,neg & MAP_PA_CLUMP);
if((event & mtex->pmapto) & MAP_PA_KINK)
- ptex->kink= texture_value_blend(value,ptex->kink,value,var,blend,neg & MAP_PA_KINK);
+ ptex->kink= texture_value_blend(def,ptex->kink,value,var,blend,neg & MAP_PA_KINK);
if((event & mtex->pmapto) & MAP_PA_ROUGH)
- ptex->rough= texture_value_blend(value,ptex->rough,value,var,blend,neg & MAP_PA_ROUGH);
+ ptex->rough= texture_value_blend(def,ptex->rough,value,var,blend,neg & MAP_PA_ROUGH);
}
}
if(event & MAP_PA_TIME) { CLAMP(ptex->time,0.0,1.0); }
@@ -3025,61 +3182,48 @@ void psys_get_texture(Object *ob, Material *ma, ParticleSystemModifierData *psmd
mtex=ma->mtex[m];
if(mtex && (ma->septex & (1<<m))==0){
float var=mtex->varfac;
+ float def=mtex->def_var;
short blend=mtex->blendtype;
short neg=mtex->pmaptoneg;
- if(mtex->texco & TEXCO_UV){
- int uv_index=CustomData_get_named_layer_index(&psmd->dm->faceData,CD_MTFACE,mtex->uvname);
- if(uv_index<0){
- uv_index=CustomData_get_active_layer_index(&psmd->dm->faceData,CD_MTFACE);
- }
- if(uv_index>=0){
- CustomDataLayer *layer=&psmd->dm->faceData.layers[uv_index];
- MTFace *mtface= &((MTFace*)layer->data)[pa->num];
- MFace *mf=psmd->dm->getFaceData(psmd->dm,pa->num,CD_MFACE);
- psys_interpolate_uvs(mtface,mf->v4,pa->fuv,texco);
- texco[0]*=2.0;
- texco[1]*=2.0;
- texco[0]-=1.0;
- texco[1]-=1.0;
+ if((mtex->texco & TEXCO_UV) && ELEM(psys->part->from, PART_FROM_FACE, PART_FROM_VOLUME)) {
+ if(!get_particle_uv(psmd->dm, pa, 0, pa->fuv, mtex->uvname, texco)) {
+ /* failed to get uv's, let's try orco's */
+ psys_particle_on_emitter(psmd,psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,0,0,0,texco, 0);
}
- else
- //psys_particle_on_emitter(ob,psmd,psys->part->from,pa->num,pa->fuv,pa->foffset,texco,0,0,0);
- /* <jahka> anyways I think it will be too small a difference to notice, so psys_get_texture should only know about the original mesh structure.. no dm needed anywhere */
- /* <brecht> the code only does dm based lookup now, so passing num_dmcache anyway to avoid^
- * massive slowdown here */
- psys_particle_on_emitter(ob,psmd,psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,0,0,0,texco, 0);
}
- else{
- //psys_particle_on_emitter(ob,psmd,psys->part->from,pa->num,pa->fuv,pa->offset,texco,0,0,0);
- /* ditto above */
- psys_particle_on_emitter(ob,psmd,psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,0,0,0,texco, 0);
+ else {
+ psys_particle_on_emitter(psmd,psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,0,0,0,texco, 0);
}
+
externtex(mtex, texco, &value, rgba, rgba+1, rgba+2, rgba+3);
if((event & mtex->pmapto) & MAP_PA_TIME){
+ /* the first time has to set the base value for time regardless of blend mode */
if((setvars&MAP_PA_TIME)==0){
- ptex->time=0.0;
- setvars|=MAP_PA_TIME;
+ ptex->time *= 1.0f - var;
+ ptex->time += var * ((neg & MAP_PA_TIME)? 1.0f - value : value);
+ setvars |= MAP_PA_TIME;
}
- ptex->time= texture_value_blend(mtex->def_var,ptex->time,value,var,blend,neg & MAP_PA_TIME);
+ else
+ ptex->time= texture_value_blend(def,ptex->time,value,var,blend,neg & MAP_PA_TIME);
}
if((event & mtex->pmapto) & MAP_PA_LIFE)
- ptex->life= texture_value_blend(mtex->def_var,ptex->life,value,var,blend,neg & MAP_PA_LIFE);
+ ptex->life= texture_value_blend(def,ptex->life,value,var,blend,neg & MAP_PA_LIFE);
if((event & mtex->pmapto) & MAP_PA_DENS)
- ptex->exist= texture_value_blend(mtex->def_var,ptex->exist,value,var,blend,neg & MAP_PA_DENS);
+ ptex->exist= texture_value_blend(def,ptex->exist,value,var,blend,neg & MAP_PA_DENS);
if((event & mtex->pmapto) & MAP_PA_SIZE)
- ptex->size= texture_value_blend(mtex->def_var,ptex->size,value,var,blend,neg & MAP_PA_SIZE);
+ ptex->size= texture_value_blend(def,ptex->size,value,var,blend,neg & MAP_PA_SIZE);
if((event & mtex->pmapto) & MAP_PA_IVEL)
- ptex->ivel= texture_value_blend(mtex->def_var,ptex->ivel,value,var,blend,neg & MAP_PA_IVEL);
+ ptex->ivel= texture_value_blend(def,ptex->ivel,value,var,blend,neg & MAP_PA_IVEL);
if((event & mtex->pmapto) & MAP_PA_PVEL)
texture_rgb_blend(ptex->pvel,rgba,ptex->pvel,value,var,blend);
if((event & mtex->pmapto) & MAP_PA_LENGTH)
- ptex->length= texture_value_blend(mtex->def_var,ptex->length,value,var,blend,neg & MAP_PA_LENGTH);
+ ptex->length= texture_value_blend(def,ptex->length,value,var,blend,neg & MAP_PA_LENGTH);
if((event & mtex->pmapto) & MAP_PA_CLUMP)
- ptex->clump= texture_value_blend(mtex->def_var,ptex->clump,value,var,blend,neg & MAP_PA_CLUMP);
+ ptex->clump= texture_value_blend(def,ptex->clump,value,var,blend,neg & MAP_PA_CLUMP);
if((event & mtex->pmapto) & MAP_PA_KINK)
- ptex->kink= texture_value_blend(mtex->def_var,ptex->kink,value,var,blend,neg & MAP_PA_CLUMP);
+ ptex->kink= texture_value_blend(def,ptex->kink,value,var,blend,neg & MAP_PA_CLUMP);
}
}
if(event & MAP_PA_TIME) { CLAMP(ptex->time,0.0,1.0); }
@@ -3116,7 +3260,7 @@ float psys_get_size(Object *ob, Material *ma, ParticleSystemModifierData *psmd,
}
if(vg_size)
- size*=psys_interpolate_value_from_verts(psmd->dm,part->from,pa->num,pa->fuv,vg_size);
+ size*=psys_particle_value_from_verts(psmd->dm,part->from,pa,vg_size);
if(part->randsize!=0.0)
size*= 1.0f - part->randsize*pa->sizemul;
@@ -3149,16 +3293,24 @@ float psys_get_child_size(ParticleSystem *psys, ChildParticle *cpa, float cfra,
float size, time;
if(part->childtype==PART_CHILD_FACES){
- if(pa_time)
- time=*pa_time;
- else
- time=psys_get_child_time(psys,cpa,cfra);
+ size=part->size;
if((part->flag&PART_ABS_TIME)==0 && part->ipo){
+ IpoCurve *icu;
+
+ if(pa_time)
+ time=*pa_time;
+ else
+ time=psys_get_child_time(psys,cpa,cfra);
+
+ /* correction for lifetime */
calc_ipo(part->ipo, 100*time);
- execute_ipo((ID *)part, part->ipo);
+
+ for(icu = part->ipo->curve.first; icu; icu=icu->next) {
+ if(icu->adrcode == PART_SIZE)
+ size = icu->curval;
+ }
}
- size=part->size;
}
else
size=psys->particles[cpa->parent].size;
@@ -3179,13 +3331,13 @@ void psys_get_particle_on_path(Object *ob, ParticleSystem *psys, int p, Particle
ParticleData *pa;
ChildParticle *cpa;
ParticleTexture ptex;
- ParticleKey tstate;
- HairKey *hkey[2];
+ ParticleKey *kkey[2] = {NULL, NULL};
+ HairKey *hkey[2] = {NULL, NULL};
ParticleKey *par=0, keys[4];
- float t, real_t, dfra, keytime;
+ float t, real_t, dfra, keytime, frs_sec = G.scene->r.frs_sec;
float co[3], orco[3];
- float imat[4][4], hairmat[4][4], cpa_1st[3];
+ float hairmat[4][4];
float pa_clump = 0.0, pa_kink = 0.0;
int totparent = 0;
int totpart = psys->totpart;
@@ -3218,19 +3370,39 @@ void psys_get_particle_on_path(Object *ob, ParticleSystem *psys, int p, Particle
return;
}
- hkey[0] = pa->hair;
- hkey[1] = pa->hair + 1;
+ if(psys->flag & PSYS_KEYED) {
+ kkey[0] = pa->keys;
+ kkey[1] = kkey[0] + 1;
+
+ real_t = kkey[0]->time + t * (kkey[0][pa->totkey-1].time - kkey[0]->time);
+ }
+ else {
+ hkey[0] = pa->hair;
+ hkey[1] = pa->hair + 1;
- real_t = hkey[0]->time + (hkey[0][pa->totkey-1].time - hkey[0]->time) * t;
+ real_t = hkey[0]->time + (hkey[0][pa->totkey-1].time - hkey[0]->time) * t;
+ }
- while(hkey[1]->time < real_t)
- hkey[1]++;
+ if(psys->flag & PSYS_KEYED) {
+ while(kkey[1]->time < real_t) {
+ kkey[1]++;
+ }
+ kkey[0] = kkey[1] - 1;
- hkey[0] = hkey[1] - 1;
+ memcpy(keys + 1, kkey[0], sizeof(ParticleKey));
+ memcpy(keys + 2, kkey[1], sizeof(ParticleKey));
+ }
+ else {
+ while(hkey[1]->time < real_t)
+ hkey[1]++;
- hair_to_particle(keys + 1, hkey[0]);
- hair_to_particle(keys + 2, hkey[1]);
+ hkey[0] = hkey[1] - 1;
+ hair_to_particle(keys + 1, hkey[0]);
+ hair_to_particle(keys + 2, hkey[1]);
+ }
+
+ if((psys->flag & PSYS_KEYED)==0) {
//if(soft){
// if(key[0] != sbel.keys)
// DB_copy_key(&k1,key[0]-1);
@@ -3255,6 +3427,7 @@ void psys_get_particle_on_path(Object *ob, ParticleSystem *psys, int p, Particle
hair_to_particle(keys + 3, hkey[1] + 1);
else
hair_to_particle(keys + 3, hkey[1]);
+ }
//}
//psys_get_particle_on_path(bsys,p,t,bkey,ckey[0]);
@@ -3264,35 +3437,48 @@ void psys_get_particle_on_path(Object *ob, ParticleSystem *psys, int p, Particle
//else{
// /* TODO: different rotations */
// float nvel[3];
- // float *q2;
// VECCOPY(nvel,state->vel);
// VecMulf(nvel,-1.0f);
- // q2=vectoquat(nvel, OB_POSX, OB_POSZ);
- // QUATCOPY(state->rot,q2);
+ // vectoquat(nvel, OB_POSX, OB_POSZ, state->rot);
//}
dfra = keys[2].time - keys[1].time;
keytime = (real_t - keys[1].time) / dfra;
- interpolate_particle((psys->part->flag & PART_HAIR_BSPLINE) ? KEY_BSPLINE : KEY_CARDINAL
- ,keys, keytime, state);
+ /* convert velocity to timestep size */
+ if(psys->flag & PSYS_KEYED){
+ VecMulf(keys[1].vel, dfra / frs_sec);
+ VecMulf(keys[2].vel, dfra / frs_sec);
+ QuatInterpol(state->rot,keys[1].rot,keys[2].rot,keytime);
+ }
- if((pa->flag & PARS_REKEY)==0) {
- psys_mat_hair_to_global(ob, psmd->dm, part->from, pa, hairmat);
- Mat4MulVecfl(hairmat, state->co);
+ interpolate_particle((psys->flag & PSYS_KEYED) ? -1 /* signal for cubic interpolation */
+ : ((psys->part->flag & PART_HAIR_BSPLINE) ? KEY_BSPLINE : KEY_CARDINAL)
+ ,keys, keytime, state, 1);
- if(psys->effectors.first && (part->flag & PART_CHILD_GUIDE)==0) {
- do_guide(state, p, state->time, &psys->effectors);
- /* TODO: proper velocity handling */
- }
+ /* the velocity needs to be converted back from cubic interpolation */
+ if(psys->flag & PSYS_KEYED){
+ VecMulf(state->vel, frs_sec / dfra);
+ }
+ else {
+ if((pa->flag & PARS_REKEY)==0) {
+ psys_mat_hair_to_global(ob, psmd->dm, part->from, pa, hairmat);
+ Mat4MulVecfl(hairmat, state->co);
+ Mat4Mul3Vecfl(hairmat, state->vel);
+
+ if(psys->effectors.first && (part->flag & PART_CHILD_GUIDE)==0) {
+ do_guide(state, p, state->time, &psys->effectors);
+ /* TODO: proper velocity handling */
+ }
- if(psys->lattice && edit==0)
- calc_latt_deform(state->co,1.0f);
+ if(psys->lattice && edit==0)
+ calc_latt_deform(state->co,1.0f);
+ }
}
}
else if(totchild){
- Mat4Invert(imat,ob->obmat);
+ //Mat4Invert(imat,ob->obmat);
cpa=psys->child+p-totpart;
@@ -3321,22 +3507,12 @@ void psys_get_particle_on_path(Object *ob, ParticleSystem *psys, int p, Particle
cpa_fuv = cpa->fuv;
cpa_from = PART_FROM_FACE;
- psys_particle_on_emitter(ob,psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa->fuv,foffset,co,0,0,0,orco,0);
+ psys_particle_on_emitter(psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa->fuv,foffset,co,0,0,0,orco,0);
/* we need to save the actual root position of the child for positioning it accurately to the surface of the emitter */
- VECCOPY(cpa_1st,co);
-
- //w=0;
- //while(w<4 && cpa->pa[w]>=0){
- // pa=psys->particles+cpa->pa[w];
- // psys_particle_on_emitter(ob,psmd,part->from,pa->num,pa->fuv,pa->foffset,vec,0,0,0);
- // cpa_1st[0] -= cpa->w[w]*vec[0];
- // cpa_1st[1] -= cpa->w[w]*vec[1];
- // cpa_1st[2] -= cpa->w[w]*vec[2];
- // w++;
- //}
+ //VECCOPY(cpa_1st,co);
- Mat4MulVecfl(ob->obmat,cpa_1st);
+ //Mat4MulVecfl(ob->obmat,cpa_1st);
pa=0;
}
@@ -3353,7 +3529,7 @@ void psys_get_particle_on_path(Object *ob, ParticleSystem *psys, int p, Particle
cpa_num=pa->num;
cpa_fuv=pa->fuv;
- psys_particle_on_emitter(ob,psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa_fuv,pa->foffset,co,0,0,0,orco,0);
+ psys_particle_on_emitter(psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa_fuv,pa->foffset,co,0,0,0,orco,0);
}
/* correct child ipo timing */
@@ -3391,7 +3567,7 @@ void psys_get_particle_on_path(Object *ob, ParticleSystem *psys, int p, Particle
w++;
}
/* apply offset for correct positioning */
- VECADD(state->co,state->co,cpa_1st);
+ //VECADD(state->co,state->co,cpa_1st);
}
else{
/* offset the child from the parent position */
@@ -3418,12 +3594,8 @@ void psys_get_particle_on_path(Object *ob, ParticleSystem *psys, int p, Particle
do_clump(state, par, t, part->clumpfac, part->clumppow, 1.0f);
- if(part->kink)
- do_postkink(state, par, par->rot, t, part->kink_freq * pa_kink, part->kink_shape,
- part->kink_amp, part->kink, part->kink_axis, ob->obmat);
-
if(part->rough1 != 0.0)
- do_rough(orco, t, part->rough1, part->rough1_size, 0.0, state);
+ do_rough(orco, t, part->rough1, part->rough1_size, 0.0, state);
if(part->rough2 != 0.0)
do_rough(cpa->rand, t, part->rough2, part->rough2_size, part->rough2_thres, state);
@@ -3431,19 +3603,18 @@ void psys_get_particle_on_path(Object *ob, ParticleSystem *psys, int p, Particle
if(part->rough_end != 0.0)
do_rough_end(cpa->rand, t, part->rough_end, part->rough_end_shape, state, par);
- if(vel){
- if(t>=0.001f){
- tstate.time=t-0.001f;
- psys_get_particle_on_path(ob,psys,p,&tstate,0);
- VECSUB(state->vel,state->co,tstate.co);
- }
- else{
- tstate.time=t+0.001f;
- psys_get_particle_on_path(ob,psys,p,&tstate,0);
- VECSUB(state->vel,tstate.co,state->co);
- }
- }
-
+ //if(vel){
+ // if(t>=0.001f){
+ // tstate.time=t-0.001f;
+ // psys_get_particle_on_path(ob,psys,p,&tstate,0);
+ // VECSUB(state->vel,state->co,tstate.co);
+ // }
+ // else{
+ // tstate.time=t+0.001f;
+ // psys_get_particle_on_path(ob,psys,p,&tstate,0);
+ // VECSUB(state->vel,tstate.co,state->co);
+ // }
+ //}
}
}
/* gets particle's state at a time, returns 1 if particle exists and can be seen and 0 if not */
@@ -3453,6 +3624,7 @@ int psys_get_particle_state(Object *ob, ParticleSystem *psys, int p, ParticleKey
float cfra;
int totpart=psys->totpart, between=0;
+ /* negative time means "use current time" */
if(state->time>0)
cfra=state->time;
else
@@ -3484,50 +3656,92 @@ int psys_get_particle_state(Object *ob, ParticleSystem *psys, int p, ParticleKey
return 0;
}
- //if(bsys->flag & (BSYS_DONE|BSYS_KEYED)){
- // if(between){
- // //ChildParticle *cpa=psys->child+p-totpart;
- // //state->time= (cfra-(part->sta+(part->end-part->sta)*cpa->rand[0]))/(part->lifetime*cpa->rand[1]);
- // }
- // else
- // state->time= (cfra-pa->time)/(pa->dietime-pa->time);//pa->lifetime;
+ if(psys->flag & PSYS_KEYED){
+ if(between){
+ ChildParticle *cpa=psys->child+p-totpart;
+ state->time= (cfra-(part->sta+(part->end-part->sta)*cpa->rand[0]))/(part->lifetime*cpa->rand[1]);
+ }
+ else
+ state->time= (cfra-pa->time)/(pa->dietime-pa->time);
- // psys_get_particle_on_path(ob,psys,p,state,1);
- // return 1;
- //}
- //else{
- //if(psys->totchild && p>=psys->totpart){
- // ChildParticle *cpa=psys->child+p-psys->totpart;
- // ParticleKey *key1, skey;
- // float t=(cfra-pa->time)/pa->lifetime, clump;
-
- // pa=psys->particles+cpa->parent;
-
- // if(pa->alive==PARS_DEAD && part->flag&PART_STICKY && pa->flag&PARS_STICKY && pa->stick_ob){
- // key1=&skey;
- // copy_particle_key(key1,&pa->state,0);
- // key_from_object(pa->stick_ob,key1);
- // }
- // else{
- // key1=&pa->state;
- // }
- //
- // offset_child(cpa, key1, state, part->childflat, part->childrad);
- //
- // CLAMP(t,0.0,1.0);
- // if(part->kink) /* TODO: part->kink_freq*pa_kink */
- // do_prekink(state,key1,t,part->kink_freq,part->kink_shape,part->kink_amp,part->kink,part->kink_axis,ob->obmat);
- //
- // /* TODO: pa_clump vgroup */
- // do_clump(state,key1,t,part->clumpfac,part->clumppow,0);
-
- // if(part->kink) /* TODO: part->kink_freq*pa_kink */
- // do_postkink(state,key1,t,part->kink_freq,part->kink_shape,part->kink_amp,part->kink,part->kink_axis,ob->obmat);
+ psys_get_particle_on_path(ob,psys,p,state,1);
+ return 1;
+ }
+ else{
+ if(between)
+ return 0; /* currently not supported */
+ else if(psys->totchild && p>=psys->totpart){
+ ChildParticle *cpa=psys->child+p-psys->totpart;
+ ParticleKey *key1, skey;
+ float t = (cfra - pa->time + pa->loop * pa->lifetime) / pa->lifetime;
+
+ pa = psys->particles + cpa->parent;
+
+ if(pa->alive==PARS_DEAD && part->flag&PART_STICKY && pa->flag&PARS_STICKY && pa->stick_ob) {
+ key1 = &skey;
+ copy_particle_key(key1,&pa->state,0);
+ key_from_object(pa->stick_ob,key1);
+ }
+ else {
+ key1=&pa->state;
+ }
+
+ offset_child(cpa, key1, state, part->childflat, part->childrad);
+
+ CLAMP(t,0.0,1.0);
+ if(part->kink) /* TODO: part->kink_freq*pa_kink */
+ do_prekink(state,key1,key1->rot,t,part->kink_freq,part->kink_shape,part->kink_amp,part->kink,part->kink_axis,ob->obmat);
+
+ /* TODO: pa_clump vgroup */
+ do_clump(state,key1,t,part->clumpfac,part->clumppow,1.0);
- //}
- //else{
+ if(psys->lattice)
+ calc_latt_deform(state->co,1.0f);
+ }
+ else{
if (pa) { /* TODO PARTICLE - should this ever be NULL? - Campbell */
- copy_particle_key(state,&pa->state,0);
+ if(pa->state.time==state->time || ELEM(part->phystype,PART_PHYS_NO,PART_PHYS_KEYED))
+ copy_particle_key(state, &pa->state, 1);
+ else if(pa->prev_state.time==state->time)
+ copy_particle_key(state, &pa->prev_state, 1);
+ else {
+ /* let's interpolate to try to be as accurate as possible */
+ if(pa->state.time + 1.0f > state->time && pa->prev_state.time - 1.0f < state->time) {
+ ParticleKey keys[4];
+ float dfra, keytime, frs_sec = G.scene->r.frs_sec;
+
+ if(pa->prev_state.time >= pa->state.time) {
+ /* prev_state is wrong so let's not use it, this can happen at frame 1 or particle birth */
+ copy_particle_key(state, &pa->state, 1);
+
+ VECADDFAC(state->co, state->co, state->vel, (state->time-pa->state.time)/frs_sec);
+ }
+ else {
+ copy_particle_key(keys+1, &pa->prev_state, 1);
+ copy_particle_key(keys+2, &pa->state, 1);
+
+ dfra = keys[2].time - keys[1].time;
+
+ keytime = (state->time - keys[1].time) / dfra;
+
+ /* convert velocity to timestep size */
+ VecMulf(keys[1].vel, dfra / frs_sec);
+ VecMulf(keys[2].vel, dfra / frs_sec);
+
+ interpolate_particle(-1, keys, keytime, state, 1);
+
+ /* convert back to real velocity */
+ VecMulf(state->vel, frs_sec / dfra);
+
+ VecLerpf(state->ave, keys[1].ave, keys[2].ave, keytime);
+ QuatInterpol(state->rot, keys[1].rot, keys[2].rot, keytime);
+ }
+ }
+ else {
+ /* extrapolating over big ranges is not accurate so let's just give something close to reasonable back */
+ copy_particle_key(state, &pa->state, 0);
+ }
+ }
if(pa->alive==PARS_DEAD && part->flag&PART_STICKY && pa->flag&PARS_STICKY && pa->stick_ob){
key_from_object(pa->stick_ob,state);
@@ -3536,9 +3750,111 @@ int psys_get_particle_state(Object *ob, ParticleSystem *psys, int p, ParticleKey
if(psys->lattice)
calc_latt_deform(state->co,1.0f);
}
- //}
+ }
return 1;
- //}
+ }
+}
+
+void psys_get_dupli_texture(Object *ob, ParticleSettings *part, ParticleSystemModifierData *psmd, ParticleData *pa, ChildParticle *cpa, float *uv, float *orco)
+{
+ MFace *mface;
+ MTFace *mtface;
+ float loc[3];
+ int num;
+
+ if(cpa) {
+ if(part->childtype == PART_CHILD_FACES) {
+ mtface= CustomData_get_layer(&psmd->dm->faceData, CD_MTFACE);
+ if(mtface) {
+ mface= psmd->dm->getFaceData(psmd->dm, cpa->num, CD_MFACE);
+ mtface += cpa->num;
+ psys_interpolate_uvs(mtface, mface->v4, cpa->fuv, uv);
+ }
+ else
+ uv[0]= uv[1]= 0.0f;
+ }
+ else
+ uv[0]= uv[1]= 0.0f;
+
+ psys_particle_on_emitter(psmd,
+ (part->childtype == PART_CHILD_FACES)? PART_FROM_FACE: PART_FROM_PARTICLE,
+ cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,loc,0,0,0,orco,0);
+ }
+ else {
+ if(part->from == PART_FROM_FACE) {
+ mtface= CustomData_get_layer(&psmd->dm->faceData, CD_MTFACE);
+ num= pa->num_dmcache;
+
+ if(num == DMCACHE_NOTFOUND)
+ if(pa->num < psmd->dm->getNumFaces(psmd->dm))
+ num= pa->num;
+
+ if(mtface && num != DMCACHE_NOTFOUND) {
+ mface= psmd->dm->getFaceData(psmd->dm, num, CD_MFACE);
+ mtface += num;
+ psys_interpolate_uvs(mtface, mface->v4, pa->fuv, uv);
+ }
+ else
+ uv[0]= uv[1]= 0.0f;
+ }
+ else
+ uv[0]= uv[1]= 0.0f;
+
+ psys_particle_on_emitter(psmd,part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,loc,0,0,0,orco,0);
+ }
+}
+
+void psys_get_dupli_path_transform(Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd, ParticleData *pa, ChildParticle *cpa, ParticleCacheKey *cache, float mat[][4], float *scale)
+{
+ float loc[3], nor[3], vec[3], side[3], len, obrotmat[4][4], qmat[4][4];
+ float xvec[3] = {-1.0, 0.0, 0.0}, q[4];
+
+ VecSubf(vec, (cache+cache->steps-1)->co, cache->co);
+ len= Normalize(vec);
+
+ if(pa)
+ psys_particle_on_emitter(psmd,psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,loc,nor,0,0,0,0);
+ else
+ psys_particle_on_emitter(psmd,
+ (psys->part->childtype == PART_CHILD_FACES)? PART_FROM_FACE: PART_FROM_PARTICLE,
+ cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,loc,nor,0,0,0,0);
+
+ if(psys->part->rotmode) {
+ if(!pa)
+ pa= psys->particles+cpa->pa[0];
+
+ vectoquat(xvec, ob->trackflag, ob->upflag, q);
+ QuatToMat4(q, obrotmat);
+ obrotmat[3][3]= 1.0f;
+
+ QuatToMat4(pa->state.rot, qmat);
+ Mat4MulMat4(mat, obrotmat, qmat);
+ }
+ else {
+ /* make sure that we get a proper side vector */
+ if(fabs(Inpf(nor,vec))>0.999999) {
+ if(fabs(Inpf(nor,xvec))>0.999999) {
+ nor[0] = 0.0f;
+ nor[1] = 1.0f;
+ nor[2] = 0.0f;
+ }
+ else {
+ nor[0] = 1.0f;
+ nor[1] = 0.0f;
+ nor[2] = 0.0f;
+ }
+ }
+ Crossf(side, nor, vec);
+ Normalize(side);
+ Crossf(nor, vec, side);
+
+ Mat4One(mat);
+ VECCOPY(mat[0], vec);
+ VECCOPY(mat[1], side);
+ VECCOPY(mat[2], nor);
+ }
+
+ *scale= len;
}
diff --git a/source/blender/blenkernel/intern/particle_system.c b/source/blender/blenkernel/intern/particle_system.c
index e3b3629fb72..6d8d6c233ac 100644
--- a/source/blender/blenkernel/intern/particle_system.c
+++ b/source/blender/blenkernel/intern/particle_system.c
@@ -53,13 +53,15 @@
#include "BLI_arithb.h"
#include "BLI_blenlib.h"
#include "BLI_kdtree.h"
+#include "BLI_kdopbvh.h"
#include "BLI_linklist.h"
#include "BLI_threads.h"
#include "BKE_anim.h"
#include "BKE_cdderivedmesh.h"
+#include "BKE_collision.h"
#include "BKE_displist.h"
-
+#include "BKE_effect.h"
#include "BKE_particle.h"
#include "BKE_global.h"
#include "BKE_utildefines.h"
@@ -73,10 +75,28 @@
#include "BKE_pointcache.h"
#include "BKE_mesh.h"
#include "BKE_modifier.h"
+#include "BKE_scene.h"
+#include "PIL_time.h"
#include "RE_shader_ext.h"
+/* fluid sim particle import */
+#ifndef DISABLE_ELBEEM
+#include "DNA_object_fluidsim.h"
+#include "LBM_fluidsim.h"
+#include "elbeem.h"
+#include <zlib.h>
+#include <string.h>
+
+#ifdef WIN32
+#ifndef snprintf
+#define snprintf _snprintf
+#endif
+#endif
+
+#endif // DISABLE_ELBEEM
+
/************************************************/
/* Reacting to system events */
/************************************************/
@@ -98,13 +118,65 @@ static int get_current_display_percentage(ParticleSystem *psys)
return psys->part->disp;
}
-static void alloc_particles(Object *ob, ParticleSystem *psys, int new_totpart)
+void psys_reset(ParticleSystem *psys, int mode)
+{
+ ParticleSettings *part= psys->part;
+ ParticleData *pa;
+ int i;
+
+ if(ELEM(mode, PSYS_RESET_ALL, PSYS_RESET_DEPSGRAPH)) {
+ if(mode == PSYS_RESET_ALL || !(part->type == PART_HAIR && (psys->flag & PSYS_EDITED))) {
+ if(psys->particles) {
+ if(psys->particles->keys)
+ MEM_freeN(psys->particles->keys);
+
+ for(i=0, pa=psys->particles; i<psys->totpart; i++, pa++)
+ if(pa->hair) MEM_freeN(pa->hair);
+
+ MEM_freeN(psys->particles);
+ psys->particles= NULL;
+ }
+
+ psys->totpart= 0;
+ psys->totkeyed= 0;
+ psys->flag &= ~(PSYS_HAIR_DONE|PSYS_KEYED);
+
+ if(psys->reactevents.first)
+ BLI_freelistN(&psys->reactevents);
+ }
+ }
+ else if(mode == PSYS_RESET_CACHE_MISS) {
+ /* set all particles to be skipped */
+ ParticleData *pa = psys->particles;
+ int p=0;
+
+ for(; p<psys->totpart; p++, pa++)
+ pa->flag |= PARS_NO_DISP;
+ }
+
+ /* reset children */
+ if(psys->child) {
+ MEM_freeN(psys->child);
+ psys->child= 0;
+ }
+
+ psys->totchild= 0;
+
+ /* reset path cache */
+ psys_free_path_cache(psys);
+
+ /* reset point cache */
+ psys->pointcache->flag &= ~PTCACHE_SIMULATION_VALID;
+ psys->pointcache->simframe= 0;
+}
+
+static void realloc_particles(Object *ob, ParticleSystem *psys, int new_totpart)
{
ParticleData *newpars = 0, *pa;
int i, totpart, totsaved = 0;
if(new_totpart<0) {
- if(psys->part->distr==PART_DISTR_GRID) {
+ if(psys->part->distr==PART_DISTR_GRID && psys->part->from != PART_FROM_VERT) {
totpart= psys->part->grid_res;
totpart*=totpart*totpart;
}
@@ -122,6 +194,12 @@ static void alloc_particles(Object *ob, ParticleSystem *psys, int new_totpart)
if(totsaved)
memcpy(newpars,psys->particles,totsaved*sizeof(ParticleData));
+ if(psys->particles->keys)
+ MEM_freeN(psys->particles->keys);
+
+ for(i=0, pa=psys->particles; i<totsaved; i++, pa++)
+ if(pa->keys) pa->keys= NULL;
+
for(i=totsaved, pa=psys->particles+totsaved; i<psys->totpart; i++, pa++)
if(pa->hair) MEM_freeN(pa->hair);
@@ -138,15 +216,24 @@ static void alloc_particles(Object *ob, ParticleSystem *psys, int new_totpart)
psys->totpart=totpart;
}
-static int get_alloc_child_particles_tot(ParticleSystem *psys)
+static int get_psys_child_number(ParticleSystem *psys)
{
- int child_nbr;
+ int nbr;
if(!psys->part->childtype)
return 0;
- child_nbr= (psys->renderdata)? psys->part->ren_child_nbr: psys->part->child_nbr;
- return psys->totpart*child_nbr;
+ if(psys->renderdata) {
+ nbr= psys->part->ren_child_nbr;
+ return get_render_child_particle_number(&G.scene->r, nbr);
+ }
+ else
+ return psys->part->child_nbr;
+}
+
+static int get_psys_tot_child(ParticleSystem *psys)
+{
+ return psys->totpart*get_psys_child_number(psys);
}
static void alloc_child_particles(ParticleSystem *psys, int tot)
@@ -164,12 +251,13 @@ static void alloc_child_particles(ParticleSystem *psys, int tot)
}
}
-/* only run this if from == PART_FROM_FACE */
-void psys_calc_dmfaces(Object *ob, DerivedMesh *dm, ParticleSystem *psys)
+void psys_calc_dmcache(Object *ob, DerivedMesh *dm, ParticleSystem *psys)
{
- /* use for building derived mesh face-origin info,
- node - the allocated links - total derived mesh face count
- node_array - is the array of nodes alligned with the base mesh's faces, so each original face can reference its derived faces
+ /* use for building derived mesh mapping info:
+
+ node: the allocated links - total derived mesh element count
+ nodearray: the array of nodes aligned with the base mesh's elements, so
+ each original elements can reference its derived elements
*/
Mesh *me= (Mesh*)ob->data;
ParticleData *pa= 0;
@@ -178,57 +266,60 @@ void psys_calc_dmfaces(Object *ob, DerivedMesh *dm, ParticleSystem *psys)
/* CACHE LOCATIONS */
if(!dm->deformedOnly) {
/* Will use later to speed up subsurf/derivedmesh */
+ LinkNode *node, *nodedmelem, **nodearray;
+ int totdmelem, totelem, i, *origindex;
+
+ if(psys->part->from == PART_FROM_VERT) {
+ totdmelem= dm->getNumVerts(dm);
+ totelem= me->totvert;
+ origindex= DM_get_vert_data_layer(dm, CD_ORIGINDEX);
+ }
+ else { /* FROM_FACE/FROM_VOLUME */
+ totdmelem= dm->getNumFaces(dm);
+ totelem= me->totface;
+ origindex= DM_get_face_data_layer(dm, CD_ORIGINDEX);
+ }
- int tot_dm_face = dm->getNumFaces(dm);
- int totface = me->totface;
- int *origindex = DM_get_face_data_layer(dm, CD_ORIGINDEX);
- int i;
- LinkNode *node, *node_dm_faces, **node_array;
+ nodedmelem= MEM_callocN(sizeof(LinkNode)*totdmelem, "psys node elems");
+ nodearray= MEM_callocN(sizeof(LinkNode *)*totelem, "psys node array");
- node_dm_faces = node = MEM_callocN(sizeof(LinkNode)*tot_dm_face, "faceindicies");
- node_array = MEM_callocN(sizeof(LinkNode *)*totface, "faceindicies array");
-
- for(i=0; i < tot_dm_face; i++, origindex++, node++) {
- node->link = (void *)i; // or use the index?
+ for(i=0, node=nodedmelem; i<totdmelem; i++, origindex++, node++) {
+ node->link= SET_INT_IN_POINTER(i);
+
if(*origindex != -1) {
- if(node_array[*origindex]) {
+ if(nodearray[*origindex]) {
/* prepend */
- node->next = node_array[*origindex];
- node_array[*origindex] = node;
- } else {
- node_array[*origindex] = node;
+ node->next = nodearray[*origindex];
+ nodearray[*origindex]= node;
}
+ else
+ nodearray[*origindex]= node;
}
}
- /* cache the faces! */
-
-
+ /* cache the verts/faces! */
for(p=0,pa=psys->particles; p<psys->totpart; p++,pa++) {
- //i = pa->num;
- //if (i<totface) // should never happen
- i = psys_particle_dm_face_lookup(ob, dm, pa->num, pa->fuv, node_array[pa->num]);
- pa->num_dmcache = i;
+ if(psys->part->from == PART_FROM_VERT) {
+ if(nodearray[pa->num])
+ pa->num_dmcache= GET_INT_FROM_POINTER(nodearray[pa->num]->link);
+ }
+ else { /* FROM_FACE/FROM_VOLUME */
+ /* Note that somtimes the pa->num is over the nodearray size, this is bad, maybe there is a better place to fix this,
+ * but for now passing NULL is OK. every face will be searched for the particle so its slower - Campbell */
+ pa->num_dmcache= psys_particle_dm_face_lookup(ob, dm, pa->num, pa->fuv, pa->num < totelem ? nodearray[pa->num] : NULL);
+ }
}
- //for (i=0; i < totface; i++) {
- // i = psys_particle_dm_face_lookup(ob, dm, node_array[], fuv, (LinkNode*)NULL);
- //}
- MEM_freeN(node_array);
- MEM_freeN(node_dm_faces);
-
- } else {
- /* set the num_dmcache to an invalid value, just incase */
- /* TODO PARTICLE, make the following line unnecessary, each function should know to use the num or num_dmcache */
+ MEM_freeN(nodearray);
+ MEM_freeN(nodedmelem);
+ }
+ else {
+ /* TODO PARTICLE, make the following line unnecessary, each function
+ * should know to use the num or num_dmcache, set the num_dmcache to
+ * an invalid value, just incase */
- /*
- for(p=0,pa=psys->particles; p<psys->totpart; p++,pa++) {
- pa->num_dmcache = pa->num;
- }
- */
- for(p=0,pa=psys->particles; p<psys->totpart; p++,pa++) {
+ for(p=0,pa=psys->particles; p<psys->totpart; p++,pa++)
pa->num_dmcache = -1;
- }
}
}
@@ -388,6 +479,29 @@ static void distribute_particles_in_grid(DerivedMesh *dm, ParticleSystem *psys)
}
}
+/* modified copy from rayshade.c */
+static void hammersley_create(float *out, int n, int seed, float amount)
+{
+ RNG *rng;
+ double p, t, offs[2];
+ int k, kk;
+
+ rng = rng_new(31415926 + n + seed);
+ offs[0]= rng_getDouble(rng) + amount;
+ offs[1]= rng_getDouble(rng) + amount;
+ rng_free(rng);
+
+ for (k = 0; k < n; k++) {
+ t = 0;
+ for (p = 0.5, kk = k; kk; p *= 0.5, kk >>= 1)
+ if (kk & 1) /* kk mod 2 = 1 */
+ t += p;
+
+ out[2*k + 0]= fmod((double)k/(double)n + offs[0], 1.0);
+ out[2*k + 1]= fmod(t + offs[1], 1.0);
+ }
+}
+
/* modified copy from effect.c */
static void init_mv_jit(float *jit, int num, int seed2, float amount)
{
@@ -485,7 +599,7 @@ void psys_thread_distribute_particle(ParticleThread *thread, ParticleData *pa, C
ParticleData *tpa;
ParticleSettings *part= ctx->psys->part;
float *v1, *v2, *v3, *v4, nor[3], orco1[3], co1[3], co2[3], nor1[3], ornor1[3];
- float cur_d, min_d;
+ float cur_d, min_d, randu, randv;
int from= ctx->from;
int cfrom= ctx->cfrom;
int distr= ctx->distr;
@@ -503,7 +617,7 @@ void psys_thread_distribute_particle(ParticleThread *thread, ParticleData *pa, C
KDTreeNearest ptn[3];
int w, maxw;
- psys_particle_on_dm(ctx->ob,ctx->dm,from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co1,0,0,0,orco1,0);
+ psys_particle_on_dm(ctx->dm,from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co1,0,0,0,orco1,0);
transform_mesh_orco_verts((Mesh*)ob->data, &orco1, 1, 1);
maxw = BLI_kdtree_find_n_nearest(ctx->tree,3,orco1,NULL,ptn);
@@ -527,7 +641,9 @@ void psys_thread_distribute_particle(ParticleThread *thread, ParticleData *pa, C
//ctx->jitoff[i]=(float)fmod(ctx->jitoff[i]+ctx->maxweight/ctx->weight[i],(float)ctx->jitlevel);
break;
case PART_DISTR_RAND:
- psys_uv_to_w(rng_getFloat(thread->rng), rng_getFloat(thread->rng), mface->v4, pa->fuv);
+ randu= rng_getFloat(thread->rng);
+ randv= rng_getFloat(thread->rng);
+ psys_uv_to_w(randu, randv, mface->v4, pa->fuv);
break;
}
pa->foffset= 0.0f;
@@ -625,7 +741,9 @@ void psys_thread_distribute_particle(ParticleThread *thread, ParticleData *pa, C
// ctx->jitoff[i]=(float)fmod(ctx->jitoff[i]+ctx->maxweight/ctx->weight[i],(float)ctx->jitlevel);
// break;
// case PART_DISTR_RAND:
- psys_uv_to_w(rng_getFloat(thread->rng), rng_getFloat(thread->rng), mf->v4, cpa->fuv);
+ randu= rng_getFloat(thread->rng);
+ randv= rng_getFloat(thread->rng);
+ psys_uv_to_w(randu, randv, mf->v4, cpa->fuv);
// break;
//}
@@ -643,7 +761,7 @@ void psys_thread_distribute_particle(ParticleThread *thread, ParticleData *pa, C
do_seams= (part->flag&PART_CHILD_SEAMS && ctx->seams);
- psys_particle_on_dm(ob,dm,cfrom,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co1,nor1,0,0,orco1,ornor1);
+ psys_particle_on_dm(dm,cfrom,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co1,nor1,0,0,orco1,ornor1);
transform_mesh_orco_verts((Mesh*)ob->data, &orco1, 1, 1);
maxw = BLI_kdtree_find_n_nearest(ctx->tree,(do_seams)?10:4,orco1,ornor1,ptn);
@@ -741,7 +859,7 @@ void psys_thread_distribute_particle(ParticleThread *thread, ParticleData *pa, C
}
}
-void *exec_distribution(void *data)
+static void *exec_distribution(void *data)
{
ParticleThread *thread= (ParticleThread*)data;
ParticleSystem *psys= thread->ctx->psys;
@@ -773,6 +891,29 @@ void *exec_distribution(void *data)
return 0;
}
+/* not thread safe, but qsort doesn't take userdata argument */
+static int *COMPARE_ORIG_INDEX = NULL;
+static int compare_orig_index(const void *p1, const void *p2)
+{
+ int index1 = COMPARE_ORIG_INDEX[*(const int*)p1];
+ int index2 = COMPARE_ORIG_INDEX[*(const int*)p2];
+
+ if(index1 < index2)
+ return -1;
+ else if(index1 == index2) {
+ /* this pointer comparison appears to make qsort stable for glibc,
+ * and apparently on solaris too, makes the renders reproducable */
+ if(p1 < p2)
+ return -1;
+ else if(p1 == p2)
+ return 0;
+ else
+ return 1;
+ }
+ else
+ return 1;
+}
+
/* creates a distribution of coordinates on a DerivedMesh */
/* */
/* 1. lets check from what we are emitting */
@@ -834,14 +975,14 @@ int psys_threads_init_distribution(ParticleThread *threads, DerivedMesh *finaldm
tree=BLI_kdtree_new(totpart);
for(p=0,pa=psys->particles; p<totpart; p++,pa++){
- psys_particle_on_dm(ob,dm,part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,nor,0,0,orco,ornor);
+ psys_particle_on_dm(dm,part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,nor,0,0,orco,ornor);
transform_mesh_orco_verts((Mesh*)ob->data, &orco, 1, 1);
BLI_kdtree_insert(tree, p, orco, ornor);
}
BLI_kdtree_balance(tree);
- totpart=get_alloc_child_particles_tot(psys);
+ totpart=get_psys_tot_child(psys);
cfrom=from=PART_FROM_FACE;
if(part->flag&PART_CHILD_SEAMS){
@@ -890,9 +1031,9 @@ int psys_threads_init_distribution(ParticleThread *threads, DerivedMesh *finaldm
}
else{
/* no need to figure out distribution */
- int child_nbr= (psys->renderdata)? part->ren_child_nbr: part->child_nbr;
+ int child_nbr= get_psys_child_number(psys);
- totpart= get_alloc_child_particles_tot(psys);
+ totpart= get_psys_tot_child(psys);
alloc_child_particles(psys, totpart);
cpa=psys->child;
for(i=0; i<child_nbr; i++){
@@ -923,7 +1064,7 @@ int psys_threads_init_distribution(ParticleThread *threads, DerivedMesh *finaldm
dm= CDDM_from_mesh((Mesh*)ob->data, ob);
/* special handling of grid distribution */
- if(part->distr==PART_DISTR_GRID){
+ if(part->distr==PART_DISTR_GRID && from != PART_FROM_VERT){
distribute_particles_in_grid(dm,psys);
dm->release(dm);
return 0;
@@ -980,17 +1121,21 @@ int psys_threads_init_distribution(ParticleThread *threads, DerivedMesh *finaldm
if(tot==0){
no_distr=1;
if(children){
- fprintf(stderr,"Particle child distribution error: Nothing to emit from!\n");
- for(p=0,cpa=psys->child; p<totpart; p++,cpa++){
- cpa->fuv[0]=cpa->fuv[1]=cpa->fuv[2]=cpa->fuv[3]= 0.0;
- cpa->foffset= 0.0f;
- cpa->parent=0;
- cpa->pa[0]=cpa->pa[1]=cpa->pa[2]=cpa->pa[3]=0;
- cpa->num= -1;
+ if(G.f & G_DEBUG)
+ fprintf(stderr,"Particle child distribution error: Nothing to emit from!\n");
+ if(psys->child) {
+ for(p=0,cpa=psys->child; p<totpart; p++,cpa++){
+ cpa->fuv[0]=cpa->fuv[1]=cpa->fuv[2]=cpa->fuv[3]= 0.0;
+ cpa->foffset= 0.0f;
+ cpa->parent=0;
+ cpa->pa[0]=cpa->pa[1]=cpa->pa[2]=cpa->pa[3]=0;
+ cpa->num= -1;
+ }
}
}
else {
- fprintf(stderr,"Particle distribution error: Nothing to emit from!\n");
+ if(G.f & G_DEBUG)
+ fprintf(stderr,"Particle distribution error: Nothing to emit from!\n");
for(p=0,pa=psys->particles; p<totpart; p++,pa++){
pa->fuv[0]=pa->fuv[1]=pa->fuv[2]= pa->fuv[3]= 0.0;
pa->foffset= 0.0f;
@@ -1131,7 +1276,7 @@ int psys_threads_init_distribution(ParticleThread *threads, DerivedMesh *finaldm
double step, pos;
step= (totpart <= 1)? 0.5: 1.0/(totpart-1);
- pos= 0.0f;
+ pos= 1e-16f; /* tiny offset to avoid zero weight face */
i= 0;
for(p=0; p<totpart; p++, pos+=step) {
@@ -1139,6 +1284,8 @@ int psys_threads_init_distribution(ParticleThread *threads, DerivedMesh *finaldm
i++;
index[p]= MIN2(tot-1, i);
+
+ /* avoid zero weight face */
if(p == totpart-1 && weight[index[p]] == 0.0f)
index[p]= index[p-1];
@@ -1148,6 +1295,13 @@ int psys_threads_init_distribution(ParticleThread *threads, DerivedMesh *finaldm
MEM_freeN(sum);
+ /* for hair, sort by origindex, allows optimizations in rendering */
+ if(part->type == PART_HAIR) {
+ COMPARE_ORIG_INDEX= dm->getFaceDataArray(dm, CD_ORIGINDEX);
+ if(COMPARE_ORIG_INDEX)
+ qsort(index, totpart, sizeof(int), compare_orig_index);
+ }
+
/* weights are no longer used except for FROM_PARTICLE, which needs them zeroed for indexing */
if(from==PART_FROM_PARTICLE){
for(i=0; i<tot; i++)
@@ -1165,9 +1319,15 @@ int psys_threads_init_distribution(ParticleThread *threads, DerivedMesh *finaldm
//if(jitlevel>100) jitlevel= 100;
}
- jit= MEM_callocN(2+ jitlevel*2*sizeof(float), "jit");
+ jit= MEM_callocN((2+ jitlevel*2)*sizeof(float), "jit");
- init_mv_jit(jit, jitlevel, psys->seed, part->jitfac);
+ /* for small amounts of particles we use regular jitter since it looks
+ * a bit better, for larger amounts we switch to hammersley sequence
+ * because it is much faster */
+ if(jitlevel < 25)
+ init_mv_jit(jit, jitlevel, psys->seed, part->jitfac);
+ else
+ hammersley_create(jit, jitlevel+1, psys->seed, part->jitfac);
BLI_array_randomize(jit, 2*sizeof(float), jitlevel, psys->seed); /* for custom jit or even distribution */
}
@@ -1212,7 +1372,7 @@ static void distribute_particles_on_dm(DerivedMesh *finaldm, Object *ob, Particl
ParticleThreadContext *ctx;
int i, totthread;
- pthreads= psys_threads_create(ob, psys, G.scene->r.threads);
+ pthreads= psys_threads_create(ob, psys);
if(!psys_threads_init_distribution(pthreads, finaldm, from)) {
psys_threads_free(pthreads);
@@ -1231,8 +1391,7 @@ static void distribute_particles_on_dm(DerivedMesh *finaldm, Object *ob, Particl
else
exec_distribution(&pthreads[0]);
- if (from == PART_FROM_FACE)
- psys_calc_dmfaces(ob, finaldm, psys);
+ psys_calc_dmcache(ob, finaldm, psys);
ctx= pthreads[0].ctx;
if(ctx->dm != finaldm)
@@ -1285,11 +1444,16 @@ static void distribute_particles(Object *ob, ParticleSystem *psys, int from)
}
/* threaded child particle distribution and path caching */
-ParticleThread *psys_threads_create(struct Object *ob, struct ParticleSystem *psys, int totthread)
+ParticleThread *psys_threads_create(struct Object *ob, struct ParticleSystem *psys)
{
ParticleThread *threads;
ParticleThreadContext *ctx;
- int i;
+ int i, totthread;
+
+ if(G.scene->r.mode & R_FIXED_THREADS)
+ totthread= G.scene->r.threads;
+ else
+ totthread= BLI_system_thread_count();
threads= MEM_callocN(sizeof(ParticleThread)*totthread, "ParticleThread");
ctx= MEM_callocN(sizeof(ParticleThreadContext), "ParticleThreadContext");
@@ -1326,7 +1490,7 @@ void psys_threads_free(ParticleThread *threads)
if(ctx->vg_rough1)
MEM_freeN(ctx->vg_rough1);
if(ctx->vg_rough2)
- MEM_freeN(ctx->vg_roughe);
+ MEM_freeN(ctx->vg_rough2);
if(ctx->vg_roughe)
MEM_freeN(ctx->vg_roughe);
@@ -1376,7 +1540,7 @@ void initialize_particle(ParticleData *pa, int p, Object *ob, ParticleSystem *ps
BLI_srandom(psys->seed+p);
- if(part->from!=PART_FROM_PARTICLE){
+ if(part->from!=PART_FROM_PARTICLE && part->type!=PART_FLUID){
ma=give_current_material(ob,part->omat);
/* TODO: needs some work to make most blendtypes generally usefull */
@@ -1446,7 +1610,7 @@ void initialize_particle(ParticleData *pa, int p, Object *ob, ParticleSystem *ps
NormalQuat(pa->r_rot);
- if(part->distr!=PART_DISTR_GRID){
+ if(part->distr!=PART_DISTR_GRID && part->from != PART_FROM_VERT){
/* any unique random number will do (r_ave[0]) */
if(ptex.exist < 0.5*(1.0+pa->r_ave[0]))
pa->flag |= PARS_UNEXIST;
@@ -1468,53 +1632,54 @@ static void initialize_all_particles(Object *ob, ParticleSystem *psys, ParticleS
for(p=0, pa=psys->particles; p<totpart; p++, pa++)
initialize_particle(pa,p,ob,psys,psmd);
- /* store the derived mesh face index for each particle */
- icu=find_ipocurve(psys->part->ipo,PART_EMIT_FREQ);
- if(icu){
- float time=psys->part->sta, end=psys->part->end;
- float v1, v2, a=0.0f, t1,t2, d;
+ if(psys->part->type != PART_FLUID) {
+ icu=find_ipocurve(psys->part->ipo,PART_EMIT_FREQ);
+ if(icu){
+ float time=psys->part->sta, end=psys->part->end;
+ float v1, v2, a=0.0f, t1,t2, d;
+
+ p=0;
+ pa=psys->particles;
+
+ calc_icu(icu,time);
+ v1=icu->curval;
+ if(v1<0.0f) v1=0.0f;
+
+ calc_icu(icu,time+1.0f);
+ v2=icu->curval;
+ if(v2<0.0f) v2=0.0f;
+
+ for(p=0, pa=psys->particles; p<totpart && time<end; p++, pa++){
+ while(a+0.5f*(v1+v2) < (float)(p+1) && time<end){
+ a+=0.5f*(v1+v2);
+ v1=v2;
+ time++;
+ calc_icu(icu,time+1.0f);
+ v2=icu->curval;
+ }
+ if(time<end){
+ if(v1==v2){
+ pa->time=time+((float)(p+1)-a)/v1;
+ }
+ else{
+ d=(float)sqrt(v1*v1-2.0f*(v2-v1)*(a-(float)(p+1)));
+ t1=(-v1+d)/(v2-v1);
+ t2=(-v1-d)/(v2-v1);
- p=0;
- pa=psys->particles;
+ /* the root between 0-1 is the correct one */
+ if(t1>0.0f && t1<=1.0f)
+ pa->time=time+t1;
+ else
+ pa->time=time+t2;
+ }
+ }
- calc_icu(icu,time);
- v1=icu->curval;
- if(v1<0.0f) v1=0.0f;
-
- calc_icu(icu,time+1.0f);
- v2=icu->curval;
- if(v2<0.0f) v2=0.0f;
-
- for(p=0, pa=psys->particles; p<totpart && time<end; p++, pa++){
- while(a+0.5f*(v1+v2) < (float)(p+1) && time<end){
- a+=0.5f*(v1+v2);
- v1=v2;
- time++;
- calc_icu(icu,time+1.0f);
- v2=icu->curval;
+ pa->dietime = pa->time+pa->lifetime;
+ pa->flag &= ~PARS_UNEXIST;
}
- if(time<end){
- if(v1==v2){
- pa->time=time+((float)(p+1)-a)/v1;
- }
- else{
- d=(float)sqrt(v1*v1-2.0f*(v2-v1)*(a-(float)(p+1)));
- t1=(-v1+d)/(v2-v1);
- t2=(-v1-d)/(v2-v1);
-
- /* the root between 0-1 is the correct one */
- if(t1>0.0f && t1<=1.0f)
- pa->time=time+t1;
- else
- pa->time=time+t2;
- }
+ for(; p<totpart; p++, pa++){
+ pa->flag |= PARS_UNEXIST;
}
-
- pa->dietime = pa->time+pa->lifetime;
- pa->flag &= ~PARS_UNEXIST;
- }
- for(; p<totpart; p++, pa++){
- pa->flag |= PARS_UNEXIST;
}
}
}
@@ -1526,11 +1691,10 @@ void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifi
ParticleTexture ptex;
ParticleKey state;
IpoCurve *icu=0;
- float fac, nor[3]={0,0,0},loc[3],tloc[3],vel[3]={0.0,0.0,0.0},rot[4],*q2=0;
+ float fac, phasefac, nor[3]={0,0,0},loc[3],tloc[3],vel[3]={0.0,0.0,0.0},rot[4],q2[4];
float r_vel[3],r_ave[3],r_rot[4],p_vel[3]={0.0,0.0,0.0};
- float x_vec[3]={1.0,0.0,0.0}, utan[3]={0.0,1.0,0.0}, vtan[3]={0.0,0.0,1.0};
-
- float q_one[4]={1.0,0.0,0.0,0.0}, q_phase[4];
+ float x_vec[3]={1.0,0.0,0.0}, utan[3]={0.0,1.0,0.0}, vtan[3]={0.0,0.0,1.0}, rot_vec[3]={0.0,0.0,0.0};
+ float q_phase[4];
part=psys->part;
ptex.ivel=1.0;
@@ -1545,11 +1709,12 @@ void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifi
tob=ob;
tpsys=BLI_findlink(&tob->particlesystem,psys->target_psys-1);
-
- /*TODO: get precise location of particle at birth*/
- state.time=cfra;
- psys_get_particle_state(tob,tpsys,pa->num,&state,1);
+ state.time = pa->time;
+ if(pa->num == -1)
+ memset(&state, 0, sizeof(state));
+ else
+ psys_get_particle_state(tob,tpsys,pa->num,&state,1);
psys_get_from_key(&state,loc,nor,rot,0);
QuatMulVecf(rot,vtan);
@@ -1571,7 +1736,7 @@ void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifi
where_is_object_time(ob,pa->time);
/* get birth location from object */
- psys_particle_on_emitter(ob,psmd,part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,utan,vtan,0,0);
+ psys_particle_on_emitter(psmd,part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,utan,vtan,0,0);
/* save local coordinates for later */
VECCOPY(tloc,loc);
@@ -1579,9 +1744,8 @@ void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifi
/* get possible textural influence */
psys_get_texture(ob,give_current_material(ob,part->omat),psmd,psys,pa,&ptex,MAP_PA_IVEL);
- if(vg_vel){
- ptex.ivel*=psys_interpolate_value_from_verts(psmd->dm,part->from,pa->num,pa->fuv,vg_vel);
- }
+ if(vg_vel && pa->num != -1)
+ ptex.ivel*=psys_particle_value_from_verts(psmd->dm,part->from,pa,vg_vel);
/* particles live in global space so */
/* let's convert: */
@@ -1596,7 +1760,7 @@ void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifi
/* -tangent */
if(part->tanfac!=0.0){
- float phase=vg_rot?2.0f*(psys_interpolate_value_from_verts(psmd->dm,part->from,pa->num,pa->fuv,vg_rot)-0.5f):0.0f;
+ float phase=vg_rot?2.0f*(psys_particle_value_from_verts(psmd->dm,part->from,pa,vg_rot)-0.5f):0.0f;
VecMulf(vtan,-(float)cos(M_PI*(part->tanphase+phase)));
fac=-(float)sin(M_PI*(part->tanphase+phase));
VECADDFAC(vtan,vtan,utan,fac);
@@ -1630,7 +1794,7 @@ void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifi
}
/* -rotation */
- if(part->rotmode==PART_ROT_RAND){
+ if(part->randrotfac != 0.0f){
QUATCOPY(r_rot,pa->r_rot);
Mat4ToQuat(ob->obmat,rot);
QuatMul(r_rot,r_rot,rot);
@@ -1638,6 +1802,12 @@ void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifi
}
/* conversion done so now we apply new: */
/* -velocity from: */
+
+ /* *reactions */
+ if(dtime>0.0f){
+ VECSUB(vel,pa->state.vel,pa->prev_state.vel);
+ }
+
/* *emitter velocity */
if(dtime!=0.0 && part->obfac!=0.0){
VECSUB(vel,loc,pa->state.co);
@@ -1650,7 +1820,7 @@ void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifi
/* *emitter tangent */
if(part->tanfac!=0.0)
- VECADDFAC(vel,vel,vtan,part->tanfac*(vg_tan?psys_interpolate_value_from_verts(psmd->dm,part->from,pa->num,pa->fuv,vg_tan):1.0f));
+ VECADDFAC(vel,vel,vtan,part->tanfac*(vg_tan?psys_particle_value_from_verts(psmd->dm,part->from,pa,vg_tan):1.0f));
/* *texture */
/* TODO */
@@ -1681,34 +1851,49 @@ void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifi
pa->state.rot[1]=pa->state.rot[2]=pa->state.rot[3]=0.0;
if(part->rotmode){
+ /* create vector into which rotation is aligned */
switch(part->rotmode){
case PART_ROT_NOR:
- VecMulf(nor,-1.0);
- q2= vectoquat(nor, OB_POSX, OB_POSZ);
- VecMulf(nor,-1.0);
+ VecCopyf(rot_vec, nor);
break;
case PART_ROT_VEL:
- VecMulf(vel,-1.0);
- q2= vectoquat(vel, OB_POSX, OB_POSZ);
- VecMulf(vel,-1.0);
+ VecCopyf(rot_vec, vel);
+ break;
+ case PART_ROT_GLOB_X:
+ case PART_ROT_GLOB_Y:
+ case PART_ROT_GLOB_Z:
+ rot_vec[part->rotmode - PART_ROT_GLOB_X] = 1.0f;
break;
- case PART_ROT_RAND:
- q2= r_rot;
+ case PART_ROT_OB_X:
+ case PART_ROT_OB_Y:
+ case PART_ROT_OB_Z:
+ VecCopyf(rot_vec, ob->obmat[part->rotmode - PART_ROT_OB_X]);
break;
}
- /* how much to rotate from rest position */
- QuatInterpol(rot,q_one,q2,part->rotfac);
+
+ /* create rotation quat */
+ VecMulf(rot_vec,-1.0);
+ vectoquat(rot_vec, OB_POSX, OB_POSZ, q2);
+
+ /* randomize rotation quat */
+ if(part->randrotfac!=0.0f)
+ QuatInterpol(rot, q2, r_rot, part->randrotfac);
+ else
+ QuatCopy(rot,q2);
- /* phase */
- VecRotToQuat(x_vec,part->phasefac*(float)M_PI,q_phase);
+ /* rotation phase */
+ phasefac = part->phasefac;
+ if(part->randphasefac != 0.0f) /* abuse r_ave[0] as a random number */
+ phasefac += part->randphasefac * pa->r_ave[0];
+ VecRotToQuat(x_vec, phasefac*(float)M_PI, q_phase);
- /* combine amount & phase */
- QuatMul(pa->state.rot,rot,q_phase);
+ /* combine base rotation & phase */
+ QuatMul(pa->state.rot, rot, q_phase);
}
/* -angular velocity */
- pa->state.ave[0]=pa->state.ave[1]=pa->state.ave[2]=0.0;
+ pa->state.ave[0] = pa->state.ave[1] = pa->state.ave[2] = 0.0;
if(part->avemode){
switch(part->avemode){
@@ -1729,15 +1914,15 @@ void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifi
}
}
- pa->dietime=pa->time+pa->lifetime;
+ pa->dietime = pa->time + pa->lifetime;
if(pa->time >= cfra)
- pa->alive=PARS_UNBORN;
+ pa->alive = PARS_UNBORN;
- pa->state.time=cfra;
+ pa->state.time = cfra;
- pa->stick_ob=0;
- pa->flag&=~PARS_STICKY;
+ pa->stick_ob = 0;
+ pa->flag &= ~PARS_STICKY;
}
static void reset_all_particles(Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd, float dtime, float cfra, int from)
{
@@ -1807,7 +1992,8 @@ int psys_count_keyed_targets(Object *ob, ParticleSystem *psys)
BLI_freelistN(&lb);
return select;
}
-void set_keyed_keys(Object *ob, ParticleSystem *psys)
+
+static void set_keyed_keys(Object *ob, ParticleSystem *psys)
{
Object *kob = ob;
ParticleSystem *kpsys = psys;
@@ -1817,17 +2003,16 @@ void set_keyed_keys(Object *ob, ParticleSystem *psys)
float prevtime, nexttime, keyedtime;
/* no proper targets so let's clear and bail out */
- if(psys->totkeyed==0){
+ if(psys->totkeyed==0) {
free_keyed_keys(psys);
psys->flag &= ~PSYS_KEYED;
return;
}
- if(totpart && psys->particles->totkey != totkeys){
+ if(totpart && psys->particles->totkey != totkeys) {
free_keyed_keys(psys);
- psys->particles->keys = MEM_callocN(psys->totpart * totkeys * sizeof(ParticleKey),"Keyed keys");
-
+ psys->particles->keys = MEM_callocN(psys->totpart*totkeys*sizeof(ParticleKey), "Keyed keys");
psys->particles->totkey = totkeys;
for(i=1, pa=psys->particles+1; i<totpart; i++,pa++){
@@ -1839,9 +2024,10 @@ void set_keyed_keys(Object *ob, ParticleSystem *psys)
psys->flag &= ~PSYS_KEYED;
state.time=-1.0;
- for(k=0; k<totkeys; k++){
- for(i=0,pa=psys->particles; i<totpart; i++, pa++){
- psys_get_particle_state(kob, kpsys, i%kpsys->totpart, pa->keys + k, 1);
+ for(k=0; k<totkeys; k++) {
+ for(i=0,pa=psys->particles; i<totpart; i++, pa++) {
+ if(kpsys->totpart > 0)
+ psys_get_particle_state(kob, kpsys, i%kpsys->totpart, pa->keys + k, 1);
if(k==0)
pa->keys->time = pa->time;
@@ -1923,22 +2109,18 @@ static void react_to_events(ParticleSystem *psys, int pa_num)
for(re=psys->reactevents.first; re; re=re->next){
birth=0;
if(part->from==PART_FROM_PARTICLE){
- if(pa->num==re->pa_num){
+ if(pa->num==re->pa_num && pa->alive==PARS_UNBORN){
if(re->event==PART_EVENT_NEAR){
ParticleData *tpa = re->psys->particles+re->pa_num;
float pa_time=tpa->time + pa->foffset*tpa->lifetime;
- if(re->time > pa_time){
- pa->alive=PARS_ALIVE;
+ if(re->time >= pa_time){
pa->time=pa_time;
pa->dietime=pa->time+pa->lifetime;
}
}
else{
- if(pa->alive==PARS_UNBORN){
- pa->alive=PARS_ALIVE;
- pa->time=re->time;
- pa->dietime=pa->time+pa->lifetime;
- }
+ pa->time=re->time;
+ pa->dietime=pa->time+pa->lifetime;
}
}
}
@@ -1946,7 +2128,6 @@ static void react_to_events(ParticleSystem *psys, int pa_num)
dist=VecLenf(pa->state.co, re->state.co);
if(dist <= re->size){
if(pa->alive==PARS_UNBORN){
- pa->alive=PARS_ALIVE;
pa->time=re->time;
pa->dietime=pa->time+pa->lifetime;
birth=1;
@@ -1982,273 +2163,70 @@ void psys_get_reactor_target(Object *ob, ParticleSystem *psys, Object **target_o
/************************************************/
/* Point Cache */
/************************************************/
-void clear_particles_from_cache(Object *ob, ParticleSystem *psys, int cfra)
-{
- ParticleSystemModifierData *psmd = psys_get_modifier(ob,psys);
- int stack_index = modifiers_indexInObject(ob,(ModifierData*)psmd);
- BKE_ptcache_id_clear((ID *)ob, PTCACHE_CLEAR_ALL, cfra, stack_index);
-}
static void write_particles_to_cache(Object *ob, ParticleSystem *psys, int cfra)
{
- FILE *fp = NULL;
- ParticleSystemModifierData *psmd = psys_get_modifier(ob,psys);
+ PTCacheID pid;
+ PTCacheFile *pf;
ParticleData *pa;
- int stack_index = modifiers_indexInObject(ob,(ModifierData*)psmd);
- int i, totpart = psys->totpart;
+ int i, totpart= psys->totpart;
- if(totpart == 0) return;
+ if(totpart == 0)
+ return;
- fp = BKE_ptcache_id_fopen((ID *)ob, 'w', cfra, stack_index);
- if(!fp) return;
+ BKE_ptcache_id_from_particles(&pid, ob, psys);
+ pf= BKE_ptcache_file_open(&pid, PTCACHE_FILE_WRITE, cfra);
+ if(!pf)
+ return;
+ /* assuming struct consists of tightly packed floats */
for(i=0, pa=psys->particles; i<totpart; i++, pa++)
- fwrite(&pa->state, sizeof(ParticleKey), 1, fp);
+ BKE_ptcache_file_write_floats(pf, (float*)&pa->state, sizeof(ParticleKey)/sizeof(float));
- fclose(fp);
+ BKE_ptcache_file_close(pf);
}
+
static int get_particles_from_cache(Object *ob, ParticleSystem *psys, int cfra)
{
- FILE *fp = NULL;
- ParticleSystemModifierData *psmd = psys_get_modifier(ob,psys);
+ PTCacheID pid;
+ PTCacheFile *pf;
ParticleData *pa;
- int stack_index = modifiers_indexInObject(ob,(ModifierData*)psmd);
- int i, totpart = psys->totpart, ret = 1;
+ int i, totpart= psys->totpart;
- if(totpart == 0) return 0;
+ if(totpart == 0)
+ return 0;
- fp = BKE_ptcache_id_fopen((ID *)ob, 'r', cfra, stack_index);
- if(!fp)
- ret = 0;
- else {
- for(i=0, pa=psys->particles; i<totpart; i++, pa++)
- if((fread(&pa->state, sizeof(ParticleKey), 1, fp)) != 1) {
- ret = 0;
- break;
- }
-
- fclose(fp);
+ BKE_ptcache_id_from_particles(&pid, ob, psys);
+ pf= BKE_ptcache_file_open(&pid, PTCACHE_FILE_READ, cfra);
+ if(!pf)
+ return 0;
+
+ /* assuming struct consists of tightly packed floats */
+ for(i=0, pa=psys->particles; i<totpart; i++, pa++) {
+ if(cfra!=pa->state.time)
+ copy_particle_key(&pa->prev_state,&pa->state,1);
+ if(!BKE_ptcache_file_read_floats(pf, (float*)&pa->state, sizeof(ParticleKey)/sizeof(float))) {
+ BKE_ptcache_file_close(pf);
+ return 0;
+ }
}
- return ret;
+ BKE_ptcache_file_close(pf);
+
+ return 1;
}
+
/************************************************/
/* Effectors */
/************************************************/
-static float effector_falloff(PartDeflect *pd, float *eff_velocity, float *vec_to_part)
-{
- float eff_dir[3], temp[3];
- float falloff=1.0, fac, r_fac;
-
- VecCopyf(eff_dir,eff_velocity);
- Normalize(eff_dir);
-
- if(pd->flag & PFIELD_POSZ && Inpf(eff_dir,vec_to_part)<0.0f)
- falloff=0.0f;
- else switch(pd->falloff){
- case PFIELD_FALL_SPHERE:
- fac=VecLength(vec_to_part);
- if(pd->flag&PFIELD_USEMAX && fac>pd->maxdist){
- falloff=0.0f;
- break;
- }
-
- if(pd->flag & PFIELD_USEMIN){
- if(fac>pd->mindist)
- fac+=1.0f-pd->mindist;
- else
- fac=1.0f;
- }
- else if(fac<0.001)
- fac=0.001f;
-
- falloff=1.0f/(float)pow((double)fac,(double)pd->f_power);
- break;
-
- case PFIELD_FALL_TUBE:
- fac=Inpf(vec_to_part,eff_dir);
- if(pd->flag&PFIELD_USEMAX && ABS(fac)>pd->maxdist){
- falloff=0.0f;
- break;
- }
-
- VECADDFAC(temp,vec_to_part,eff_dir,-fac);
- r_fac=VecLength(temp);
- if(pd->flag&PFIELD_USEMAXR && r_fac>pd->maxrad){
- falloff=0.0f;
- break;
- }
-
- fac=ABS(fac);
-
-
- if(pd->flag & PFIELD_USEMIN){
- if(fac>pd->mindist)
- fac+=1.0f-pd->mindist;
- else
- fac=1.0f;
- }
- else if(fac<0.001)
- fac=0.001f;
-
- if(pd->flag & PFIELD_USEMINR){
- if(r_fac>pd->minrad)
- r_fac+=1.0f-pd->minrad;
- else
- r_fac=1.0f;
- }
- else if(r_fac<0.001)
- r_fac=0.001f;
-
- falloff=1.0f/((float)pow((double)fac,(double)pd->f_power)*(float)pow((double)r_fac,(double)pd->f_power_r));
-
- break;
- case PFIELD_FALL_CONE:
- fac=Inpf(vec_to_part,eff_dir);
- if(pd->flag&PFIELD_USEMAX && ABS(fac)>pd->maxdist){
- falloff=0.0f;
- break;
- }
- r_fac=saacos(fac/VecLength(vec_to_part))*180.0f/(float)M_PI;
- if(pd->flag&PFIELD_USEMAXR && r_fac>pd->maxrad){
- falloff=0.0f;
- break;
- }
-
- if(pd->flag & PFIELD_USEMIN){
- if(fac>pd->mindist)
- fac+=1.0f-pd->mindist;
- else
- fac=1.0f;
- }
- else if(fac<0.001)
- fac=0.001f;
-
- if(pd->flag & PFIELD_USEMINR){
- if(r_fac>pd->minrad)
- r_fac+=1.0f-pd->minrad;
- else
- r_fac=1.0f;
- }
- else if(r_fac<0.001)
- r_fac=0.001f;
-
- falloff=1.0f/((float)pow((double)fac,(double)pd->f_power)*(float)pow((double)r_fac,(double)pd->f_power_r));
-
- break;
-// case PFIELD_FALL_INSIDE:
- //for(i=0; i<totface; i++,mface++){
- // VECCOPY(v1,mvert[mface->v1].co);
- // VECCOPY(v2,mvert[mface->v2].co);
- // VECCOPY(v3,mvert[mface->v3].co);
-
- // if(AxialLineIntersectsTriangle(a,co1, co2, v2, v3, v1, &lambda)){
- // if(from==PART_FROM_FACE)
- // (pa+(int)(lambda*size[a])*a0mul)->flag &= ~PARS_UNEXIST;
- // else /* store number of intersections */
- // (pa+(int)(lambda*size[a])*a0mul)->loop++;
- // }
- //
- // if(mface->v4){
- // VECCOPY(v4,mvert[mface->v4].co);
-
- // if(AxialLineIntersectsTriangle(a,co1, co2, v4, v1, v3, &lambda)){
- // if(from==PART_FROM_FACE)
- // (pa+(int)(lambda*size[a])*a0mul)->flag &= ~PARS_UNEXIST;
- // else
- // (pa+(int)(lambda*size[a])*a0mul)->loop++;
- // }
- // }
- //}
-
-// break;
- }
-
- return falloff;
-}
-static void do_physical_effector(short type, float force_val, float distance, float falloff, float size, float damp,
- float *eff_velocity, float *vec_to_part, float *velocity, float *field, int planar)
-{
- float mag_vec[3]={0,0,0};
- float temp[3], temp2[3];
- float eff_vel[3];
-
- VecCopyf(eff_vel,eff_velocity);
- Normalize(eff_vel);
-
- switch(type){
- case PFIELD_WIND:
- VECCOPY(mag_vec,eff_vel);
-
- VecMulf(mag_vec,force_val*falloff);
- VecAddf(field,field,mag_vec);
- break;
-
- case PFIELD_FORCE:
- if(planar)
- Projf(mag_vec,vec_to_part,eff_vel);
- else
- VecCopyf(mag_vec,vec_to_part);
-
- VecMulf(mag_vec,force_val*falloff);
- VecAddf(field,field,mag_vec);
- break;
-
- case PFIELD_VORTEX:
- Crossf(mag_vec,eff_vel,vec_to_part);
- Normalize(mag_vec);
-
- VecMulf(mag_vec,force_val*distance*falloff);
- VecAddf(field,field,mag_vec);
-
- break;
- case PFIELD_MAGNET:
- if(planar)
- VecCopyf(temp,eff_vel);
- else
- /* magnetic field of a moving charge */
- Crossf(temp,eff_vel,vec_to_part);
-
- Crossf(temp2,velocity,temp);
- VecAddf(mag_vec,mag_vec,temp2);
-
- VecMulf(mag_vec,force_val*falloff);
- VecAddf(field,field,mag_vec);
- break;
- case PFIELD_HARMONIC:
- if(planar)
- Projf(mag_vec,vec_to_part,eff_vel);
- else
- VecCopyf(mag_vec,vec_to_part);
-
- VecMulf(mag_vec,force_val*falloff);
- VecSubf(field,field,mag_vec);
-
- VecCopyf(mag_vec,velocity);
- /* 1.9 is an experimental value to get critical damping at damp=1.0 */
- VecMulf(mag_vec,damp*1.9f*(float)sqrt(force_val));
- VecSubf(field,field,mag_vec);
- break;
- case PFIELD_NUCLEAR:
- /*pow here is root of cosine expression below*/
- //rad=(float)pow(2.0,-1.0/power)*distance/size;
- //VECCOPY(mag_vec,vec_to_part);
- //Normalize(mag_vec);
- //VecMulf(mag_vec,(float)cos(3.0*M_PI/2.0*(1.0-1.0/(pow(rad,power)+1.0)))/(rad+0.2f));
- //VECADDFAC(field,field,mag_vec,force_val);
- break;
- }
-}
static void do_texture_effector(Tex *tex, short mode, short is_2d, float nabla, short object, float *pa_co, float obmat[4][4], float force_val, float falloff, float *field)
{
TexResult result[4];
float tex_co[3], strength, mag_vec[3];
- int i;
-
- if(tex==0) return;
+ int hasrgb;
+ if(tex==NULL) return;
- for(i=0; i<4; i++)
- result[i].nor=0;
+ result[0].nor = result[1].nor = result[2].nor = result[3].nor = 0;
strength= force_val*falloff;///(float)pow((double)distance,(double)power);
@@ -2264,9 +2242,9 @@ static void do_texture_effector(Tex *tex, short mode, short is_2d, float nabla,
Mat4Mul3Vecfl(obmat,tex_co);
}
- multitex_ext(tex, tex_co, NULL,NULL, 1, result);
+ hasrgb = multitex_ext(tex, tex_co, NULL,NULL, 1, result);
- if(mode==PFIELD_TEX_RGB){
+ if(hasrgb && mode==PFIELD_TEX_RGB){
mag_vec[0]= (0.5f-result->tr)*strength;
mag_vec[1]= (0.5f-result->tg)*strength;
mag_vec[2]= (0.5f-result->tb)*strength;
@@ -2285,7 +2263,7 @@ static void do_texture_effector(Tex *tex, short mode, short is_2d, float nabla,
tex_co[2]+= nabla;
multitex_ext(tex, tex_co, NULL,NULL, 1, result+3);
- if(mode==PFIELD_TEX_GRAD){
+ if(mode==PFIELD_TEX_GRAD || !hasrgb){ /* if we dont have rgb fall back to grad */
mag_vec[0]= (result[0].tin-result[1].tin)*strength;
mag_vec[1]= (result[0].tin-result[2].tin)*strength;
mag_vec[2]= (result[0].tin-result[3].tin)*strength;
@@ -2333,7 +2311,9 @@ static void add_to_effectors(ListBase *lb, Object *ob, Object *obsrc, ParticleSy
}
}
else if(pd->forcefield)
+ {
type |= PSYS_EC_EFFECTOR;
+ }
}
if(pd && pd->deflect)
@@ -2345,6 +2325,9 @@ static void add_to_effectors(ListBase *lb, Object *ob, Object *obsrc, ParticleSy
ec->type=type;
ec->distances=0;
ec->locations=0;
+ ec->rng = rng_new(1);
+ rng_srandom(ec->rng, (unsigned int)(ceil(PIL_check_seconds_timer()))); // use better seed
+
BLI_addtail(lb, ec);
}
@@ -2358,11 +2341,14 @@ static void add_to_effectors(ListBase *lb, Object *ob, Object *obsrc, ParticleSy
for(i=0; epsys; epsys=epsys->next,i++){
type=0;
- if(epsys!=psys){
+ if(epsys!=psys || (psys->part->flag & PART_SELF_EFFECT)){
epart=epsys->part;
- if(epsys->part->pd && epsys->part->pd->forcefield)
+ if((epsys->part->pd && epsys->part->pd->forcefield)
+ || (epsys->part->pd2 && epsys->part->pd2->forcefield))
+ {
type=PSYS_EC_PARTICLE;
+ }
if(epart->type==PART_REACTOR) {
tob=epsys->target_ob;
@@ -2377,6 +2363,9 @@ static void add_to_effectors(ListBase *lb, Object *ob, Object *obsrc, ParticleSy
ec->ob= ob;
ec->type=type;
ec->psys_nbr=i;
+ ec->rng = rng_new(1);
+ rng_srandom(ec->rng, (unsigned int)(ceil(PIL_check_seconds_timer())));
+
BLI_addtail(lb, ec);
}
}
@@ -2384,34 +2373,51 @@ static void add_to_effectors(ListBase *lb, Object *ob, Object *obsrc, ParticleSy
}
}
+
+static void psys_init_effectors_recurs(Object *ob, Object *obsrc, ParticleSystem *psys, ListBase *listb, int level)
+{
+ Group *group;
+ GroupObject *go;
+ unsigned int layer= obsrc->lay;
+
+ if(level>MAX_DUPLI_RECUR) return;
+
+ if(ob->lay & layer) {
+ if(ob->pd || ob->particlesystem.first)
+ add_to_effectors(listb, ob, obsrc, psys);
+
+ if(ob->dup_group) {
+ group= ob->dup_group;
+ for(go= group->gobject.first; go; go= go->next)
+ psys_init_effectors_recurs(go->ob, obsrc, psys, listb, level+1);
+ }
+ }
+}
+
void psys_init_effectors(Object *obsrc, Group *group, ParticleSystem *psys)
{
- ListBase *listb=&psys->effectors;
+ ListBase *listb= &psys->effectors;
Base *base;
- unsigned int layer= obsrc->lay;
listb->first=listb->last=0;
if(group) {
GroupObject *go;
- for(go= group->gobject.first; go; go= go->next) {
- if( (go->ob->lay & layer) && (go->ob->pd || go->ob->particlesystem.first)) {
- add_to_effectors(listb, go->ob, obsrc, psys);
- }
- }
+ for(go= group->gobject.first; go; go= go->next)
+ psys_init_effectors_recurs(go->ob, obsrc, psys, listb, 0);
}
else {
- for(base = G.scene->base.first; base; base= base->next) {
- if( (base->lay & layer) && (base->object->pd || base->object->particlesystem.first)) {
- add_to_effectors(listb, base->object, obsrc, psys);
- }
- }
+ for(base = G.scene->base.first; base; base= base->next)
+ psys_init_effectors_recurs(base->object, obsrc, psys, listb, 0);
}
}
void psys_end_effectors(ParticleSystem *psys)
{
+ /* NOTE:
+ ec->ob is not valid in here anymore! - dg
+ */
ListBase *lb=&psys->effectors;
if(lb->first) {
ParticleEffectorCache *ec;
@@ -2430,23 +2436,28 @@ void psys_end_effectors(ParticleSystem *psys)
if(ec->tree)
BLI_kdtree_free(ec->tree);
+
+ if(ec->rng)
+ rng_free(ec->rng);
+
}
BLI_freelistN(lb);
}
}
-static void precalc_effectors(Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd)
+static void precalc_effectors(Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd, float cfra)
{
ListBase *lb=&psys->effectors;
ParticleEffectorCache *ec;
ParticleSettings *part=psys->part;
ParticleData *pa;
float vec2[3],loc[3],*co=0;
- int p,totpart,totvert;
+ int p,totpart;
for(ec= lb->first; ec; ec= ec->next) {
PartDeflect *pd= ec->ob->pd;
+ co = NULL;
if(ec->type==PSYS_EC_EFFECTOR && pd->forcefield==PFIELD_GUIDE && ec->ob->type==OB_CURVE
&& part->phystype!=PART_PHYS_BOIDS) {
@@ -2467,7 +2478,7 @@ static void precalc_effectors(Object *ob, ParticleSystem *psys, ParticleSystemMo
ec->locations=MEM_callocN(totpart*3*sizeof(float),"particle locations");
for(p=0,pa=psys->particles; p<totpart; p++, pa++){
- psys_particle_on_emitter(ob,psmd,part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,loc,0,0,0,0,0);
+ psys_particle_on_emitter(psmd,part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,loc,0,0,0,0,0);
Mat4MulVecfl(ob->obmat,loc);
ec->distances[p]=VecLenf(loc,vec);
VECSUB(loc,loc,vec);
@@ -2475,96 +2486,18 @@ static void precalc_effectors(Object *ob, ParticleSystem *psys, ParticleSystemMo
}
}
}
- else if(ec->type==PSYS_EC_DEFLECT){
- DerivedMesh *dm;
- MFace *mface=0;
- MVert *mvert=0;
- int i, totface;
- float v1[3],v2[3],v3[3],v4[4], *min, *max;
-
- if(ob==ec->ob)
- dm=psmd->dm;
- else{
- psys_disable_all(ec->ob);
-
- dm=mesh_get_derived_final(ec->ob,0);
-
- psys_enable_all(ec->ob);
- }
-
- if(dm){
- totvert=dm->getNumVerts(dm);
- totface=dm->getNumFaces(dm);
- mface=dm->getFaceDataArray(dm,CD_MFACE);
- mvert=dm->getVertDataArray(dm,CD_MVERT);
-
- /* Decide which is faster to calculate by the amount of*/
- /* matrice multiplications needed to convert spaces. */
- /* With size deflect we have to convert allways because */
- /* the object can be scaled nonuniformly (sphere->ellipsoid). */
- if(totvert<2*psys->totpart || part->flag & PART_SIZE_DEFL){
- co=ec->vert_cos=MEM_callocN(sizeof(float)*3*totvert,"Particle deflection vert cos");
- /* convert vert coordinates to global (particle) coordinates */
- for(i=0; i<totvert; i++, co+=3){
- VECCOPY(co,mvert[i].co);
- Mat4MulVecfl(ec->ob->obmat,co);
- }
- co=ec->vert_cos;
- }
- else
- ec->vert_cos=0;
-
- INIT_MINMAX(ec->ob_minmax,ec->ob_minmax+3);
-
- min=ec->face_minmax=MEM_callocN(sizeof(float)*6*totface,"Particle deflection face minmax");
- max=min+3;
-
- for(i=0; i<totface; i++,mface++,min+=6,max+=6){
- if(co){
- VECCOPY(v1,co+3*mface->v1);
- VECCOPY(v2,co+3*mface->v2);
- VECCOPY(v3,co+3*mface->v3);
- }
- else{
- VECCOPY(v1,mvert[mface->v1].co);
- VECCOPY(v2,mvert[mface->v2].co);
- VECCOPY(v3,mvert[mface->v3].co);
- }
- INIT_MINMAX(min,max);
- DO_MINMAX(v1,min,max);
- DO_MINMAX(v2,min,max);
- DO_MINMAX(v3,min,max);
-
- if(mface->v4){
- if(co){
- VECCOPY(v4,co+3*mface->v4);
- }
- else{
- VECCOPY(v4,mvert[mface->v4].co);
- }
- DO_MINMAX(v4,min,max);
- }
-
- DO_MINMAX(min,ec->ob_minmax,ec->ob_minmax+3);
- DO_MINMAX(max,ec->ob_minmax,ec->ob_minmax+3);
- }
- }
- else
- ec->face_minmax=0;
- }
else if(ec->type==PSYS_EC_PARTICLE){
+ Object *eob = ec->ob;
+ ParticleSystem *epsys = BLI_findlink(&eob->particlesystem,ec->psys_nbr);
+ ParticleSettings *epart = epsys->part;
+ ParticleData *epa;
+ int p, totepart = epsys->totpart;
+
if(psys->part->phystype==PART_PHYS_BOIDS){
- Object *eob = ec->ob;
- ParticleSystem *epsys;
- ParticleSettings *epart;
- ParticleData *epa;
ParticleKey state;
PartDeflect *pd;
- int totepart, p;
- epsys= BLI_findlink(&eob->particlesystem,ec->psys_nbr);
- epart= epsys->part;
+
pd= epart->pd;
- totepart= epsys->totpart;
if(pd->forcefield==PFIELD_FORCE && totepart){
KDTree *tree;
@@ -2578,13 +2511,19 @@ static void precalc_effectors(Object *ob, ParticleSystem *psys, ParticleSystemMo
BLI_kdtree_balance(tree);
}
}
+
+ }
+ else if(ec->type==PSYS_EC_DEFLECT) {
+ CollisionModifierData *collmd = ( CollisionModifierData * ) ( modifiers_findByType ( ec->ob, eModifierType_Collision ) );
+ if(collmd)
+ collision_move_object(collmd, 1.0, 0.0);
}
}
}
/* calculate forces that all effectors apply to a particle*/
-static void do_effectors(int pa_no, ParticleData *pa, ParticleKey *state, Object *ob, ParticleSystem *psys, float *force_field, float *vel,float framestep, float cfra)
+void do_effectors(int pa_no, ParticleData *pa, ParticleKey *state, Object *ob, ParticleSystem *psys, float *rootco, float *force_field, float *vel,float framestep, float cfra)
{
Object *eob;
ParticleSystem *epsys;
@@ -2595,35 +2534,31 @@ static void do_effectors(int pa_no, ParticleData *pa, ParticleKey *state, Object
ListBase *lb=&psys->effectors;
ParticleEffectorCache *ec;
float distance, vec_to_part[3];
- float falloff;
+ float falloff, charge = 0.0f;
int p;
/* check all effector objects for interaction */
if(lb->first){
+ if(psys->part->pd && psys->part->pd->forcefield==PFIELD_CHARGE){
+ /* Only the charge of the effected particle is used for
+ interaction, not fall-offs. If the fall-offs aren't the
+ same this will be unphysical, but for animation this
+ could be the wanted behavior. If you want physical
+ correctness the fall-off should be spherical 2.0 anyways.
+ */
+ charge = psys->part->pd->f_strength;
+ }
+ if(psys->part->pd2 && psys->part->pd2->forcefield==PFIELD_CHARGE){
+ charge += psys->part->pd2->f_strength;
+ }
for(ec = lb->first; ec; ec= ec->next){
eob= ec->ob;
if(ec->type & PSYS_EC_EFFECTOR){
pd=eob->pd;
if(psys->part->type!=PART_HAIR && psys->part->integrator)
where_is_object_time(eob,cfra);
- /* Get IPO force strength and fall off values here */
- //if (has_ipo_code(eob->ipo, OB_PD_FSTR))
- // force_val = IPO_GetFloatValue(eob->ipo, OB_PD_FSTR, cfra);
- //else
- // force_val = pd->f_strength;
-
- //if (has_ipo_code(eob->ipo, OB_PD_FFALL))
- // ffall_val = IPO_GetFloatValue(eob->ipo, OB_PD_FFALL, cfra);
- //else
- // ffall_val = pd->f_power;
-
- //if (has_ipo_code(eob->ipo, OB_PD_FMAXD))
- // maxdist = IPO_GetFloatValue(eob->ipo, OB_PD_FMAXD, cfra);
- //else
- // maxdist = pd->maxdist;
/* use center of object for distance calculus */
- //obloc= eob->obmat[3];
VecSubf(vec_to_part, state->co, eob->obmat[3]);
distance = VecLength(vec_to_part);
@@ -2631,23 +2566,27 @@ static void do_effectors(int pa_no, ParticleData *pa, ParticleKey *state, Object
if(falloff<=0.0f)
; /* don't do anything */
- else if(pd->forcefield==PFIELD_TEXTURE)
+ else if(pd->forcefield==PFIELD_TEXTURE) {
do_texture_effector(pd->tex, pd->tex_mode, pd->flag&PFIELD_TEX_2D, pd->tex_nabla,
- pd->flag & PFIELD_TEX_OBJECT, state->co, eob->obmat,
- pd->f_strength, falloff, force_field);
- else
- do_physical_effector(pd->forcefield,pd->f_strength,distance,
- falloff,pd->f_dist,pd->f_damp,eob->obmat[2],vec_to_part,
- pa->state.vel,force_field,pd->flag&PFIELD_PLANAR);
+ pd->flag & PFIELD_TEX_OBJECT, (pd->flag & PFIELD_TEX_ROOTCO) ? rootco : state->co, eob->obmat,
+ pd->f_strength, falloff, force_field);
+ } else {
+ do_physical_effector(eob, state->co, pd->forcefield,pd->f_strength,distance,
+ falloff,0.0,pd->f_damp,eob->obmat[2],vec_to_part,
+ state->vel,force_field,pd->flag&PFIELD_PLANAR,ec->rng,pd->f_noise,charge,pa->size);
+ }
}
if(ec->type & PSYS_EC_PARTICLE){
- int totepart;
+ int totepart, i;
epsys= BLI_findlink(&eob->particlesystem,ec->psys_nbr);
epart= epsys->part;
- pd= epart->pd;
+ pd=epart->pd;
totepart= epsys->totpart;
-
- if(pd->forcefield==PFIELD_HARMONIC){
+
+ if(totepart <= 0)
+ continue;
+
+ if(pd && pd->forcefield==PFIELD_HARMONIC){
/* every particle is mapped to only one harmonic effector particle */
p= pa_no%epsys->totpart;
totepart= p+1;
@@ -2659,33 +2598,29 @@ static void do_effectors(int pa_no, ParticleData *pa, ParticleKey *state, Object
epsys->lattice=psys_get_lattice(ob,psys);
for(; p<totepart; p++){
+ /* particle skips itself as effector */
+ if(epsys==psys && p == pa_no) continue;
+
epa = epsys->particles + p;
- estate.time=-1.0;
+ estate.time=cfra;
if(psys_get_particle_state(eob,epsys,p,&estate,0)){
VECSUB(vec_to_part, state->co, estate.co);
distance = VecLength(vec_to_part);
-
- //if(pd->forcefield==PFIELD_HARMONIC){
- // //if(cfra < epa->time + radius){ /* radius is fade-in in ui */
- // // eforce*=(cfra-epa->time)/radius;
- // //}
- //}
- //else{
- // /* Limit minimum distance to effector particle so that */
- // /* the force is not too big */
- // if (distance < 0.001) distance = 0.001f;
- //}
- falloff=effector_falloff(pd,estate.vel,vec_to_part);
+ for(i=0, pd = epart->pd; i<2; i++,pd = epart->pd2) {
+ if(pd==NULL || pd->forcefield==0) continue;
- if(falloff<=0.0f)
- ; /* don't do anything */
- else
- do_physical_effector(pd->forcefield,pd->f_strength,distance,
- falloff,epart->size,pd->f_damp,estate.vel,vec_to_part,
- state->vel,force_field,0);
+ falloff=effector_falloff(pd,estate.vel,vec_to_part);
+
+ if(falloff<=0.0f)
+ ; /* don't do anything */
+ else
+ do_physical_effector(eob, state->co, pd->forcefield,pd->f_strength,distance,
+ falloff,epart->size,pd->f_damp,estate.vel,vec_to_part,
+ state->vel,force_field,0, ec->rng, pd->f_noise,charge,pa->size);
+ }
}
- else if(pd->forcefield==PFIELD_HARMONIC && cfra-framestep <= epa->dietime && cfra>epa->dietime){
+ else if(pd && pd->forcefield==PFIELD_HARMONIC && cfra-framestep <= epa->dietime && cfra>epa->dietime){
/* first step after key release */
psys_get_particle_state(eob,epsys,p,&estate,1);
VECADD(vel,vel,estate.vel);
@@ -2706,7 +2641,7 @@ static void do_effectors(int pa_no, ParticleData *pa, ParticleKey *state, Object
/* Newtonian physics */
/************************************************/
/* gathers all forces that effect particles and calculates a new state for the particle */
-static void apply_particle_forces(int pa_no, ParticleData *pa, Object *ob, ParticleSystem *psys, ParticleSettings *part, float timestep, float dfra, float cfra, ParticleKey *state)
+static void apply_particle_forces(int pa_no, ParticleData *pa, Object *ob, ParticleSystem *psys, ParticleSettings *part, float timestep, float dfra, float cfra)
{
ParticleKey states[5], tkey;
float force[3],tvel[3],dx[4][3],dv[4][3];
@@ -2714,7 +2649,7 @@ static void apply_particle_forces(int pa_no, ParticleData *pa, Object *ob, Parti
int i, steps=1;
/* maintain angular velocity */
- VECCOPY(state->ave,pa->state.ave);
+ VECCOPY(pa->state.ave,pa->prev_state.ave);
if(part->flag & PART_SIZEMASS)
pa_mass*=pa->size;
@@ -2737,7 +2672,8 @@ static void apply_particle_forces(int pa_no, ParticleData *pa, Object *ob, Parti
force[0]=force[1]=force[2]=0.0;
tvel[0]=tvel[1]=tvel[2]=0.0;
/* add effectors */
- do_effectors(pa_no,pa,states+i,ob,psys,force,tvel,dfra,fra);
+ if(part->type != PART_HAIR)
+ do_effectors(pa_no,pa,states+i,ob,psys,states->co,force,tvel,dfra,fra);
/* calculate air-particle interaction */
if(part->dragfac!=0.0f){
@@ -2757,17 +2693,14 @@ static void apply_particle_forces(int pa_no, ParticleData *pa, Object *ob, Parti
/* add global acceleration (gravitation) */
VECADD(force,force,part->acc);
-
- //VecMulf(force,dtime);
/* calculate next state */
VECADD(states[i].vel,states[i].vel,tvel);
- //VecMulf(force,0.5f*dt);
switch(part->integrator){
case PART_INT_EULER:
- VECADDFAC(state->co,states->co,states->vel,dtime);
- VECADDFAC(state->vel,states->vel,force,dtime);
+ VECADDFAC(pa->state.co,states->co,states->vel,dtime);
+ VECADDFAC(pa->state.vel,states->vel,force,dtime);
break;
case PART_INT_MIDPOINT:
if(i==0){
@@ -2776,8 +2709,8 @@ static void apply_particle_forces(int pa_no, ParticleData *pa, Object *ob, Parti
fra=psys->cfra+0.5f*dfra;
}
else{
- VECADDFAC(state->co,states->co,states[1].vel,dtime);
- VECADDFAC(state->vel,states->vel,force,dtime);
+ VECADDFAC(pa->state.co,states->co,states[1].vel,dtime);
+ VECADDFAC(pa->state.vel,states->vel,force,dtime);
}
break;
case PART_INT_RK4:
@@ -2817,77 +2750,78 @@ static void apply_particle_forces(int pa_no, ParticleData *pa, Object *ob, Parti
VECCOPY(dv[3],force);
VecMulf(dv[3],dtime);
- VECADDFAC(state->co,states->co,dx[0],1.0f/6.0f);
- VECADDFAC(state->co,state->co,dx[1],1.0f/3.0f);
- VECADDFAC(state->co,state->co,dx[2],1.0f/3.0f);
- VECADDFAC(state->co,state->co,dx[3],1.0f/6.0f);
+ VECADDFAC(pa->state.co,states->co,dx[0],1.0f/6.0f);
+ VECADDFAC(pa->state.co,pa->state.co,dx[1],1.0f/3.0f);
+ VECADDFAC(pa->state.co,pa->state.co,dx[2],1.0f/3.0f);
+ VECADDFAC(pa->state.co,pa->state.co,dx[3],1.0f/6.0f);
- VECADDFAC(state->vel,states->vel,dv[0],1.0f/6.0f);
- VECADDFAC(state->vel,state->vel,dv[1],1.0f/3.0f);
- VECADDFAC(state->vel,state->vel,dv[2],1.0f/3.0f);
- VECADDFAC(state->vel,state->vel,dv[3],1.0f/6.0f);
+ VECADDFAC(pa->state.vel,states->vel,dv[0],1.0f/6.0f);
+ VECADDFAC(pa->state.vel,pa->state.vel,dv[1],1.0f/3.0f);
+ VECADDFAC(pa->state.vel,pa->state.vel,dv[2],1.0f/3.0f);
+ VECADDFAC(pa->state.vel,pa->state.vel,dv[3],1.0f/6.0f);
}
break;
}
- //VECADD(states[i+1].co,states[i+1].co,force);
}
/* damp affects final velocity */
if(part->dampfac!=0.0)
- VecMulf(state->vel,1.0f-part->dampfac);
+ VecMulf(pa->state.vel,1.0f-part->dampfac);
/* finally we do guides */
time=(cfra-pa->time)/pa->lifetime;
CLAMP(time,0.0,1.0);
- VECCOPY(tkey.co,state->co);
- VECCOPY(tkey.vel,state->vel);
- tkey.time=state->time;
- if(do_guide(&tkey,pa_no,time,&psys->effectors)){
- VECCOPY(state->co,tkey.co);
- /* guides don't produce valid velocity */
- VECSUB(state->vel,tkey.co,pa->state.co);
- VecMulf(state->vel,1.0f/dtime);
- state->time=tkey.time;
+ VECCOPY(tkey.co,pa->state.co);
+ VECCOPY(tkey.vel,pa->state.vel);
+ tkey.time=pa->state.time;
+
+ if(part->type != PART_HAIR) {
+ if(do_guide(&tkey,pa_no,time,&psys->effectors)) {
+ VECCOPY(pa->state.co,tkey.co);
+ /* guides don't produce valid velocity */
+ VECSUB(pa->state.vel,tkey.co,pa->prev_state.co);
+ VecMulf(pa->state.vel,1.0f/dtime);
+ pa->state.time=tkey.time;
+ }
}
}
-static void rotate_particle(ParticleSettings *part, ParticleData *pa, float dfra, float timestep, ParticleKey *state)
+static void rotate_particle(ParticleSettings *part, ParticleData *pa, float dfra, float timestep)
{
float rotfac, rot1[4], rot2[4]={1.0,0.0,0.0,0.0}, dtime=dfra*timestep;
if((part->flag & PART_ROT_DYN)==0){
- if(ELEM(part->avemode,PART_AVE_SPIN,PART_AVE_VEL)){
+ if(part->avemode==PART_AVE_SPIN){
float angle;
- float len1 = VecLength(pa->state.vel);
- float len2 = VecLength(state->vel);
+ float len1 = VecLength(pa->prev_state.vel);
+ float len2 = VecLength(pa->state.vel);
if(len1==0.0f || len2==0.0f)
- state->ave[0]=state->ave[1]=state->ave[2]=0.0f;
+ pa->state.ave[0]=pa->state.ave[1]=pa->state.ave[2]=0.0f;
else{
- Crossf(state->ave,pa->state.vel,state->vel);
- Normalize(state->ave);
- angle=Inpf(pa->state.vel,state->vel)/(len1*len2);
- VecMulf(state->ave,saacos(angle)/dtime);
+ Crossf(pa->state.ave,pa->prev_state.vel,pa->state.vel);
+ Normalize(pa->state.ave);
+ angle=Inpf(pa->prev_state.vel,pa->state.vel)/(len1*len2);
+ VecMulf(pa->state.ave,saacos(angle)/dtime);
}
- }
- if(part->avemode == PART_AVE_SPIN)
- VecRotToQuat(state->vel,dtime*part->avefac,rot2);
+ VecRotToQuat(pa->state.vel,dtime*part->avefac,rot2);
+ }
}
- rotfac=VecLength(state->ave);
+ rotfac=VecLength(pa->state.ave);
if(rotfac==0.0){ /* QuatOne (in VecRotToQuat) doesn't give unit quat [1,0,0,0]?? */
rot1[0]=1.0;
rot1[1]=rot1[2]=rot1[3]=0;
}
else{
- VecRotToQuat(state->ave,rotfac*dtime,rot1);
+ VecRotToQuat(pa->state.ave,rotfac*dtime,rot1);
}
- QuatMul(state->rot,rot1,pa->state.rot);
- QuatMul(state->rot,rot2,state->rot);
+ QuatMul(pa->state.rot,rot1,pa->prev_state.rot);
+ QuatMul(pa->state.rot,rot2,pa->state.rot);
/* keep rotation quat in good health */
- NormalQuat(state->rot);
+ NormalQuat(pa->state.rot);
}
/* convert from triangle barycentric weights to quad mean value weights */
@@ -2922,7 +2856,7 @@ int psys_intersect_dm(Object *ob, DerivedMesh *dm, float *vert_cos, float *co1,
dm=mesh_get_derived_final(ob,0);
if(dm==0)
- mesh_get_derived_deform(ob,0);
+ dm=mesh_get_derived_deform(ob,0);
psys_enable_all(ob);
@@ -3032,37 +2966,122 @@ int psys_intersect_dm(Object *ob, DerivedMesh *dm, float *vert_cos, float *co1,
}
return intersect;
}
+
+/* container for moving data between deflet_particle and particle_intersect_face */
+typedef struct ParticleCollision
+{
+ struct Object *ob, *ob_t; // collided and current objects
+ struct CollisionModifierData *md; // collision modifier for ob_t;
+ float nor[3]; // normal at collision point
+ float vel[3]; // velocity of collision point
+ float co1[3], co2[3]; // ray start and end points
+ float ray_len; // original length of co2-co1, needed for collision time evaluation
+ float t; // time of previous collision, needed for substracting face velocity
+}
+ParticleCollision;
+
+static void particle_intersect_face(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
+{
+ ParticleCollision *col = (ParticleCollision *) userdata;
+ MFace *face = col->md->mfaces + index;
+ MVert *x = col->md->x;
+ MVert *v = col->md->current_v;
+ float vel[3], co1[3], co2[3], uv[2], ipoint[3], temp[3], t;
+
+ float *t0, *t1, *t2, *t3;
+ t0 = x[ face->v1 ].co;
+ t1 = x[ face->v2 ].co;
+ t2 = x[ face->v3 ].co;
+ t3 = face->v4 ? x[ face->v4].co : NULL;
+
+ /* calculate average velocity of face */
+ VECCOPY(vel, v[ face->v1 ].co);
+ VECADD(vel, vel, v[ face->v2 ].co);
+ VECADD(vel, vel, v[ face->v3 ].co);
+ VecMulf(vel, 0.33334f);
+
+ /* substract face velocity, in other words convert to
+ a coordinate system where only the particle moves */
+ VECADDFAC(co1, col->co1, vel, -col->t);
+ VECSUB(co2, col->co2, vel);
+
+ do
+ {
+ if(ray->radius == 0.0f) {
+ if(LineIntersectsTriangle(co1, co2, t0, t1, t2, &t, uv)) {
+ if(t >= 0.0f && t < hit->dist/col->ray_len) {
+ hit->dist = col->ray_len * t;
+ hit->index = index;
+
+ /* calculate normal that's facing the particle */
+ CalcNormFloat(t0, t1, t2, col->nor);
+ VECSUB(temp, co2, co1);
+ if(Inpf(col->nor, temp) > 0.0f)
+ VecMulf(col->nor, -1.0f);
+
+ VECCOPY(col->vel,vel);
+
+ col->ob = col->ob_t;
+ }
+ }
+ }
+ else {
+ if(SweepingSphereIntersectsTriangleUV(co1, co2, ray->radius, t0, t1, t2, &t, ipoint)) {
+ if(t >=0.0f && t < hit->dist/col->ray_len) {
+ hit->dist = col->ray_len * t;
+ hit->index = index;
+
+ VecLerpf(temp, co1, co2, t);
+
+ VECSUB(col->nor, temp, ipoint);
+ Normalize(col->nor);
+
+ VECCOPY(col->vel,vel);
+
+ col->ob = col->ob_t;
+ }
+ }
+ }
+
+ t1 = t2;
+ t2 = t3;
+ t3 = NULL;
+
+ } while(t2);
+}
/* particle - mesh collision code */
/* in addition to basic point to surface collisions handles friction & damping,*/
/* angular momentum <-> linear momentum and swept sphere - mesh collisions */
/* 1. check for all possible deflectors for closest intersection on particle path */
/* 2. if deflection was found kill the particle or calculate new coordinates */
-static void deflect_particle(Object *pob, ParticleSystemModifierData *psmd, ParticleSystem *psys, ParticleSettings *part, ParticleData *pa, int p, float dfra, float cfra, ParticleKey *state, int *pa_die){
- Object *ob, *min_ob;
- MFace *mface;
- MVert *mvert;
- DerivedMesh *dm;
+static void deflect_particle(Object *pob, ParticleSystemModifierData *psmd, ParticleSystem *psys, ParticleSettings *part, ParticleData *pa, int p, float timestep, float dfra, float cfra){
+ Object *ob = NULL;
ListBase *lb=&psys->effectors;
ParticleEffectorCache *ec;
- ParticleKey cstate;
- float imat[4][4];
- float co1[3],co2[3],def_loc[3],def_nor[3],unit_nor[3],def_tan[3],dvec[3],def_vel[3],dave[3],dvel[3];
- float pa_minmax[6];
- float min_w[4], zerovec[3]={0.0,0.0,0.0}, ipoint[3];
- float min_d,dotprod,damp,frict,o_len,d_len,radius=-1.0f;
- int min_face=0, intersect=1, through=0;
- short deflections=0, global=0;
+ ParticleKey reaction_state;
+ ParticleCollision col;
+ BVHTreeRayHit hit;
+ float ray_dir[3], zerovec[3]={0.0,0.0,0.0};
+ float radius = ((part->flag & PART_SIZE_DEFL)?pa->size:0.0f);
+ int deflections=0, max_deflections=10;
- VECCOPY(def_loc,pa->state.co);
- VECCOPY(def_vel,pa->state.vel);
+ VECCOPY(col.co1, pa->prev_state.co);
+ VECCOPY(col.co2, pa->state.co);
+ col.t = 0.0f;
/* 10 iterations to catch multiple deflections */
- if(lb->first) while(deflections<10){
- intersect=0;
- global=0;
- min_d=20000.0;
- min_ob=NULL;
+ if(lb->first) while(deflections < max_deflections){
/* 1. */
+
+ VECSUB(ray_dir, col.co2, col.co1);
+ hit.index = -1;
+ hit.dist = col.ray_len = VecLength(ray_dir);
+
+ /* even if particle is stationary we want to check for moving colliders */
+ /* if hit.dist is zero the bvhtree_ray_cast will just ignore everything */
+ if(hit.dist == 0.0f)
+ hit.dist = col.ray_len = 0.000001f;
+
for(ec=lb->first; ec; ec=ec->next){
if(ec->type & PSYS_EC_DEFLECT){
ob= ec->ob;
@@ -3070,256 +3089,168 @@ static void deflect_particle(Object *pob, ParticleSystemModifierData *psmd, Part
if(part->type!=PART_HAIR)
where_is_object_time(ob,cfra);
- if(ob==pob){
- dm=psmd->dm;
- /* particles should not collide with emitter at birth */
- if(pa->time < cfra && pa->time >= psys->cfra)
- continue;
- }
- else
- dm=0;
-
- VECCOPY(co1,def_loc);
- VECCOPY(co2,state->co);
-
- if(ec->vert_cos==0){
- /* convert particle coordinates to object coordinates */
- Mat4Invert(imat,ob->obmat);
-
- Mat4MulVecfl(imat,co1);
- Mat4MulVecfl(imat,co2);
- }
+ /* particles should not collide with emitter at birth */
+ if(ob==pob && pa->time < cfra && pa->time >= psys->cfra)
+ continue;
- INIT_MINMAX(pa_minmax,pa_minmax+3);
- DO_MINMAX(co1,pa_minmax,pa_minmax+3);
- DO_MINMAX(co2,pa_minmax,pa_minmax+3);
- if(part->flag&PART_SIZE_DEFL){
- pa_minmax[0]-=pa->size;
- pa_minmax[1]-=pa->size;
- pa_minmax[2]-=pa->size;
- pa_minmax[3]+=pa->size;
- pa_minmax[4]+=pa->size;
- pa_minmax[5]+=pa->size;
-
- radius=pa->size;
- }
+ col.md = ( CollisionModifierData * ) ( modifiers_findByType ( ec->ob, eModifierType_Collision ) );
+ col.ob_t = ob;
- if(ec->face_minmax==0 || AabbIntersectAabb(pa_minmax,pa_minmax+3,ec->ob_minmax,ec->ob_minmax+3))
- if(psys_intersect_dm(ob,dm,ec->vert_cos,co1,co2,&min_d,&min_face,min_w,
- ec->face_minmax,pa_minmax,radius,ipoint)){
- min_ob=ob;
- if(ec->vert_cos)
- global=1;
- else
- global=0;
- }
+ if(col.md && col.md->bvhtree)
+ BLI_bvhtree_ray_cast(col.md->bvhtree, col.co1, ray_dir, radius, &hit, particle_intersect_face, &col);
}
}
/* 2. */
- if(min_ob){
- BLI_srandom((int)cfra+p);
- ob=min_ob;
-
- if(ob==pob){
- dm=psmd->dm;
- }
- else{
- psys_disable_all(ob);
-
- dm=mesh_get_derived_final(ob,0);
-
- psys_enable_all(ob);
- }
-
- mface=dm->getFaceDataArray(dm,CD_MFACE);
- mface+=min_face;
- mvert=dm->getVertDataArray(dm,CD_MVERT);
-
-
- /* permeability check */
- if(BLI_frand()<ob->pd->pdef_perm)
- through=1;
- else
- through=0;
-
- if(through==0 && (part->flag & PART_DIE_ON_COL || ob->pd->flag & PDEFLE_KILL_PART)){
- pa->dietime = cfra-(1.0f-min_d)*dfra;
- VecLerpf(def_loc,co1,co2,min_d);
-
- if(global==0)
- Mat4MulVecfl(ob->obmat,def_loc);
-
- VECCOPY(state->co,def_loc);
- VecLerpf(state->vel,pa->state.vel,state->vel,min_d);
- QuatInterpol(state->rot,pa->state.rot,state->rot,min_d);
- VecLerpf(state->ave,pa->state.ave,state->ave,min_d);
+ if(hit.index>=0) {
+ PartDeflect *pd = col.ob->pd;
+ int through = (BLI_frand() < pd->pdef_perm) ? 1 : 0;
+ float co[3]; /* point of collision */
+ float vec[3]; /* movement through collision */
+ float t = hit.dist/col.ray_len; /* time of collision between this iteration */
+ float dt = col.t + t * (1.0f - col.t); /* time of collision between frame change*/
+
+ VecLerpf(co, col.co1, col.co2, t);
+ VECSUB(vec, col.co2, col.co1);
+
+ VecMulf(col.vel, 1.0f-col.t);
+
+ /* particle dies in collision */
+ if(through == 0 && (part->flag & PART_DIE_ON_COL || pd->flag & PDEFLE_KILL_PART)) {
+ pa->alive = PARS_DYING;
+ pa->dietime = pa->state.time + (cfra - pa->state.time) * dt;
+
+ /* we have to add this for dying particles too so that reactors work correctly */
+ VECADDFAC(co, co, col.nor, (through ? -0.0001f : 0.0001f));
- *pa_die=1;
+ VECCOPY(pa->state.co, co);
+ VecLerpf(pa->state.vel, pa->prev_state.vel, pa->state.vel, dt);
+ QuatInterpol(pa->state.rot, pa->prev_state.rot, pa->state.rot, dt);
+ VecLerpf(pa->state.ave, pa->prev_state.ave, pa->state.ave, dt);
/* particle is dead so we don't need to calculate further */
- deflections=10;
+ deflections=max_deflections;
/* store for reactors */
- copy_particle_key(&cstate,state,0);
+ copy_particle_key(&reaction_state,&pa->state,0);
if(part->flag & PART_STICKY){
pa->stick_ob=ob;
pa->flag |= PARS_STICKY;
- //stick_particle_to_object(ob,pa,state);
}
}
- else{
- VecLerpf(def_loc,co1,co2,min_d);
-
- if(radius>0.0f){
- VECSUB(unit_nor,def_loc,ipoint);
- }
- else{
- /* get deflection point & normal */
- psys_interpolate_face(mvert,mface,0,0,min_w,ipoint,unit_nor,0,0,0,0);
- if(global){
- Mat4Mul3Vecfl(ob->obmat,unit_nor);
- Mat4MulVecfl(ob->obmat,ipoint);
- }
- }
-
- Normalize(unit_nor);
-
- VECSUB(dvec,co1,co2);
- /* scale to remaining length after deflection */
- VecMulf(dvec,1.0f-min_d);
+ else {
+ float nor_vec[3], tan_vec[3], tan_vel[3], vel[3];
+ float damp, frict;
+ float inp, inp_v;
+
+ /* get damping & friction factors */
+ damp = pd->pdef_damp + pd->pdef_rdamp * 2 * (BLI_frand() - 0.5f);
+ CLAMP(damp,0.0,1.0);
- /* flip normal to face particle */
- if(Inpf(unit_nor,dvec)<0.0f)
- VecMulf(unit_nor,-1.0f);
+ frict = pd->pdef_frict + pd->pdef_rfrict * 2 * (BLI_frand() - 0.5f);
+ CLAMP(frict,0.0,1.0);
- /* store for easy velocity calculation */
- o_len=VecLength(dvec);
+ /* treat normal & tangent components separately */
+ inp = Inpf(col.nor, vec);
+ inp_v = Inpf(col.nor, col.vel);
- /* project particle movement to normal & create tangent */
- dotprod=Inpf(dvec,unit_nor);
- VECCOPY(def_nor,unit_nor);
- VecMulf(def_nor,dotprod);
- VECSUB(def_tan,def_nor,dvec);
+ VECADDFAC(tan_vec, vec, col.nor, -inp);
+ VECADDFAC(tan_vel, col.vel, col.nor, -inp_v);
+ if((part->flag & PART_ROT_DYN)==0)
+ VecLerpf(tan_vec, tan_vec, tan_vel, frict);
- damp=ob->pd->pdef_damp+ob->pd->pdef_rdamp*2*(BLI_frand()-0.5f);
+ VECCOPY(nor_vec, col.nor);
+ inp *= 1.0f - damp;
- /* create location after deflection */
- VECCOPY(dvec,def_nor);
- damp=ob->pd->pdef_damp+ob->pd->pdef_rdamp*2*(BLI_frand()-0.5f);
- CLAMP(damp,0.0,1.0);
- VecMulf(dvec,1.0f-damp);
if(through)
- VecMulf(dvec,-1.0);
-
- frict=ob->pd->pdef_frict+ob->pd->pdef_rfrict*2.0f*(BLI_frand()-0.5f);
- CLAMP(frict,0.0,1.0);
- VECADDFAC(dvec,dvec,def_tan,1.0f-frict);
+ inp_v *= damp;
- /* store for easy velocity calculation */
- d_len=VecLength(dvec);
+ /* special case for object hitting the particle from behind */
+ if(through==0 && ((inp_v>0 && inp>0 && inp_v>inp) || (inp_v<0 && inp<0 && inp_v<inp)))
+ VecMulf(nor_vec, inp_v);
+ else
+ VecMulf(nor_vec, inp_v + (through ? 1.0f : -1.0f) * inp);
- /* just to be sure we don't hit the current face again */
- if(through){
- VECADDFAC(ipoint,ipoint,unit_nor,-0.0001f);
- VECADDFAC(def_loc,def_loc,unit_nor,-0.0001f);
+ /* angular <-> linear velocity - slightly more physical and looks even nicer than before */
+ if(part->flag & PART_ROT_DYN) {
+ float surface_vel[3], rot_vel[3], friction[3], dave[3], dvel[3];
- if(part->flag & PART_ROT_DYN){
- VECADDFAC(def_tan,def_tan,unit_nor,-0.0001f);
- VECADDFAC(def_nor,def_nor,unit_nor,-0.0001f);
- }
- }
- else{
- VECADDFAC(ipoint,ipoint,unit_nor,0.0001f);
- VECADDFAC(def_loc,def_loc,unit_nor,0.0001f);
+ /* apparent velocity along collision surface */
+ VECSUB(surface_vel, tan_vec, tan_vel);
- if(part->flag & PART_ROT_DYN){
- VECADDFAC(def_tan,def_tan,unit_nor,0.0001f);
- VECADDFAC(def_nor,def_nor,unit_nor,0.0001f);
- }
- }
+ /* direction of rolling friction */
+ Crossf(rot_vel, pa->state.ave, col.nor);
+ /* convert to current dt */
+ VecMulf(rot_vel, (timestep*dfra) * (1.0f - col.t));
+ VecMulf(rot_vel, pa->size);
- /* lets get back to global space */
- if(global==0){
- Mat4Mul3Vecfl(ob->obmat,dvec);
- Mat4MulVecfl(ob->obmat,ipoint);
- Mat4MulVecfl(ob->obmat,def_loc);/* def_loc remains as intersection point for next iteration */
- }
+ /* apply sliding friction */
+ VECSUB(surface_vel, surface_vel, rot_vel);
+ VECCOPY(friction, surface_vel);
- /* store for reactors */
- VECCOPY(cstate.co,ipoint);
- VecLerpf(cstate.vel,pa->state.vel,state->vel,min_d);
- QuatInterpol(cstate.rot,pa->state.rot,state->rot,min_d);
-
- /* slightly unphysical but looks nice enough */
- if(part->flag & PART_ROT_DYN){
- if(global==0){
- Mat4Mul3Vecfl(ob->obmat,def_nor);
- Mat4Mul3Vecfl(ob->obmat,def_tan);
- }
+ VecMulf(surface_vel, 1.0 - frict);
+ VecMulf(friction, frict);
- Normalize(def_tan);
- Normalize(def_nor);
- VECCOPY(unit_nor,def_nor);
+ /* sliding changes angular velocity */
+ Crossf(dave, col.nor, friction);
+ VecMulf(dave, 1.0f/MAX2(pa->size, 0.001));
- /* create normal velocity */
- VecMulf(def_nor,Inpf(pa->state.vel,def_nor));
+ /* we assume rolling friction is around 0.01 of sliding friction */
+ VecMulf(rot_vel, 1.0 - frict*0.01);
- /* create tangential velocity */
- VecMulf(def_tan,Inpf(pa->state.vel,def_tan));
-
- /* angular velocity change due to tangential velocity */
- Crossf(dave,unit_nor,def_tan);
- VecMulf(dave,1.0f/pa->size);
-
- /* linear velocity change due to angular velocity */
- VecMulf(unit_nor,pa->size); /* point of impact from particle center */
- Crossf(dvel,pa->state.ave,unit_nor);
+ /* change in angular velocity has to be added to the linear velocity too */
+ Crossf(dvel, dave, col.nor);
+ VecMulf(dvel, pa->size);
+ VECADD(rot_vel, rot_vel, dvel);
- if(through)
- VecMulf(def_nor,-1.0);
+ VECADD(surface_vel, surface_vel, rot_vel);
+ VECADD(tan_vec, surface_vel, tan_vel);
- VecMulf(def_nor,1.0f-damp);
- VECSUB(dvel,dvel,def_nor);
+ /* convert back to normal time */
+ VecMulf(dave, 1.0f/MAX2((timestep*dfra) * (1.0f - col.t), 0.00001));
- VecMulf(dvel,1.0f-frict);
- VecMulf(dave,1.0f-frict);
+ VecMulf(pa->state.ave, 1.0 - frict*0.01);
+ VECADD(pa->state.ave, pa->state.ave, dave);
}
-
- if(d_len<0.001 && VecLength(pa->state.vel)<0.001){
- /* kill speed to stop slipping */
- VECCOPY(state->vel,zerovec);
- VECCOPY(state->co,def_loc);
- if(part->flag & PART_ROT_DYN)
- VECCOPY(state->ave,zerovec);
- deflections=10;
- }
- else{
- /* apply new coordinates */
- VECADD(state->co,def_loc,dvec);
+ /* combine components together again */
+ VECADD(vec, nor_vec, tan_vec);
+
+ /* calculate velocity from collision vector */
+ VECCOPY(vel, vec);
+ VecMulf(vel, 1.0f/MAX2((timestep*dfra) * (1.0f - col.t), 0.00001));
- Normalize(dvec);
+ /* make sure we don't hit the current face again */
+ VECADDFAC(co, co, col.nor, (through ? -0.0001f : 0.0001f));
- /* we have to use original velocity because otherwise we get slipping */
- /* when forces like gravity balance out damping & friction */
- VecMulf(dvec,VecLength(pa->state.vel)*(d_len/o_len));
- VECCOPY(state->vel,dvec);
+ /* store state for reactors */
+ VECCOPY(reaction_state.co, co);
+ VecLerpf(reaction_state.vel, pa->prev_state.vel, pa->state.vel, dt);
+ QuatInterpol(reaction_state.rot, pa->prev_state.rot, pa->state.rot, dt);
- if(part->flag & PART_ROT_DYN){
- VECADD(state->vel,state->vel,dvel);
- VecMulf(state->vel,0.5);
- VECADD(state->ave,state->ave,dave);
- VecMulf(state->ave,0.5);
+ /* set coordinates for next iteration */
+ VECCOPY(col.co1, co);
+ VECADDFAC(col.co2, co, vec, 1.0f - t);
+ col.t = dt;
+
+ if(VecLength(vec) < 0.001 && VecLength(pa->state.vel) < 0.001) {
+ /* kill speed to stop slipping */
+ VECCOPY(pa->state.vel,zerovec);
+ VECCOPY(pa->state.co, co);
+ if(part->flag & PART_ROT_DYN) {
+ VECCOPY(pa->state.ave,zerovec);
}
}
+ else {
+ VECCOPY(pa->state.co, col.co2);
+ VECCOPY(pa->state.vel, vel);
+ }
}
deflections++;
- cstate.time=cfra-(1.0f-min_d)*dfra;
- //particle_react_to_collision(min_ob,pob,psys,pa,p,&cstate);
- push_reaction(pob,psys,p,PART_EVENT_COLLIDE,&cstate);
+ reaction_state.time = cfra - (1.0f - dt) * dfra;
+ push_reaction(col.ob, psys, p, PART_EVENT_COLLIDE, &reaction_state);
}
else
return;
@@ -3380,7 +3311,9 @@ static int boid_see_mesh(ListBase *lb, Object *pob, ParticleSystem *psys, float
else{
psys_disable_all(ob);
- dm=mesh_get_derived_deform(ob,0);
+ dm=mesh_get_derived_final(ob,0);
+ if(dm==0)
+ dm=mesh_get_derived_deform(ob,0);
psys_enable_all(ob);
}
@@ -3483,7 +3416,7 @@ static int add_boid_acc(BoidVecFunc *bvf, float lat_max, float tan_max, float *l
}
}
/* determines the acceleration that the boid tries to acchieve */
-static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleSystem *psys, ParticleSettings *part, KDTree *tree, float timestep, float cfra, float *acc, int *pa_die)
+static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleSystem *psys, ParticleSettings *part, KDTree *tree, float timestep, float cfra, float *acc)
{
ParticleData *pars=psys->particles;
KDTreeNearest ptn[MAX_BOIDNEIGHBOURS+1];
@@ -3514,18 +3447,18 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
switch(part->boidrule[i]){
case BOID_COLLIDE:
/* collision avoidance */
- bvf->Copyf(dvec,pa->state.vel);
+ bvf->Copyf(dvec,pa->prev_state.vel);
bvf->Mulf(dvec,5.0f);
- bvf->Addf(dvec,dvec,pa->state.co);
- if(boid_see_mesh(&psys->effectors,ob,psys,pa->state.co,dvec,ob_co,ob_nor,cfra)){
+ bvf->Addf(dvec,dvec,pa->prev_state.co);
+ if(boid_see_mesh(&psys->effectors,ob,psys,pa->prev_state.co,dvec,ob_co,ob_nor,cfra)){
float probelen = bvf->Length(dvec);
float proj;
float oblen;
Normalize(ob_nor);
- proj = bvf->Inpf(ob_nor,pa->state.vel);
+ proj = bvf->Inpf(ob_nor,pa->prev_state.vel);
- bvf->Subf(dvec,pa->state.co,ob_co);
+ bvf->Subf(dvec,pa->prev_state.co,ob_co);
oblen=bvf->Length(dvec);
bvf->Copyf(dvec,ob_nor);
@@ -3545,12 +3478,12 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
if(pd->forcefield==PFIELD_FORCE && pd->f_strength<0.0){
float distance;
- VECSUB(dvec,eob->obmat[3],pa->state.co);
+ VECSUB(dvec,eob->obmat[3],pa->prev_state.co);
distance=Normalize(dvec);
if(part->flag & PART_DIE_ON_COL && distance < pd->mindist){
- *pa_die=1;
+ pa->alive = PARS_DYING;
pa->dietime=cfra;
i=BOID_TOT_RULES;
break;
@@ -3579,17 +3512,17 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
pd= epart->pd;
totepart= epsys->totpart;
- if(pd->forcefield==PFIELD_FORCE && pd->f_strength<0.0){
- count=BLI_kdtree_find_n_nearest(ec->tree,epart->boidneighbours,pa->state.co,NULL,ptn2);
+ if(pd->forcefield==PFIELD_FORCE && pd->f_strength<0.0 && ec->tree){
+ count=BLI_kdtree_find_n_nearest(ec->tree,epart->boidneighbours,pa->prev_state.co,NULL,ptn2);
for(p=0; p<count; p++){
state.time=-1.0;
if(psys_get_particle_state(eob,epsys,ptn2[p].index,&state,0)){
- VECSUB(dvec, state.co, pa->state.co);
+ VECSUB(dvec, state.co, pa->prev_state.co);
distance = Normalize(dvec);
if(part->flag & PART_DIE_ON_COL && distance < (epsys->particles+ptn2[p].index)->size){
- *pa_die=1;
+ pa->alive = PARS_DYING;
pa->dietime=cfra;
i=BOID_TOT_RULES;
break;
@@ -3614,10 +3547,12 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
near=0;
for(n=1; n<neighbours; n++){
if(ptn[n].dist<2.0f*pa->size){
- bvf->Subf(dvec,pa->state.co,pars[ptn[n].index].state.co);
- bvf->Mulf(dvec,(2.0f*pa->size-ptn[n].dist)/ptn[n].dist);
- bvf->Addf(avoid,avoid,dvec);
- near++;
+ if(ptn[n].dist!=0.0f) {
+ bvf->Subf(dvec,pa->prev_state.co,pars[ptn[n].index].state.co);
+ bvf->Mulf(dvec,(2.0f*pa->size-ptn[n].dist)/ptn[n].dist);
+ bvf->Addf(avoid,avoid,dvec);
+ near++;
+ }
}
/* ptn[] is distance ordered so no need to check others */
else break;
@@ -3636,7 +3571,7 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
}
bvf->Mulf(center,1.0f/((float)neighbours-1.0f));
- bvf->Subf(dvec,center,pa->state.co);
+ bvf->Subf(dvec,center,pa->prev_state.co);
bvf->Mulf(dvec,part->boidfac[BOID_CENTER]*2.0f);
@@ -3645,9 +3580,9 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
break;
case BOID_AV_VEL:
/* average velocity */
- cur_vel=bvf->Length(pa->state.vel);
+ cur_vel=bvf->Length(pa->prev_state.vel);
if(cur_vel>0.0){
- bvf->Copyf(dvec,pa->state.vel);
+ bvf->Copyf(dvec,pa->prev_state.vel);
bvf->Mulf(dvec,part->boidfac[BOID_AV_VEL]*(avg_vel-cur_vel)/cur_vel);
not_finished=add_boid_acc(bvf,max_lat_acc,max_tan_acc,&lat_accu,&tan_accu,acc,dvec,0);
}
@@ -3662,7 +3597,7 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
}
bvf->Mulf(velocity,1.0f/((float)neighbours-1.0f));
- bvf->Subf(dvec,velocity,pa->state.vel);
+ bvf->Subf(dvec,velocity,pa->prev_state.vel);
bvf->Mulf(dvec,part->boidfac[BOID_VEL_MATCH]);
@@ -3680,7 +3615,7 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
if(pd->forcefield==PFIELD_FORCE && pd->f_strength>0.0){
float distance;
- VECSUB(dvec,eob->obmat[3],pa->state.co);
+ VECSUB(dvec,eob->obmat[3],pa->prev_state.co);
distance=Normalize(dvec);
@@ -3697,7 +3632,7 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
where_on_path(eob, (cfra-pa->time)/pa->lifetime, temp, dvec);
- VECSUB(dvec,temp,pa->state.co);
+ VECSUB(dvec,temp,pa->prev_state.co);
distance=Normalize(dvec);
@@ -3724,12 +3659,12 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
pd= epart->pd;
totepart= epsys->totpart;
- if(pd->forcefield==PFIELD_FORCE && pd->f_strength>0.0){
- count=BLI_kdtree_find_n_nearest(ec->tree,epart->boidneighbours,pa->state.co,NULL,ptn2);
+ if(pd->forcefield==PFIELD_FORCE && pd->f_strength>0.0 && ec->tree){
+ count=BLI_kdtree_find_n_nearest(ec->tree,epart->boidneighbours,pa->prev_state.co,NULL,ptn2);
for(p=0; p<count; p++){
state.time=-1.0;
if(psys_get_particle_state(eob,epsys,ptn2[p].index,&state,0)){
- VECSUB(dvec, state.co, pa->state.co);
+ VECSUB(dvec, state.co, pa->prev_state.co);
distance = Normalize(dvec);
@@ -3751,7 +3686,7 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
/* level flight */
if((part->flag & PART_BOIDS_2D)==0){
dvec[0]=dvec[1]=0.0;
- dvec[2]=-pa->state.vel[2];
+ dvec[2]=-pa->prev_state.vel[2];
VecMulf(dvec,part->boidfac[BOID_LEVEL]);
not_finished=add_boid_acc(bvf,max_lat_acc,max_tan_acc,&lat_accu,&tan_accu,acc,dvec,0);
@@ -3761,15 +3696,15 @@ static void boid_brain(BoidVecFunc *bvf, ParticleData *pa, Object *ob, ParticleS
}
}
/* tries to realize the wanted acceleration */
-static void boid_body(BoidVecFunc *bvf, ParticleData *pa, ParticleSystem *psys, ParticleSettings *part, float timestep, float *acc, ParticleKey *state)
+static void boid_body(BoidVecFunc *bvf, ParticleData *pa, ParticleSystem *psys, ParticleSettings *part, float timestep, float *acc)
{
float dvec[3], bvec[3], length, max_vel=part->max_vel;
- float *q2, q[4];
+ float q2[4], q[4];
float g=9.81f, pa_mass=part->mass;
float yvec[3]={0.0,1.0,0.0}, zvec[3]={0.0,0.0,-1.0}, bank;
/* apply new velocity, location & rotation */
- copy_particle_key(state,&pa->state,0);
+ copy_particle_key(&pa->state,&pa->prev_state,0);
if(part->flag & PART_SIZEMASS)
pa_mass*=pa->size;
@@ -3781,32 +3716,49 @@ static void boid_body(BoidVecFunc *bvf, ParticleData *pa, ParticleSystem *psys,
bvf->Copyf(dvec,acc);
bvf->Mulf(dvec,timestep*timestep*0.5f);
- bvf->Copyf(bvec,state->vel);
+ bvf->Copyf(bvec,pa->state.vel);
bvf->Mulf(bvec,timestep);
bvf->Addf(dvec,dvec,bvec);
- bvf->Addf(state->co,state->co,dvec);
+ bvf->Addf(pa->state.co,pa->state.co,dvec);
- /* air speed from wind effectors */
- if(psys->effectors.first){
+ /* air speed from wind and vortex effectors */
+ if(psys->effectors.first) {
ParticleEffectorCache *ec;
- for(ec=psys->effectors.first; ec; ec=ec->next){
- if(ec->type & PSYS_EC_EFFECTOR){
+ for(ec=psys->effectors.first; ec; ec=ec->next) {
+ if(ec->type & PSYS_EC_EFFECTOR) {
Object *eob = ec->ob;
PartDeflect *pd = eob->pd;
+ float direction[3], vec_to_part[3];
+ float falloff;
+
+ if(pd->f_strength != 0.0f) {
+ VecCopyf(direction, eob->obmat[2]);
+ VecSubf(vec_to_part, pa->state.co, eob->obmat[3]);
+
+ falloff=effector_falloff(pd, direction, vec_to_part);
+
+ switch(pd->forcefield) {
+ case PFIELD_WIND:
+ if(falloff <= 0.0f)
+ ; /* don't do anything */
+ else {
+ Normalize(direction);
+ VecMulf(direction, pd->f_strength * falloff);
+ bvf->Addf(pa->state.co, pa->state.co, direction);
+ }
+ break;
+ case PFIELD_VORTEX:
+ {
+ float distance, mag_vec[3];
+ Crossf(mag_vec, direction, vec_to_part);
+ Normalize(mag_vec);
- if(pd->forcefield==PFIELD_WIND && pd->f_strength!=0.0){
- float distance, wind[3];
- VecCopyf(wind,eob->obmat[2]);
- distance=VecLenf(state->co,eob->obmat[3]);
-
- if (distance < 0.001) distance = 0.001f;
+ distance = VecLength(vec_to_part);
- if(pd->flag&PFIELD_USEMAX && distance > pd->maxdist)
- ;
- else{
- Normalize(wind);
- VecMulf(wind,pd->f_strength/(float)pow((double)distance,(double)pd->f_power));
- bvf->Addf(state->co,state->co,wind);
+ VecMulf(mag_vec, pd->f_strength * distance * falloff);
+ bvf->Addf(pa->state.co, pa->state.co, mag_vec);
+ break;
+ }
}
}
}
@@ -3814,8 +3766,8 @@ static void boid_body(BoidVecFunc *bvf, ParticleData *pa, ParticleSystem *psys,
}
- if((part->flag & PART_BOIDS_2D)==0 && pa->state.vel[0]!=0.0 && pa->state.vel[0]!=0.0 && pa->state.vel[0]!=0.0){
- Crossf(yvec,state->vel,zvec);
+ if((part->flag & PART_BOIDS_2D)==0 && pa->prev_state.vel[0]!=0.0 && pa->prev_state.vel[0]!=0.0 && pa->prev_state.vel[0]!=0.0){
+ Crossf(yvec,pa->state.vel,zvec);
Normalize(yvec);
@@ -3842,27 +3794,27 @@ static void boid_body(BoidVecFunc *bvf, ParticleData *pa, ParticleSystem *psys,
}
- VecRotToQuat(state->vel,bank,q);
+ VecRotToQuat(pa->state.vel,bank,q);
- VECCOPY(dvec,state->vel);
+ VECCOPY(dvec,pa->state.vel);
VecMulf(dvec,-1.0f);
- q2= vectoquat(dvec, OB_POSX, OB_POSZ);
+ vectoquat(dvec, OB_POSX, OB_POSZ, q2);
- QuatMul(state->rot,q,q2);
+ QuatMul(pa->state.rot,q,q2);
bvf->Mulf(acc,timestep);
- bvf->Addf(state->vel,state->vel,acc);
+ bvf->Addf(pa->state.vel,pa->state.vel,acc);
if(part->flag & PART_BOIDS_2D){
- state->vel[2]=0.0;
- state->co[2]=part->groundz;
+ pa->state.vel[2]=0.0;
+ pa->state.co[2]=part->groundz;
- if(psys->keyed_ob){
+ if(psys->keyed_ob && (psys->keyed_ob->type == OB_MESH)){
Object *zob=psys->keyed_ob;
int min_face;
float co1[3],co2[3],min_d=2.0,min_w[4],imat[4][4];
- VECCOPY(co1,state->co);
- VECCOPY(co2,state->co);
+ VECCOPY(co1,pa->state.co);
+ VECCOPY(co2,pa->state.co);
co1[2]=1000.0f;
co2[2]=-1000.0f;
@@ -3893,7 +3845,7 @@ static void boid_body(BoidVecFunc *bvf, ParticleData *pa, ParticleSystem *psys,
Normalize(nor);
- VECCOPY(state->co,loc);
+ VECCOPY(pa->state.co,loc);
zvec[2]=1.0;
@@ -3905,22 +3857,22 @@ static void boid_body(BoidVecFunc *bvf, ParticleData *pa, ParticleSystem *psys,
VecRotToQuat(loc,bank,q);
- QUATCOPY(q1,state->rot);
+ QUATCOPY(q1,pa->state.rot);
- QuatMul(state->rot,q,q1);
+ QuatMul(pa->state.rot,q,q1);
}
}
}
}
- length=bvf->Length(state->vel);
+ length=bvf->Length(pa->state.vel);
if(length > max_vel)
- bvf->Mulf(state->vel,max_vel/length);
+ bvf->Mulf(pa->state.vel,max_vel/length);
}
/************************************************/
/* Hair */
/************************************************/
-void save_hair(Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd, float cfra){
+static void save_hair(Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd, float cfra){
ParticleData *pa;
HairKey *key;
int totpart;
@@ -3972,14 +3924,13 @@ static void dynamics_step(Object *ob, ParticleSystem *psys, ParticleSystemModifi
float *vg_vel, float *vg_tan, float *vg_rot, float *vg_size)
{
ParticleData *pa;
- ParticleKey *outstate, *key;
ParticleSettings *part=psys->part;
KDTree *tree=0;
BoidVecFunc bvf;
IpoCurve *icu_esize=find_ipocurve(part->ipo,PART_EMIT_SIZE);
Material *ma=give_current_material(ob,part->omat);
float timestep;
- int p, totpart, pa_die;
+ int p, totpart;
/* current time */
float ctime, ipotime;
/* frame & time changes */
@@ -4007,7 +3958,7 @@ static void dynamics_step(Object *ob, ParticleSystem *psys, ParticleSystemModifi
vg_size=psys_cache_vgroup(psmd->dm,psys,PSYS_VG_SIZE);
for(p=0, pa=psys->particles; p<totpart; p++,pa++){
- if(pa->flag & (PARS_NO_DISP+PARS_UNEXIST)) continue;
+ if(pa->flag & PARS_UNEXIST) continue;
/* set correct ipo timing */
if((part->flag&PART_ABS_TIME)==0 && part->ipo){
@@ -4017,36 +3968,31 @@ static void dynamics_step(Object *ob, ParticleSystem *psys, ParticleSystemModifi
}
pa->size=psys_get_size(ob,ma,psmd,icu_esize,psys,part,pa,vg_size);
- if(part->type==PART_REACTOR)
- initialize_particle(pa,p,ob,psys,psmd);
-
reset_particle(pa,psys,psmd,ob,dtime,cfra,vg_vel,vg_tan,vg_rot);
- if(cfra>pa->time && part->flag & PART_LOOP && (part->flag & PART_LOOP_INSTANT)==0){
- pa->loop=(short)((cfra-pa->time)/pa->lifetime)+1;
+ if(cfra>pa->time && part->flag & PART_LOOP && part->type!=PART_HAIR){
+ pa->loop=(short)((cfra-pa->time)/pa->lifetime);
pa->alive=PARS_UNBORN;
}
else{
- pa->loop=0;
- if(cfra<=pa->time)
- pa->alive=PARS_UNBORN;
+ pa->loop = 0;
+ if(cfra <= pa->time)
+ pa->alive = PARS_UNBORN;
/* without dynamics the state is allways known so no need to kill */
- else if(ELEM(part->phystype,PART_PHYS_NO,PART_PHYS_KEYED)==0)
- pa->alive=PARS_KILLED;
+ else if(ELEM(part->phystype, PART_PHYS_NO, PART_PHYS_KEYED)){
+ if(cfra < pa->dietime)
+ pa->alive = PARS_ALIVE;
+ }
+ else
+ pa->alive = PARS_KILLED;
}
}
if(vg_size)
MEM_freeN(vg_size);
-
- //if(part->phystype==PART_PHYS_SOLID)
- // reset_to_first_fragment(psys);
}
else{
BLI_srandom(31415926 + (int)cfra + psys->seed);
-
- /* outstate is used so that particles are updated in parallel */
- outstate=MEM_callocN(totpart*sizeof(ParticleKey),"Particle Outstates");
/* update effectors */
if(psys->effectors.first)
@@ -4055,7 +4001,7 @@ static void dynamics_step(Object *ob, ParticleSystem *psys, ParticleSystemModifi
psys_init_effectors(ob,part->eff_group,psys);
if(psys->effectors.first)
- precalc_effectors(ob,psys,psmd);
+ precalc_effectors(ob,psys,psmd,cfra);
if(part->phystype==PART_PHYS_BOIDS){
/* create particle tree for fast inter-particle comparisons */
@@ -4071,10 +4017,10 @@ static void dynamics_step(Object *ob, ParticleSystem *psys, ParticleSystemModifi
}
/* main loop: calculate physics for all particles */
- for(p=0, pa=psys->particles, key=outstate; p<totpart; p++,pa++,key++){
- if(pa->flag & (PARS_NO_DISP|PARS_UNEXIST)) continue;
+ for(p=0, pa=psys->particles; p<totpart; p++,pa++){
+ if(pa->flag & PARS_UNEXIST) continue;
- copy_particle_key(key,&pa->state,1);
+ copy_particle_key(&pa->prev_state,&pa->state,1);
/* set correct ipo timing */
if((part->flag&PART_ABS_TIME)==0 && part->ipo){
@@ -4084,104 +4030,85 @@ static void dynamics_step(Object *ob, ParticleSystem *psys, ParticleSystemModifi
}
pa->size=psys_get_size(ob,ma,psmd,icu_esize,psys,part,pa,vg_size);
- pa_die=0;
+ /* reactions can change birth time so they need to be checked first */
+ if(psys->reactevents.first && ELEM(pa->alive,PARS_DEAD,PARS_KILLED)==0)
+ react_to_events(psys,p);
+
+ birthtime = pa->time + pa->loop * pa->lifetime;
+ dietime = birthtime + pa->lifetime;
- if(pa->alive==PARS_UNBORN || pa->alive==PARS_KILLED || ELEM(part->phystype,PART_PHYS_NO,PART_PHYS_KEYED)){
- /* allways reset particles to emitter before birth */
+ /* allways reset particles to emitter before birth */
+ if(pa->alive==PARS_UNBORN
+ || pa->alive==PARS_KILLED
+ || ELEM(part->phystype,PART_PHYS_NO,PART_PHYS_KEYED)
+ || birthtime >= cfra){
reset_particle(pa,psys,psmd,ob,dtime,cfra,vg_vel,vg_tan,vg_rot);
- copy_particle_key(key,&pa->state,1);
}
- if(dfra>0.0 || psys->recalc){
-
- if(psys->reactevents.first && ELEM(pa->alive,PARS_DEAD,PARS_KILLED)==0)
- react_to_events(psys,p);
+ pa_dfra = dfra;
+ pa_dtime = dtime;
- pa_dfra= dfra;
- pa_dtime= dtime;
+ if(birthtime <= cfra && birthtime >= psys->cfra){
+ /* particle is born some time between this and last step*/
+ pa->alive = PARS_ALIVE;
+ pa_dfra = cfra - birthtime;
+ pa_dtime = pa_dfra*timestep;
+ }
+ else if(dietime <= cfra && psys->cfra < dietime){
+ /* particle dies some time between this and last step */
+ pa_dfra = dietime - psys->cfra;
+ pa_dtime = pa_dfra * timestep;
+ pa->alive = PARS_DYING;
+ }
+ else if(dietime < cfra){
+ /* nothing to be done when particle is dead */
+ }
- if(pa->flag & PART_LOOP && pa->flag & PART_LOOP_INSTANT)
- birthtime=pa->dietime;
- else
- birthtime=pa->time+pa->loop*pa->lifetime;
- dietime=birthtime+pa->lifetime;
+ if(dfra>0.0 && ELEM(pa->alive,PARS_ALIVE,PARS_DYING)){
+ switch(part->phystype){
+ case PART_PHYS_NEWTON:
+ /* do global forces & effectors */
+ apply_particle_forces(p,pa,ob,psys,part,timestep,pa_dfra,cfra);
+
+ /* deflection */
+ deflect_particle(ob,psmd,psys,part,pa,p,timestep,pa_dfra,cfra);
- if(birthtime < cfra && birthtime >= psys->cfra){
- /* particle is born some time between this and last step*/
- pa->alive=PARS_ALIVE;
- pa_dfra= cfra - birthtime;
- pa_dtime= pa_dfra*timestep;
- }
- else if(dietime <= cfra && psys->cfra < dietime){
- /* particle dies some time between this and last step */
- pa_dfra= dietime - psys->cfra;
- pa_dtime= pa_dfra*timestep;
- pa_die=1;
- }
- else if(dietime < cfra){
- /* TODO: figure out if there's something to be done when particle is dead */
+ /* rotations */
+ rotate_particle(part,pa,pa_dfra,timestep);
+ break;
+ case PART_PHYS_BOIDS:
+ {
+ float acc[3];
+ boid_brain(&bvf,pa,ob,psys,part,tree,timestep,cfra,acc);
+ if(pa->alive != PARS_DYING)
+ boid_body(&bvf,pa,psys,part,timestep,acc);
+ break;
+ }
}
- copy_particle_key(key,&pa->state,1);
-
- if(dfra>0.0 && pa->alive==PARS_ALIVE){
- switch(part->phystype){
- case PART_PHYS_NEWTON:
- /* do global forces & effectors */
- apply_particle_forces(p,pa,ob,psys,part,timestep,pa_dfra,cfra,key);
-
- /* deflection */
- deflect_particle(ob,psmd,psys,part,pa,p,pa_dfra,cfra,key,&pa_die);
-
- /* rotations */
- rotate_particle(part,pa,pa_dfra,timestep,key);
+ if(pa->alive == PARS_DYING){
+ push_reaction(ob,psys,p,PART_EVENT_DEATH,&pa->state);
- break;
- case PART_PHYS_BOIDS:
- {
- float acc[3];
- boid_brain(&bvf,pa,ob,psys,part,tree,timestep,cfra,acc,&pa_die);
- if(pa_die==0)
- boid_body(&bvf,pa,psys,part,timestep,acc,key);
- break;
- }
+ if(part->flag & PART_LOOP && part->type!=PART_HAIR){
+ pa->loop++;
+ reset_particle(pa,psys,psmd,ob,0.0,cfra,vg_vel,vg_tan,vg_rot);
+ pa->alive=PARS_ALIVE;
}
+ else{
+ pa->alive=PARS_DEAD;
+ pa->state.time=pa->dietime;
- push_reaction(ob,psys,p,PART_EVENT_NEAR,key);
-
- if(pa_die){
- push_reaction(ob,psys,p,PART_EVENT_DEATH,key);
-
- if(part->flag & PART_LOOP){
- pa->loop++;
-
- if(part->flag & PART_LOOP_INSTANT){
- reset_particle(pa,psys,psmd,ob,0.0,cfra,vg_vel,vg_tan,vg_rot);
- pa->alive=PARS_ALIVE;
- copy_particle_key(key,&pa->state,1);
- }
- else
- pa->alive=PARS_UNBORN;
- }
- else{
- pa->alive=PARS_DEAD;
- key->time=pa->dietime;
-
- if(pa->flag&PARS_STICKY)
- psys_key_to_object(pa->stick_ob,key,0);
- }
+ if(pa->flag&PARS_STICKY)
+ psys_key_to_object(pa->stick_ob,&pa->state,0);
}
- else
- key->time=cfra;
}
+ else
+ pa->state.time=cfra;
+
+ push_reaction(ob,psys,p,PART_EVENT_NEAR,&pa->state);
}
}
- /* apply outstates to particles */
- for(p=0, pa=psys->particles, key=outstate; p<totpart; p++,pa++,key++)
- copy_particle_key(&pa->state,key,1);
-
- MEM_freeN(outstate);
}
if(psys->reactevents.first)
BLI_freelistN(&psys->reactevents);
@@ -4196,9 +4123,8 @@ static void psys_update_path_cache(Object *ob, ParticleSystemModifierData *psmd,
ParticleSettings *part=psys->part;
ParticleEditSettings *pset=&G.scene->toolsettings->particle;
int distr=0,alloc=0;
- int child_nbr= (psys->renderdata)? part->ren_child_nbr: part->child_nbr;
- if((psys->part->childtype && psys->totchild != psys->totpart*child_nbr) || psys->recalc&PSYS_ALLOC)
+ if((psys->part->childtype && psys->totchild != get_psys_tot_child(psys)) || psys->recalc&PSYS_ALLOC)
alloc=1;
if(alloc || psys->recalc&PSYS_DISTR || (psys->vgroup[PSYS_VG_DENSITY] && (G.f & G_WEIGHTPAINT)))
@@ -4206,9 +4132,9 @@ static void psys_update_path_cache(Object *ob, ParticleSystemModifierData *psmd,
if(distr){
if(alloc)
- alloc_particles(ob,psys,psys->totpart);
+ realloc_particles(ob,psys,psys->totpart);
- if(get_alloc_child_particles_tot(psys)) {
+ if(get_psys_tot_child(psys)) {
/* don't generate children while computing the hair keys */
if(!(psys->part->type == PART_HAIR) || (psys->flag & PSYS_HAIR_DONE)) {
distribute_particles(ob,psys,PART_FROM_CHILD);
@@ -4220,13 +4146,14 @@ static void psys_update_path_cache(Object *ob, ParticleSystemModifierData *psmd,
}
if((part->type==PART_HAIR || psys->flag&PSYS_KEYED) && (psys_in_edit_mode(psys)
- || part->draw_as==PART_DRAW_PATH || part->draw&PART_DRAW_KEYS)){
+ || (part->type==PART_HAIR || part->draw_as==PART_DRAW_PATH))){
psys_cache_paths(ob, psys, cfra, 0);
/* for render, child particle paths are computed on the fly */
if(part->childtype) {
if(((psys->totchild!=0)) || (psys_in_edit_mode(psys) && (pset->flag&PE_SHOW_CHILD)))
- psys_cache_child_paths(ob, psys, cfra, 0);
+ if(!(psys->part->type == PART_HAIR) || (psys->flag & PSYS_HAIR_DONE))
+ psys_cache_child_paths(ob, psys, cfra, 0);
}
}
else if(psys->pathcache)
@@ -4236,17 +4163,27 @@ static void psys_update_path_cache(Object *ob, ParticleSystemModifierData *psmd,
static void hair_step(Object *ob, ParticleSystemModifierData *psmd, ParticleSystem *psys, float cfra)
{
ParticleSettings *part = psys->part;
+ ParticleData *pa;
+ int p;
+ float disp = (float)get_current_display_percentage(psys)/50.0f-1.0f;
+
+ for(p=0, pa=psys->particles; p<psys->totpart; p++,pa++){
+ if(pa->r_rot[0] > disp)
+ pa->flag |= PARS_NO_DISP;
+ else
+ pa->flag &= ~PARS_NO_DISP;
+ }
if(psys->recalc & PSYS_DISTR)
/* need this for changing subsurf levels */
- psys_calc_dmfaces(ob, psmd->dm, psys);
+ psys_calc_dmcache(ob, psmd->dm, psys);
if(psys->effectors.first)
psys_end_effectors(psys);
psys_init_effectors(ob,part->eff_group,psys);
if(psys->effectors.first)
- precalc_effectors(ob,psys,psmd);
+ precalc_effectors(ob,psys,psmd,cfra);
if(psys_in_edit_mode(psys))
; //XXX PE_recalc_world_cos(ob, psys);
@@ -4255,7 +4192,7 @@ static void hair_step(Object *ob, ParticleSystemModifierData *psmd, ParticleSyst
}
/* updates cached particles' alive & other flags etc..*/
-static void cached_step(Object *ob, ParticleSystemModifierData *psmd, ParticleSystem *psys, float cfra, float *vg_size)
+static void cached_step(Object *ob, ParticleSystemModifierData *psmd, ParticleSystem *psys, float cfra)
{
ParticleSettings *part=psys->part;
ParticleData *pa;
@@ -4263,34 +4200,10 @@ static void cached_step(Object *ob, ParticleSystemModifierData *psmd, ParticleSy
IpoCurve *icu_esize=find_ipocurve(part->ipo,PART_EMIT_SIZE);
Material *ma=give_current_material(ob,part->omat);
int p;
- float ipotime=cfra, disp;
-
- /* deprecated */
- //if(psys->recalc&PSYS_DISTR){
- // /* The dm could have been changed so particle emitter element */
- // /* indices might be wrong. There's really no "nice" way to handle*/
- // /* this so we just try not to crash by correcting indices. */
- // int totnum=-1;
- // switch(part->from){
- // case PART_FROM_VERT:
- // totnum=psmd->dm->getNumVerts(psmd->dm);
- // break;
- // case PART_FROM_FACE:
- // case PART_FROM_VOLUME:
- // totnum=psmd->dm->getNumFaces(psmd->dm);
- // break;
- // }
-
- // if(totnum==0){
- // /* Now we're in real trouble, there's no emitter elements!! */
- // for(p=0, pa=psys->particles; p<psys->totpart; p++,pa++)
- // pa->num=-1;
- // }
- // else if(totnum>0){
- // for(p=0, pa=psys->particles; p<psys->totpart; p++,pa++)
- // pa->num=pa->num%totnum;
- // }
- //}
+ float ipotime=cfra, disp, birthtime, dietime, *vg_size= NULL;
+
+ if(part->from!=PART_FROM_PARTICLE)
+ vg_size= psys_cache_vgroup(psmd->dm,psys,PSYS_VG_SIZE);
if(psys->effectors.first)
psys_end_effectors(psys);
@@ -4298,7 +4211,7 @@ static void cached_step(Object *ob, ParticleSystemModifierData *psmd, ParticleSy
//if(part->flag & (PART_BAKED_GUIDES+PART_BAKED_DEATHS)){
psys_init_effectors(ob,part->eff_group,psys);
if(psys->effectors.first)
- precalc_effectors(ob,psys,psmd);
+ precalc_effectors(ob,psys,psmd,cfra);
//}
disp= (float)get_current_display_percentage(psys)/50.0f-1.0f;
@@ -4313,22 +4226,30 @@ static void cached_step(Object *ob, ParticleSystemModifierData *psmd, ParticleSy
psys->lattice=psys_get_lattice(ob,psys);
+ if(part->flag & PART_LOOP && part->type!=PART_HAIR)
+ pa->loop = (short)((cfra - pa->time) / pa->lifetime);
+ else
+ pa->loop = 0;
+
+ birthtime = pa->time + pa->loop * pa->lifetime;
+ dietime = birthtime + (1 + pa->loop) * (pa->dietime - pa->time);
+
/* update alive status and push events */
- if(pa->time>cfra)
- pa->alive=PARS_UNBORN;
- else if(pa->dietime<=cfra){
- if(pa->dietime>psys->cfra){
- state.time=pa->dietime;
+ if(pa->time > cfra)
+ pa->alive = PARS_UNBORN;
+ else if(dietime <= cfra){
+ if(dietime > psys->cfra){
+ state.time = pa->dietime;
psys_get_particle_state(ob,psys,p,&state,1);
push_reaction(ob,psys,p,PART_EVENT_DEATH,&state);
}
- pa->alive=PARS_DEAD;
+ pa->alive = PARS_DEAD;
}
else{
- pa->alive=PARS_ALIVE;
- state.time=cfra;
+ pa->alive = PARS_ALIVE;
+ state.time = cfra;
psys_get_particle_state(ob,psys,p,&state,1);
- state.time=cfra;
+ state.time = cfra;
push_reaction(ob,psys,p,PART_EVENT_NEAR,&state);
}
@@ -4342,126 +4263,324 @@ static void cached_step(Object *ob, ParticleSystemModifierData *psmd, ParticleSy
else
pa->flag &= ~PARS_NO_DISP;
}
+
+ /* make sure that children are up to date */
+ if(psys->part->childtype && psys->totchild != get_psys_tot_child(psys)) {
+ realloc_particles(ob, psys, psys->totpart);
+ distribute_particles(ob, psys, PART_FROM_CHILD);
+ }
+
+ if(vg_size)
+ MEM_freeN(vg_size);
+}
+
+void psys_changed_type(ParticleSystem *psys)
+{
+ ParticleSettings *part;
+
+ part= psys->part;
+
+ /* system type has changed so set sensible defaults and clear non applicable flags */
+ if(part->from == PART_FROM_PARTICLE) {
+ if(part->type != PART_REACTOR)
+ part->from = PART_FROM_FACE;
+ if(part->distr == PART_DISTR_GRID && part->from != PART_FROM_VERT)
+ part->distr = PART_DISTR_JIT;
+ }
+
+ if(psys->part->phystype != PART_PHYS_KEYED)
+ psys->flag &= ~PSYS_KEYED;
+
+ if(part->type == PART_HAIR) {
+ part->draw_as = PART_DRAW_PATH;
+ part->rotfrom = PART_ROT_IINCR;
+ }
+ else {
+ free_hair(psys, 1);
+
+ if(part->draw_as == PART_DRAW_PATH)
+ if(psys->part->phystype != PART_PHYS_KEYED)
+ part->draw_as = PART_DRAW_DOT;
+ }
+
+ psys->softflag= 0;
+
+ psys_reset(psys, PSYS_RESET_ALL);
}
+
+static void particles_fluid_step(Object *ob, ParticleSystem *psys, int cfra)
+{
+ if(psys->particles){
+ MEM_freeN(psys->particles);
+ psys->particles = 0;
+ psys->totpart = 0;
+ }
+
+ /* fluid sim particle import handling, actual loading of particles from file */
+ #ifndef DISABLE_ELBEEM
+ {
+ FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
+
+ if( fluidmd && fluidmd->fss) {
+ FluidsimSettings *fss= fluidmd->fss;
+ ParticleSettings *part = psys->part;
+ ParticleData *pa=0;
+ char *suffix = "fluidsurface_particles_####";
+ char *suffix2 = ".gz";
+ char filename[256];
+ char debugStrBuffer[256];
+ int curFrame = G.scene->r.cfra -1; // warning - sync with derived mesh fsmesh loading
+ int p, j, numFileParts, totpart;
+ int readMask, activeParts = 0, fileParts = 0;
+ gzFile gzf;
+
+ if(ob==G.obedit) // off...
+ return;
+
+ // ok, start loading
+ strcpy(filename, fss->surfdataPath);
+ strcat(filename, suffix);
+ BLI_convertstringcode(filename, G.sce);
+ BLI_convertstringframe(filename, curFrame); // fixed #frame-no
+ strcat(filename, suffix2);
+
+ gzf = gzopen(filename, "rb");
+ if (!gzf) {
+ snprintf(debugStrBuffer,256,"readFsPartData::error - Unable to open file for reading '%s' \n", filename);
+ //elbeemDebugOut(debugStrBuffer);
+ return;
+ }
+
+ gzread(gzf, &totpart, sizeof(totpart));
+ numFileParts = totpart;
+ totpart = (G.rendering)?totpart:(part->disp*totpart)/100;
+
+ part->totpart= totpart;
+ part->sta=part->end = 1.0f;
+ part->lifetime = G.scene->r.efra + 1;
+
+ /* initialize particles */
+ realloc_particles(ob, psys, part->totpart);
+ initialize_all_particles(ob, psys, 0);
+
+ // set up reading mask
+ readMask = fss->typeFlags;
+
+ for(p=0, pa=psys->particles; p<totpart; p++, pa++) {
+ int ptype=0;
+
+ gzread(gzf, &ptype, sizeof( ptype ));
+ if(ptype&readMask) {
+ activeParts++;
+
+ gzread(gzf, &(pa->size), sizeof( float ));
+
+ pa->size /= 10.0f;
+
+ for(j=0; j<3; j++) {
+ float wrf;
+ gzread(gzf, &wrf, sizeof( wrf ));
+ pa->state.co[j] = wrf;
+ //fprintf(stderr,"Rj%d ",j);
+ }
+ for(j=0; j<3; j++) {
+ float wrf;
+ gzread(gzf, &wrf, sizeof( wrf ));
+ pa->state.vel[j] = wrf;
+ }
+
+ pa->state.ave[0] = pa->state.ave[1] = pa->state.ave[2] = 0.0f;
+ pa->state.rot[0] = 1.0;
+ pa->state.rot[1] = pa->state.rot[2] = pa->state.rot[3] = 0.0;
+
+ pa->alive = PARS_ALIVE;
+ //if(a<25) fprintf(stderr,"FSPARTICLE debug set %s , a%d = %f,%f,%f , life=%f \n", filename, a, pa->co[0],pa->co[1],pa->co[2], pa->lifetime );
+ } else {
+ // skip...
+ for(j=0; j<2*3+1; j++) {
+ float wrf; gzread(gzf, &wrf, sizeof( wrf ));
+ }
+ }
+ fileParts++;
+ }
+ gzclose( gzf );
+
+ totpart = psys->totpart = activeParts;
+ snprintf(debugStrBuffer,256,"readFsPartData::done - particles:%d, active:%d, file:%d, mask:%d \n", psys->totpart,activeParts,fileParts,readMask);
+ elbeemDebugOut(debugStrBuffer);
+ } // fluid sim particles done
+ }
+ #endif // DISABLE_ELBEEM
+}
+
/* Calculates the next state for all particles of the system */
/* In particles code most fra-ending are frames, time-ending are fra*timestep (seconds)*/
static void system_step(Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd, float cfra)
{
ParticleSettings *part;
ParticleData *pa;
- int totpart,oldtotpart=0,p;
- float disp, *vg_vel=0, *vg_tan=0, *vg_rot=0, *vg_size=0;
- int init=0,distr=0,alloc=0;
- int child_nbr;
+ PointCache *cache;
+ PTCacheID pid;
+ int totpart, oldtotpart, totchild, oldtotchild, p;
+ float disp, *vg_vel= 0, *vg_tan= 0, *vg_rot= 0, *vg_size= 0;
+ int init= 0, distr= 0, alloc= 0, usecache= 0, only_children_changed= 0;
+ int framenr, framedelta, startframe, endframe;
- /*----start validity checks----*/
+ part= psys->part;
+ cache= psys->pointcache;
- part=psys->part;
+ framenr= (int)CFRA;
+ framedelta= framenr - cache->simframe;
- if(part->flag&PART_ABS_TIME && part->ipo){
+ BKE_ptcache_id_from_particles(&pid, ob, psys);
+ BKE_ptcache_id_time(&pid, 0.0f, &startframe, &endframe, NULL);
+
+ /* update ipo's */
+ if((part->flag & PART_ABS_TIME) && part->ipo) {
calc_ipo(part->ipo, cfra);
execute_ipo((ID *)part, part->ipo);
}
- if(part->from!=PART_FROM_PARTICLE)
- vg_size=psys_cache_vgroup(psmd->dm,psys,PSYS_VG_SIZE);
+ /* hair if it's already done is handled separate */
+ if(part->type == PART_HAIR && (psys->flag & PSYS_HAIR_DONE)) {
+ hair_step(ob, psmd, psys, cfra);
+ psys->cfra = cfra;
+ psys->recalc = 0;
+ return;
+ }
+ /* fluid is also handled separate */
+ else if(part->type == PART_FLUID) {
+ particles_fluid_step(ob, psys, framenr);
+ psys->cfra = cfra;
+ psys->recalc = 0;
+ return;
+ }
- if(part->type == PART_HAIR) {
- if(psys->flag & PSYS_HAIR_DONE) {
- hair_step(ob, psmd, psys, cfra);
+ /* cache shouldn't be used for hair or "none" or "keyed" physics */
+ if(part->type == PART_HAIR || ELEM(part->phystype, PART_PHYS_NO, PART_PHYS_KEYED))
+ usecache= 0;
+ else if(BKE_ptcache_get_continue_physics())
+ usecache= 0;
+ else
+ usecache= 1;
+
+ if(usecache) {
+ /* frame clamping */
+ if(framenr < startframe) {
+ psys_reset(psys, PSYS_RESET_CACHE_MISS);
psys->cfra = cfra;
psys->recalc = 0;
return;
}
- }
- else {
- if(psys->recalc)
- clear_particles_from_cache(ob,psys,(int)cfra);
- else if(get_particles_from_cache(ob, psys, (int)cfra)){
- cached_step(ob,psmd,psys,cfra,vg_size);
- psys->cfra=cfra;
- psys->recalc = 0;
- return;
+ else if(framenr > endframe) {
+ framenr= endframe;
}
}
- /* if still here react to events */
+ /* verify if we need to reallocate */
+ oldtotpart = psys->totpart;
+ oldtotchild = psys->totchild;
- if(psys->recalc&PSYS_TYPE) {
- /* system type has changed so set sensible defaults and clear non applicable flags */
- if(part->from == PART_FROM_PARTICLE) {
- if(part->type != PART_REACTOR)
- part->from = PART_FROM_FACE;
- if(part->distr == PART_DISTR_GRID)
- part->distr = PART_DISTR_JIT;
- }
-
- if(psys->part->phystype != PART_PHYS_KEYED)
- psys->flag &= ~PSYS_KEYED;
-
- if(part->type == PART_HAIR) {
- part->draw_as = PART_DRAW_PATH;
- part->rotfrom = PART_ROT_IINCR;
- }
- else
- free_hair(psys);
-
- psys->recalc &= ~PSYS_TYPE;
- alloc = 1;
-
- /* this is a bad level call, but currently type change
- * can happen after redraw, so force redraw from here */
-// XXX allqueue(REDRAWBUTSOBJECT, 0);
- }
- else
- oldtotpart = psys->totpart;
-
- if(part->distr == PART_DISTR_GRID)
- totpart = part->grid_res * part->grid_res * part->grid_res;
+ if(part->distr == PART_DISTR_GRID && part->from != PART_FROM_VERT)
+ totpart = part->grid_res*part->grid_res*part->grid_res;
else
totpart = psys->part->totpart;
+ totchild = get_psys_tot_child(psys);
- child_nbr= (psys->renderdata)? part->ren_child_nbr: part->child_nbr;
- if(oldtotpart != totpart || psys->recalc&PSYS_ALLOC || (psys->part->childtype && psys->totchild != psys->totpart*child_nbr))
+ if(oldtotpart != totpart || (psys->part->childtype && oldtotchild != totchild)) {
+ only_children_changed = (oldtotpart == totpart);
+ realloc_particles(ob, psys, totpart);
alloc = 1;
+ distr= 1;
+ init= 1;
+ }
- /* bad context? XXX */
- if(alloc || psys->recalc&PSYS_DISTR || (psys->vgroup[PSYS_VG_DENSITY] && (G.f & G_WEIGHTPAINT) && ob==(G.scene->basact?G.scene->basact->object:NULL)))
- distr = 1;
-
- if(distr || psys->recalc&PSYS_INIT)
- init = 1;
+ if(psys->recalc & PSYS_DISTR) {
+ distr= 1;
+ init= 1;
+ }
if(init) {
if(distr) {
if(alloc)
- alloc_particles(ob, psys, totpart);
+ realloc_particles(ob, psys, totpart);
distribute_particles(ob, psys, part->from);
- if(get_alloc_child_particles_tot(psys))
+ if((psys->part->type == PART_HAIR) && !(psys->flag & PSYS_HAIR_DONE))
+ /* don't generate children while growing hair - waste of time */
+ psys_free_children(psys);
+ else if(get_psys_tot_child(psys))
distribute_particles(ob, psys, PART_FROM_CHILD);
}
- initialize_all_particles(ob, psys, psmd);
- if(alloc)
- reset_all_particles(ob, psys, psmd, 0.0, cfra, oldtotpart);
+ if(only_children_changed==0) {
+ initialize_all_particles(ob, psys, psmd);
+
+ if(alloc)
+ reset_all_particles(ob, psys, psmd, 0.0, cfra, oldtotpart);
+ }
/* flag for possible explode modifiers after this system */
psmd->flag |= eParticleSystemFlag_Pars;
}
+ /* try to read from the cache */
+ if(usecache) {
+ if(get_particles_from_cache(ob, psys, framenr)) {
+ if(part->phystype==PART_PHYS_KEYED && psys->flag&PSYS_FIRST_KEYED) {
+ psys_count_keyed_targets(ob,psys);
+ set_keyed_keys(ob, psys);
+ }
+
+ cached_step(ob,psmd,psys,cfra);
+ psys->cfra=cfra;
+ psys->recalc = 0;
+
+ if(part->phystype==PART_PHYS_KEYED && psys->flag&PSYS_FIRST_KEYED) {
+ psys_update_path_cache(ob,psmd,psys,framenr);
+ }
+
+ cache->simframe= framenr;
+ cache->flag |= PTCACHE_SIMULATION_VALID;
+
+ return;
+ }
+ else if(ob->id.lib || (cache->flag & PTCACHE_BAKED)) {
+ psys_reset(psys, PSYS_RESET_CACHE_MISS);
+ psys->cfra=cfra;
+ psys->recalc = 0;
+ return;
+ }
+
+ if(framenr != startframe && framedelta != 1) {
+ psys_reset(psys, PSYS_RESET_CACHE_MISS);
+ psys->cfra = cfra;
+ psys->recalc = 0;
+ return;
+ }
+ }
+ else {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ }
+
+ /* if on second frame, write cache for first frame */
+ if(usecache && framenr == startframe+1)
+ write_particles_to_cache(ob, psys, startframe);
if(part->phystype==PART_PHYS_KEYED && psys->flag&PSYS_FIRST_KEYED)
psys_count_keyed_targets(ob,psys);
- if(part->from!=PART_FROM_PARTICLE){
- vg_vel=psys_cache_vgroup(psmd->dm,psys,PSYS_VG_VEL);
- vg_tan=psys_cache_vgroup(psmd->dm,psys,PSYS_VG_TAN);
- vg_rot=psys_cache_vgroup(psmd->dm,psys,PSYS_VG_ROT);
+ /* initialize vertex groups */
+ if(part->from!=PART_FROM_PARTICLE) {
+ vg_vel= psys_cache_vgroup(psmd->dm,psys,PSYS_VG_VEL);
+ vg_tan= psys_cache_vgroup(psmd->dm,psys,PSYS_VG_TAN);
+ vg_rot= psys_cache_vgroup(psmd->dm,psys,PSYS_VG_ROT);
+ vg_size= psys_cache_vgroup(psmd->dm,psys,PSYS_VG_SIZE);
}
- /* set particles to be not calculated */
+ /* set particles to be not calculated TODO: can't work with pointcache */
disp= (float)get_current_display_percentage(psys)/50.0f-1.0f;
for(p=0, pa=psys->particles; p<totpart; p++,pa++){
@@ -4471,15 +4590,30 @@ static void system_step(Object *ob, ParticleSystem *psys, ParticleSystemModifier
pa->flag &= ~PARS_NO_DISP;
}
- /* ok now we're all set so let's go */
- if(psys->totpart)
- dynamics_step(ob,psys,psmd,cfra,vg_vel,vg_tan,vg_rot,vg_size);
+ if(psys->totpart) {
+ int dframe, totframesback = 0;
+
+ /* handle negative frame start at the first frame by doing
+ * all the steps before the first frame */
+ if(framenr == startframe && part->sta < startframe)
+ totframesback = (startframe - (int)part->sta);
+
+ for(dframe=-totframesback; dframe<=0; dframe++) {
+ /* ok now we're all set so let's go */
+ dynamics_step(ob,psys,psmd,cfra+dframe,vg_vel,vg_tan,vg_rot,vg_size);
+ psys->cfra = cfra+dframe;
+ }
+ }
+
+ cache->simframe= framenr;
+ cache->flag |= PTCACHE_SIMULATION_VALID;
psys->recalc = 0;
- psys->cfra=cfra;
+ psys->cfra = cfra;
- if(part->type!=PART_HAIR)
- write_particles_to_cache(ob, psys, cfra);
+ /* only write cache starting from second frame */
+ if(usecache && framenr != startframe)
+ write_particles_to_cache(ob, psys, framenr);
/* for keyed particles the path is allways known so it can be drawn */
if(part->phystype==PART_PHYS_KEYED && psys->flag&PSYS_FIRST_KEYED){
@@ -4489,8 +4623,11 @@ static void system_step(Object *ob, ParticleSystem *psys, ParticleSystemModifier
else if(psys->pathcache)
psys_free_path_cache(psys);
- if(vg_vel)
- MEM_freeN(vg_vel);
+ /* cleanup */
+ if(vg_vel) MEM_freeN(vg_vel);
+ if(vg_tan) MEM_freeN(vg_tan);
+ if(vg_rot) MEM_freeN(vg_rot);
+ if(vg_size) MEM_freeN(vg_size);
if(psys->lattice){
end_latt_deform();
@@ -4498,105 +4635,97 @@ static void system_step(Object *ob, ParticleSystem *psys, ParticleSystemModifier
}
}
-void psys_to_softbody(Object *ob, ParticleSystem *psys, int force_recalc)
+static void psys_to_softbody(Object *ob, ParticleSystem *psys)
{
SoftBody *sb;
short softflag;
- if((psys->softflag&OB_SB_ENABLE)==0) return;
-
- if(psys->recalc || force_recalc)
- psys->softflag|=OB_SB_REDO;
+ if(!(psys->softflag & OB_SB_ENABLE))
+ return;
/* let's replace the object's own softbody with the particle softbody */
/* a temporary solution before cloth simulation is implemented, jahka */
/* save these */
- sb=ob->soft;
- softflag=ob->softflag;
+ sb= ob->soft;
+ softflag= ob->softflag;
/* swich to new ones */
- ob->soft=psys->soft;
- ob->softflag=psys->softflag;
+ ob->soft= psys->soft;
+ ob->softflag= psys->softflag;
/* do softbody */
sbObjectStep(ob, (float)G.scene->r.cfra, NULL, psys_count_keys(psys));
/* return things back to normal */
- psys->soft=ob->soft;
- psys->softflag=ob->softflag;
+ psys->soft= ob->soft;
+ psys->softflag= ob->softflag;
- ob->soft=sb;
- ob->softflag=softflag;
+ ob->soft= sb;
+ ob->softflag= softflag;
}
+
static int hair_needs_recalc(ParticleSystem *psys)
{
- if((psys->flag & PSYS_EDITED)==0 && (
- (psys->flag & PSYS_HAIR_DONE)==0
- || psys->recalc & PSYS_RECALC_HAIR)
- ) {
+ if((psys->flag & PSYS_EDITED)==0 &&
+ ((psys->flag & PSYS_HAIR_DONE)==0 || psys->recalc & PSYS_RECALC_HAIR)) {
psys->recalc &= ~PSYS_RECALC_HAIR;
return 1;
}
return 0;
}
-/* main particle update call, checks that things are ok on the large scale before actual particle calculations */
-void particle_system_update(Object *ob, ParticleSystem *psys){
- ParticleSystemModifierData *psmd=0;
+/* main particle update call, checks that things are ok on the large scale before actual particle calculations */
+void particle_system_update(Object *ob, ParticleSystem *psys)
+{
+ ParticleSystemModifierData *psmd;
float cfra;
if(!psys_check_enabled(ob, psys))
return;
- cfra=bsystem_time(ob,(float)G.scene->r.cfra,0.0);
+ cfra= bsystem_time(ob, (float)G.scene->r.cfra, 0.0f);
psmd= psys_get_modifier(ob, psys);
/* system was already updated from modifier stack */
- if(psmd->flag&eParticleSystemFlag_psys_updated) {
+ if(psmd->flag & eParticleSystemFlag_psys_updated) {
psmd->flag &= ~eParticleSystemFlag_psys_updated;
/* make sure it really was updated to cfra */
- if(psys->cfra==cfra)
+ if(psys->cfra == cfra)
return;
}
if(!psmd->dm)
return;
- /* baked path softbody */
- if(psys->part->type==PART_HAIR && psys->soft)
- psys_to_softbody(ob, psys, 0);
-
- /* not needed, this is all handled in hair_step */
- ///* is the mesh changing under the edited particles? */
- //if((psys->flag & PSYS_EDITED) && psys->part->type==PART_HAIR && psys->recalc & PSYS_RECALC_HAIR) {
- // /* Just update the particles on the mesh */
- // psys_update_edithair_dmfaces(ob, psmd->dm, psys);
- //}
-
- if(psys->part->type==PART_HAIR && hair_needs_recalc(psys)){
+ /* (re-)create hair */
+ if(psys->part->type==PART_HAIR && hair_needs_recalc(psys)) {
float hcfra=0.0f;
int i;
- free_hair(psys);
+
+ free_hair(psys, 0);
/* first step is negative so particles get killed and reset */
- psys->cfra=1.0f;
+ psys->cfra= 1.0f;
for(i=0; i<=psys->part->hair_step; i++){
hcfra=100.0f*(float)i/(float)psys->part->hair_step;
- system_step(ob,psys,psmd,hcfra);
- save_hair(ob,psys,psmd,hcfra);
+ system_step(ob, psys, psmd, hcfra);
+ save_hair(ob, psys, psmd, hcfra);
}
psys->flag |= PSYS_HAIR_DONE;
-
- if(psys->softflag&OB_SB_ENABLE)
- psys_to_softbody(ob,psys,1);
}
- system_step(ob,psys,psmd,cfra);
+ /* handle softbody hair */
+ if(psys->part->type==PART_HAIR && psys->soft)
+ psys_to_softbody(ob, psys);
+
+ /* the main particle system step */
+ system_step(ob, psys, psmd, cfra);
- Mat4Invert(psys->imat, ob->obmat); /* used for duplicators */
+ /* save matrix for duplicators */
+ Mat4Invert(psys->imat, ob->obmat);
}
diff --git a/source/blender/blenkernel/intern/pointcache.c b/source/blender/blenkernel/intern/pointcache.c
index 6da13cf4021..596ac882d24 100644
--- a/source/blender/blenkernel/intern/pointcache.c
+++ b/source/blender/blenkernel/intern/pointcache.c
@@ -24,22 +24,37 @@
* ***** END GPL LICENSE BLOCK *****
*/
-
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
-#include "BKE_pointcache.h"
+#include "MEM_guardedalloc.h"
-#include "BKE_utildefines.h"
-#include "BKE_global.h"
-#include "BKE_library.h"
+#include "DNA_ID.h"
+#include "DNA_cloth_types.h"
+#include "DNA_modifier_types.h"
+#include "DNA_object_types.h"
+#include "DNA_object_force.h"
+#include "DNA_particle_types.h"
+#include "DNA_scene_types.h"
#include "BLI_blenlib.h"
+
+#include "BKE_cloth.h"
+#include "BKE_depsgraph.h"
+#include "BKE_global.h"
+#include "BKE_library.h"
+#include "BKE_main.h"
+#include "BKE_modifier.h"
+#include "BKE_object.h"
+#include "BKE_particle.h"
+#include "BKE_pointcache.h"
+#include "BKE_softbody.h"
#include "BKE_utildefines.h"
+
/* needed for directory lookup */
#ifndef WIN32
#include <dirent.h>
@@ -47,30 +62,150 @@
#include "BLI_winstuff.h"
#endif
+/* untitled blend's need getpid for a unique name */
+#ifdef WIN32
+#include <process.h>
+#else
+#include <unistd.h>
+#endif
+
+#ifdef _WIN32
+#ifndef snprintf
+#define snprintf _snprintf
+#endif
+#endif
+
+/* Creating ID's */
+
+void BKE_ptcache_id_from_softbody(PTCacheID *pid, Object *ob, SoftBody *sb)
+{
+ ParticleSystemModifierData *psmd;
+ ModifierData *md;
+ int a;
+
+ memset(pid, 0, sizeof(PTCacheID));
+
+ pid->ob= ob;
+ pid->data= sb;
+ pid->type= PTCACHE_TYPE_SOFTBODY;
+ pid->cache= sb->pointcache;
+
+ if(sb->particles) {
+ psmd= psys_get_modifier(ob, sb->particles);
+ pid->stack_index= modifiers_indexInObject(ob, (ModifierData*)psmd);
+ }
+ else {
+ for(a=0, md=ob->modifiers.first; md; md=md->next, a++) {
+ if(md->type == eModifierType_Softbody) {
+ pid->stack_index = a;
+ break;
+ }
+ }
+ }
+}
+
+void BKE_ptcache_id_from_particles(PTCacheID *pid, Object *ob, ParticleSystem *psys)
+{
+ ParticleSystemModifierData *psmd= psys_get_modifier(ob, psys);
+
+ memset(pid, 0, sizeof(PTCacheID));
+
+ pid->ob= ob;
+ pid->data= psys;
+ pid->type= PTCACHE_TYPE_PARTICLES;
+ pid->stack_index= modifiers_indexInObject(ob, (ModifierData *)psmd);
+ pid->cache= psys->pointcache;
+}
+
+void BKE_ptcache_id_from_cloth(PTCacheID *pid, Object *ob, ClothModifierData *clmd)
+{
+ memset(pid, 0, sizeof(PTCacheID));
+
+ pid->ob= ob;
+ pid->data= clmd;
+ pid->type= PTCACHE_TYPE_CLOTH;
+ pid->stack_index= modifiers_indexInObject(ob, (ModifierData *)clmd);
+ pid->cache= clmd->point_cache;
+}
+
+void BKE_ptcache_ids_from_object(ListBase *lb, Object *ob)
+{
+ PTCacheID *pid;
+ ParticleSystem *psys;
+ ModifierData *md;
+
+ lb->first= lb->last= NULL;
+
+ if(ob->soft) {
+ pid= MEM_callocN(sizeof(PTCacheID), "PTCacheID");
+ BKE_ptcache_id_from_softbody(pid, ob, ob->soft);
+ BLI_addtail(lb, pid);
+ }
+
+ for(psys=ob->particlesystem.first; psys; psys=psys->next) {
+ pid= MEM_callocN(sizeof(PTCacheID), "PTCacheID");
+ BKE_ptcache_id_from_particles(pid, ob, psys);
+ BLI_addtail(lb, pid);
+
+ if(psys->soft) {
+ pid= MEM_callocN(sizeof(PTCacheID), "PTCacheID");
+ BKE_ptcache_id_from_softbody(pid, ob, psys->soft);
+ BLI_addtail(lb, pid);
+ }
+ }
+
+ for(md=ob->modifiers.first; md; md=md->next) {
+ if(md->type == eModifierType_Cloth) {
+ pid= MEM_callocN(sizeof(PTCacheID), "PTCacheID");
+ BKE_ptcache_id_from_cloth(pid, ob, (ClothModifierData*)md);
+ BLI_addtail(lb, pid);
+ }
+ }
+}
+
/* Takes an Object ID and returns a unique name
- id: object id
- cfra: frame for the cache, can be negative
- stack_index: index in the modifier stack. we can have cache for more then one stack_index
*/
-static int ptcache_path(char *filename)
+#define MAX_PTCACHE_PATH FILE_MAX
+#define MAX_PTCACHE_FILE ((FILE_MAXDIR+FILE_MAXFILE)*2)
+
+static int ptcache_path(PTCacheID *pid, char *filename)
{
- char dir[FILE_MAX], file[FILE_MAX]; /* we dont want the dir, only the file */
+ Library *lib;
int i;
+
+ lib= (pid)? pid->ob->id.lib: NULL;
+
+ if (G.relbase_valid || lib) {
+ char file[MAX_PTCACHE_PATH]; /* we dont want the dir, only the file */
+ char *blendfilename;
+
+ blendfilename= (lib)? lib->filename: G.sce;
+
+ BLI_split_dirfile_basic(blendfilename, NULL, file);
+ i = strlen(file);
+
+ /* remove .blend */
+ if (i > 6)
+ file[i-6] = '\0';
+
+ snprintf(filename, MAX_PTCACHE_PATH, "//"PTCACHE_PATH"%s", file); /* add blend file name to pointcache dir */
+ BLI_convertstringcode(filename, blendfilename);
+ BLI_add_slash(filename);
+ return strlen(filename);
+ }
- BLI_split_dirfile(G.sce, dir, file);
- i = strlen(file);
-
- /* remove .blend */
- if (i > 6)
- file[i-6] = '\0';
-
- sprintf(filename, PTCACHE_PATH"%s/", file); /* add blend file name to pointcache dir */
- BLI_convertstringcode(filename, G.sce, 0);
+ /* use the temp path. this is weak but better then not using point cache at all */
+ /* btempdir is assumed to exist and ALWAYS has a trailing slash */
+ snprintf(filename, MAX_PTCACHE_PATH, "%s"PTCACHE_PATH"%d", btempdir, abs(getpid()));
+ BLI_add_slash(filename);
return strlen(filename);
}
-int BKE_ptcache_id_filename(struct ID *id, char *filename, int cfra, int stack_index, short do_path, short do_ext)
+static int BKE_ptcache_id_filename(PTCacheID *pid, char *filename, int cfra, short do_path, short do_ext)
{
int len=0;
char *idname;
@@ -78,23 +213,23 @@ int BKE_ptcache_id_filename(struct ID *id, char *filename, int cfra, int stack_i
filename[0] = '\0';
newname = filename;
- if (!G.relbase_valid) return 0; /* save blend fiel before using pointcache */
+ /*if (!G.relbase_valid) return 0; *//* save blend file before using pointcache */
/* start with temp dir */
if (do_path) {
- len = ptcache_path(filename);
+ len = ptcache_path(pid, filename);
newname += len;
}
- idname = (id->name+2);
+ idname = (pid->ob->id.name+2);
/* convert chars to hex so they are always a valid filename */
while('\0' != *idname) {
- sprintf(newname, "%02X", (char)(*idname++));
+ snprintf(newname, MAX_PTCACHE_FILE, "%02X", (char)(*idname++));
newname+=2;
len += 2;
}
if (do_ext) {
- sprintf(newname, "_%06d_%02d"PTCACHE_EXT, cfra, stack_index); /* always 6 chars */
+ snprintf(newname, MAX_PTCACHE_FILE, "_%06d_%02d"PTCACHE_EXT, cfra, pid->stack_index); /* always 6 chars */
len += 16;
}
@@ -102,65 +237,98 @@ int BKE_ptcache_id_filename(struct ID *id, char *filename, int cfra, int stack_i
}
/* youll need to close yourself after! */
-FILE *BKE_ptcache_id_fopen(struct ID *id, char mode, int cfra, int stack_index)
+PTCacheFile *BKE_ptcache_file_open(PTCacheID *pid, int mode, int cfra)
{
- /* mode is same as fopen's modes */
+ PTCacheFile *pf;
FILE *fp = NULL;
char filename[(FILE_MAXDIR+FILE_MAXFILE)*2];
- if (!G.relbase_valid) return NULL; /* save blend fiel before using pointcache */
+ /* don't allow writing for linked objects */
+ if(pid->ob->id.lib && mode == PTCACHE_FILE_WRITE)
+ return NULL;
+
+ /*if (!G.relbase_valid) return NULL; *//* save blend file before using pointcache */
- BKE_ptcache_id_filename(id, filename, cfra, stack_index, 1, 1);
+ BKE_ptcache_id_filename(pid, filename, cfra, 1, 1);
- if (mode=='r') {
+ if (mode==PTCACHE_FILE_READ) {
if (!BLI_exists(filename)) {
return NULL;
}
fp = fopen(filename, "rb");
- } else if (mode=='w') {
+ } else if (mode==PTCACHE_FILE_WRITE) {
BLI_make_existing_file(filename); /* will create the dir if needs be, same as //textures is created */
fp = fopen(filename, "wb");
}
- if (!fp) {
+ if (!fp)
return NULL;
- }
+
+ pf= MEM_mallocN(sizeof(PTCacheFile), "PTCacheFile");
+ pf->fp= fp;
- return fp;
+ return pf;
+}
+
+void BKE_ptcache_file_close(PTCacheFile *pf)
+{
+ fclose(pf->fp);
+ MEM_freeN(pf);
+}
+
+int BKE_ptcache_file_read_floats(PTCacheFile *pf, float *f, int tot)
+{
+ return (fread(f, sizeof(float), tot, pf->fp) == tot);
+}
+
+int BKE_ptcache_file_write_floats(PTCacheFile *pf, float *f, int tot)
+{
+ return (fwrite(f, sizeof(float), tot, pf->fp) == tot);
}
/* youll need to close yourself after!
- * mode,
+ * mode - PTCACHE_CLEAR_ALL,
*/
-void BKE_ptcache_id_clear(struct ID *id, char mode, int cfra, int stack_index)
+void BKE_ptcache_id_clear(PTCacheID *pid, int mode, int cfra)
{
int len; /* store the length of the string */
/* mode is same as fopen's modes */
DIR *dir;
struct dirent *de;
- char path[FILE_MAX];
- char filename[(FILE_MAXDIR+FILE_MAXFILE)*2];
- char path_full[(FILE_MAXDIR+FILE_MAXFILE)*2];
-
- if (!G.relbase_valid) return; /* save blend fiel before using pointcache */
+ char path[MAX_PTCACHE_PATH];
+ char filename[MAX_PTCACHE_FILE];
+ char path_full[MAX_PTCACHE_FILE];
+ char ext[MAX_PTCACHE_PATH];
+
+ if(!pid->cache)
+ return;
+
+ /* don't allow clearing for linked objects */
+ if(pid->ob->id.lib)
+ return;
+
+ /*if (!G.relbase_valid) return; *//* save blend file before using pointcache */
/* clear all files in the temp dir with the prefix of the ID and the ".bphys" suffix */
switch (mode) {
case PTCACHE_CLEAR_ALL:
case PTCACHE_CLEAR_BEFORE:
case PTCACHE_CLEAR_AFTER:
- ptcache_path(path);
- len = BKE_ptcache_id_filename(id, filename, cfra, stack_index, 0, 0); /* no path */
+ ptcache_path(pid, path);
+
+ len = BKE_ptcache_id_filename(pid, filename, cfra, 0, 0); /* no path */
dir = opendir(path);
if (dir==NULL)
return;
+
+ snprintf(ext, sizeof(ext), "_%02d"PTCACHE_EXT, pid->stack_index);
while ((de = readdir(dir)) != NULL) {
- if (strstr(de->d_name, PTCACHE_EXT)) { /* do we have the right extension?*/
+ if (strstr(de->d_name, ext)) { /* do we have the right extension?*/
if (strncmp(filename, de->d_name, len ) == 0) { /* do we have the right prefix */
if (mode == PTCACHE_CLEAR_ALL) {
BLI_join_dirfile(path_full, path, de->d_name);
@@ -169,8 +337,9 @@ void BKE_ptcache_id_clear(struct ID *id, char mode, int cfra, int stack_index)
/* read the number of the file */
int frame, len2 = strlen(de->d_name);
char num[7];
+
if (len2 > 15) { /* could crash if trying to copy a string out of this range*/
- strncpy(num, de->d_name + (strlen(de->d_name) - 15), 6);
+ BLI_strncpy(num, de->d_name + (strlen(de->d_name) - 15), sizeof(num));
frame = atoi(num);
if((mode==PTCACHE_CLEAR_BEFORE && frame < cfra) ||
@@ -188,18 +357,248 @@ void BKE_ptcache_id_clear(struct ID *id, char mode, int cfra, int stack_index)
break;
case PTCACHE_CLEAR_FRAME:
- len = BKE_ptcache_id_filename(id, filename, cfra, stack_index, 1, 1); /* no path */
+ len = BKE_ptcache_id_filename(pid, filename, cfra, 1, 1); /* no path */
BLI_delete(filename, 0, 0);
break;
}
- return;
}
-int BKE_ptcache_id_exist(struct ID *id, int cfra, int stack_index)
+int BKE_ptcache_id_exist(PTCacheID *pid, int cfra)
{
- char filename[(FILE_MAXDIR+FILE_MAXFILE)*2];
+ char filename[MAX_PTCACHE_FILE];
+
+ if(!pid->cache)
+ return 0;
- BKE_ptcache_id_filename(id, filename, cfra, stack_index, 1, 1);
+ BKE_ptcache_id_filename(pid, filename, cfra, 1, 1);
return BLI_exists(filename);
}
+
+void BKE_ptcache_id_time(PTCacheID *pid, float cfra, int *startframe, int *endframe, float *timescale)
+{
+ Object *ob;
+ PointCache *cache;
+ float offset, time, nexttime;
+
+ /* time handling for point cache:
+ * - simulation time is scaled by result of bsystem_time
+ * - for offsetting time only time offset is taken into account, since
+ * that's always the same and can't be animated. a timeoffset which
+ * varies over time is not simpe to support.
+ * - field and motion blur offsets are currently ignored, proper solution
+ * is probably to interpolate results from two frames for that ..
+ */
+
+ ob= pid->ob;
+ cache= pid->cache;
+
+ if(timescale) {
+ time= bsystem_time(ob, cfra, 0.0f);
+ nexttime= bsystem_time(ob, cfra+1.0f, 0.0f);
+
+ *timescale= MAX2(nexttime - time, 0.0f);
+ }
+
+ if(startframe && endframe) {
+ *startframe= cache->startframe;
+ *endframe= cache->endframe;
+
+ if ((ob->ipoflag & OB_OFFS_PARENT) && (ob->partype & PARSLOW)==0) {
+ offset= give_timeoffset(ob);
+
+ *startframe += (int)(offset+0.5f);
+ *endframe += (int)(offset+0.5f);
+ }
+ }
+}
+
+int BKE_ptcache_id_reset(PTCacheID *pid, int mode)
+{
+ PointCache *cache;
+ int reset, clear;
+
+ if(!pid->cache)
+ return 0;
+
+ cache= pid->cache;
+ reset= 0;
+ clear= 0;
+
+ if(mode == PTCACHE_RESET_DEPSGRAPH) {
+ if(!(cache->flag & PTCACHE_BAKED) && !BKE_ptcache_get_continue_physics()) {
+ reset= 1;
+ clear= 1;
+ }
+ else
+ cache->flag |= PTCACHE_OUTDATED;
+ }
+ else if(mode == PTCACHE_RESET_BAKED) {
+ if(!BKE_ptcache_get_continue_physics()) {
+ reset= 1;
+ clear= 1;
+ }
+ else
+ cache->flag |= PTCACHE_OUTDATED;
+ }
+ else if(mode == PTCACHE_RESET_OUTDATED) {
+ reset = 1;
+
+ if(cache->flag & PTCACHE_OUTDATED)
+ if(!(cache->flag & PTCACHE_BAKED))
+ clear= 1;
+ }
+
+ if(reset) {
+ cache->flag &= ~(PTCACHE_OUTDATED|PTCACHE_SIMULATION_VALID);
+ cache->simframe= 0;
+
+ if(pid->type == PTCACHE_TYPE_CLOTH)
+ cloth_free_modifier(pid->ob, pid->data);
+ else if(pid->type == PTCACHE_TYPE_SOFTBODY)
+ sbFreeSimulation(pid->data);
+ else if(pid->type == PTCACHE_TYPE_PARTICLES)
+ psys_reset(pid->data, PSYS_RESET_DEPSGRAPH);
+ }
+ if(clear)
+ BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0);
+
+ return (reset || clear);
+}
+
+int BKE_ptcache_object_reset(Object *ob, int mode)
+{
+ PTCacheID pid;
+ ParticleSystem *psys;
+ ModifierData *md;
+ int reset, skip;
+
+ reset= 0;
+ skip= 0;
+
+ if(ob->soft) {
+ BKE_ptcache_id_from_softbody(&pid, ob, ob->soft);
+ reset |= BKE_ptcache_id_reset(&pid, mode);
+ }
+
+ for(psys=ob->particlesystem.first; psys; psys=psys->next) {
+ /* Baked softbody hair has to be checked first, because we don't want to reset */
+ /* particles or softbody in that case -jahka */
+ if(psys->soft) {
+ BKE_ptcache_id_from_softbody(&pid, ob, psys->soft);
+ if(mode == PSYS_RESET_ALL || !(psys->part->type == PART_HAIR && (pid.cache->flag & PTCACHE_BAKED)))
+ reset |= BKE_ptcache_id_reset(&pid, mode);
+ else
+ skip = 1;
+ }
+
+ if(skip == 0) {
+ BKE_ptcache_id_from_particles(&pid, ob, psys);
+ reset |= BKE_ptcache_id_reset(&pid, mode);
+ }
+ }
+
+ for(md=ob->modifiers.first; md; md=md->next) {
+ if(md->type == eModifierType_Cloth) {
+ BKE_ptcache_id_from_cloth(&pid, ob, (ClothModifierData*)md);
+ reset |= BKE_ptcache_id_reset(&pid, mode);
+ }
+ }
+
+ return reset;
+}
+
+/* Use this when quitting blender, with unsaved files */
+void BKE_ptcache_remove(void)
+{
+ char path[MAX_PTCACHE_PATH];
+ char path_full[MAX_PTCACHE_PATH];
+ int rmdir = 1;
+
+ ptcache_path(NULL, path);
+
+ if (BLI_exist(path)) {
+ /* The pointcache dir exists? - remove all pointcache */
+
+ DIR *dir;
+ struct dirent *de;
+
+ dir = opendir(path);
+ if (dir==NULL)
+ return;
+
+ while ((de = readdir(dir)) != NULL) {
+ if( strcmp(de->d_name, ".")==0 || strcmp(de->d_name, "..")==0) {
+ /* do nothing */
+ } else if (strstr(de->d_name, PTCACHE_EXT)) { /* do we have the right extension?*/
+ BLI_join_dirfile(path_full, path, de->d_name);
+ BLI_delete(path_full, 0, 0);
+ } else {
+ rmdir = 0; /* unknown file, dont remove the dir */
+ }
+ }
+
+ closedir(dir);
+ } else {
+ rmdir = 0; /* path dosnt exist */
+ }
+
+ if (rmdir) {
+ BLI_delete(path, 1, 0);
+ }
+}
+
+/* Continuous Interaction */
+
+static int CONTINUE_PHYSICS = 0;
+
+void BKE_ptcache_set_continue_physics(int enable)
+{
+ Object *ob;
+
+ if(CONTINUE_PHYSICS != enable) {
+ CONTINUE_PHYSICS = enable;
+
+ if(CONTINUE_PHYSICS == 0) {
+ for(ob=G.main->object.first; ob; ob=ob->id.next)
+ if(BKE_ptcache_object_reset(ob, PTCACHE_RESET_OUTDATED))
+ DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
+ }
+ }
+}
+
+int BKE_ptcache_get_continue_physics()
+{
+ return CONTINUE_PHYSICS;
+}
+
+/* Point Cache */
+
+PointCache *BKE_ptcache_add()
+{
+ PointCache *cache;
+
+ cache= MEM_callocN(sizeof(PointCache), "PointCache");
+ cache->startframe= 1;
+ cache->endframe= 250;
+
+ return cache;
+}
+
+void BKE_ptcache_free(PointCache *cache)
+{
+ MEM_freeN(cache);
+}
+
+PointCache *BKE_ptcache_copy(PointCache *cache)
+{
+ PointCache *ncache;
+
+ ncache= MEM_dupallocN(cache);
+
+ ncache->flag= 0;
+ ncache->simframe= 0;
+
+ return ncache;
+}
+
diff --git a/source/blender/blenkernel/intern/property.c b/source/blender/blenkernel/intern/property.c
index b86efb97fc5..509cd8cf750 100644
--- a/source/blender/blenkernel/intern/property.c
+++ b/source/blender/blenkernel/intern/property.c
@@ -81,8 +81,7 @@ bProperty *copy_property(bProperty *prop)
void copy_properties(ListBase *lbn, ListBase *lbo)
{
bProperty *prop, *propn;
-
- lbn->first= lbn->last= 0;
+ free_properties( lbn ); /* incase we are copying to an object with props */
prop= lbo->first;
while(prop) {
propn= copy_property(prop);
@@ -137,7 +136,7 @@ bProperty *new_property(int type)
return prop;
}
-bProperty *get_property(Object *ob, char *name)
+bProperty *get_ob_property(Object *ob, char *name)
{
bProperty *prop;
@@ -149,6 +148,17 @@ bProperty *get_property(Object *ob, char *name)
return NULL;
}
+void set_ob_property(Object *ob, bProperty *propc)
+{
+ bProperty *prop;
+ prop= get_ob_property(ob, propc->name);
+ if(prop) {
+ free_property(prop);
+ BLI_remlink(&ob->prop, prop);
+ }
+ BLI_addtail(&ob->prop, copy_property(propc));
+}
+
/* negative: prop is smaller
* positive: prop is larger
*/
diff --git a/source/blender/blenkernel/intern/sca.c b/source/blender/blenkernel/intern/sca.c
index 81da2fcbd96..e8c6c5c199f 100644
--- a/source/blender/blenkernel/intern/sca.c
+++ b/source/blender/blenkernel/intern/sca.c
@@ -150,6 +150,12 @@ void init_sensor(bSensor *sens)
case SENS_PROPERTY:
sens->data= MEM_callocN(sizeof(bPropertySensor), "propsens");
break;
+ case SENS_ACTUATOR:
+ sens->data= MEM_callocN(sizeof(bActuatorSensor), "actsens");
+ break;
+ case SENS_DELAY:
+ sens->data= MEM_callocN(sizeof(bDelaySensor), "delaysens");
+ break;
case SENS_MOUSE:
ms=sens->data= MEM_callocN(sizeof(bMouseSensor), "mousesens");
//XXX ms->type= LEFTMOUSE;
@@ -411,6 +417,7 @@ void init_actuator(bActuator *act)
switch(act->type) {
#ifdef __NLA
case ACT_ACTION:
+ case ACT_SHAPEACTION:
act->data= MEM_callocN(sizeof(bActionActuator), "actionact");
break;
#endif
@@ -458,6 +465,15 @@ void init_actuator(bActuator *act)
case ACT_VISIBILITY:
act->data= MEM_callocN(sizeof(bVisibilityActuator), "visibility act");
break;
+ case ACT_2DFILTER:
+ act->data = MEM_callocN(sizeof( bTwoDFilterActuator ), "2d filter act");
+ break;
+ case ACT_PARENT:
+ act->data = MEM_callocN(sizeof( bParentActuator ), "parent act");
+ break;
+ case ACT_STATE:
+ act->data = MEM_callocN(sizeof( bStateActuator ), "state act");
+ break;
default:
; /* this is very severe... I cannot make any memory for this */
/* logic brick... */
diff --git a/source/blender/blenkernel/intern/scene.c b/source/blender/blenkernel/intern/scene.c
index ebb2a80314f..096c04b7bd3 100644
--- a/source/blender/blenkernel/intern/scene.c
+++ b/source/blender/blenkernel/intern/scene.c
@@ -61,11 +61,13 @@
#include "BKE_anim.h"
#include "BKE_armature.h"
#include "BKE_colortools.h"
+#include "BKE_colortools.h"
#include "BKE_constraint.h"
#include "BKE_depsgraph.h"
#include "BKE_global.h"
#include "BKE_group.h"
#include "BKE_ipo.h"
+#include "BKE_idprop.h"
#include "BKE_image.h"
#include "BKE_key.h"
#include "BKE_library.h"
@@ -78,8 +80,12 @@
#include "BKE_utildefines.h"
//XXX #include "BIF_previewrender.h"
+//XXX #include "BIF_editseq.h"
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h"
+#endif
+
#include "BLI_arithb.h"
#include "BLI_blenlib.h"
@@ -136,7 +142,10 @@ void free_scene(Scene *sce)
if(sce->radio) MEM_freeN(sce->radio);
sce->radio= 0;
+#ifndef DISABLE_PYTHON
BPY_free_scriptlink(&sce->scriptlink);
+#endif
+
if (sce->r.avicodecdata) {
free_avicodecdata(sce->r.avicodecdata);
MEM_freeN(sce->r.avicodecdata);
@@ -147,8 +156,14 @@ void free_scene(Scene *sce)
MEM_freeN(sce->r.qtcodecdata);
sce->r.qtcodecdata = NULL;
}
+ if (sce->r.ffcodecdata.properties) {
+ IDP_FreeProperty(sce->r.ffcodecdata.properties);
+ MEM_freeN(sce->r.ffcodecdata.properties);
+ sce->r.ffcodecdata.properties = NULL;
+ }
BLI_freelistN(&sce->markers);
+ BLI_freelistN(&sce->transform_spaces);
BLI_freelistN(&sce->r.layers);
if(sce->toolsettings){
@@ -179,6 +194,7 @@ Scene *add_scene(char *name)
sce->lay= 1;
sce->selectmode= SCE_SELECT_VERTEX;
sce->editbutsize= 0.1;
+ sce->autokey_mode= U.autokey_mode;
sce->r.mode= R_GAMMA;
sce->r.cfra= 1;
@@ -215,6 +231,15 @@ Scene *add_scene(char *name)
sce->r.stereomode = 1; // no stereo
+ sce->r.simplify_subsurf= 6;
+ sce->r.simplify_particles= 1.0f;
+ sce->r.simplify_shadowsamples= 16;
+ sce->r.simplify_aosss= 1.0f;
+
+ sce->r.cineonblack= 95;
+ sce->r.cineonwhite= 685;
+ sce->r.cineongamma= 1.7f;
+
sce->toolsettings = MEM_callocN(sizeof(struct ToolSettings),"Tool Settings Struct");
sce->toolsettings->cornertype=1;
sce->toolsettings->degr = 90;
@@ -234,6 +259,21 @@ Scene *add_scene(char *name)
sce->toolsettings->select_thresh= 0.01f;
sce->toolsettings->jointrilimit = 0.8f;
+ sce->toolsettings->skgen_resolution = 100;
+ sce->toolsettings->skgen_threshold_internal = 0.01f;
+ sce->toolsettings->skgen_threshold_external = 0.01f;
+ sce->toolsettings->skgen_angle_limit = 45.0f;
+ sce->toolsettings->skgen_length_ratio = 1.3f;
+ sce->toolsettings->skgen_length_limit = 1.5f;
+ sce->toolsettings->skgen_correlation_limit = 0.98f;
+ sce->toolsettings->skgen_symmetry_limit = 0.1f;
+ sce->toolsettings->skgen_postpro = SKGEN_SMOOTH;
+ sce->toolsettings->skgen_postpro_passes = 1;
+ sce->toolsettings->skgen_options = SKGEN_FILTER_INTERNAL|SKGEN_FILTER_EXTERNAL|SKGEN_FILTER_SMART|SKGEN_HARMONIC|SKGEN_SUB_CORRELATION|SKGEN_STICK_TO_EMBEDDING;
+ sce->toolsettings->skgen_subdivisions[0] = SKGEN_SUB_CORRELATION;
+ sce->toolsettings->skgen_subdivisions[1] = SKGEN_SUB_LENGTH;
+ sce->toolsettings->skgen_subdivisions[2] = SKGEN_SUB_ANGLE;
+
pset= &sce->toolsettings->particle;
pset->flag= PE_KEEP_LENGTHS|PE_LOCK_FIRST|PE_DEFLECT_EMITTER;
pset->emitterdist= 0.25f;
@@ -252,13 +292,12 @@ Scene *add_scene(char *name)
strcpy(sce->r.backbuf, "//backbuf");
strcpy(sce->r.pic, U.renderdir);
- strcpy(sce->r.ftype, "//ftype");
BLI_init_rctf(&sce->r.safety, 0.1f, 0.9f, 0.1f, 0.9f);
sce->r.osa= 8;
sculptdata_init(sce);
-
+
/* note; in header_info.c the scene copy happens..., if you add more to renderdata it has to be checked there */
scene_add_render_layer(sce);
@@ -285,6 +324,9 @@ void set_scene_bg(Scene *sce)
GroupObject *go;
int flag;
+ // Note: this here is defined in editseq.c (BIF_editseq.h), NOT in blenkernel!
+ //XXX clear_last_seq();
+
G.scene= sce;
/* check for cyclic sets, for reading old files but also for definite security (py?) */
@@ -330,7 +372,7 @@ void set_scene_bg(Scene *sce)
/* no full animation update, this to enable render code to work (render code calls own animation updates) */
/* do we need FRAMECHANGED in set_scene? */
-// if (G.f & G_DOSCRIPTLINKS) BPY_do_all_scripts(SCRIPT_FRAMECHANGED);
+// if (G.f & G_DOSCRIPTLINKS) BPY_do_all_scripts(SCRIPT_FRAMECHANGED, 0);
}
/* called from creator.c */
@@ -413,6 +455,9 @@ int next_object(int val, Base **base, Object **ob)
duplilist= object_duplilist(G.scene, (*base)->object);
dupob= duplilist->first;
+
+ if(!dupob)
+ free_object_duplilist(duplilist);
}
}
}
@@ -494,27 +539,23 @@ void scene_select_base(Scene *sce, Base *selbase)
int scene_check_setscene(Scene *sce)
{
Scene *scene;
+ int a, totscene;
if(sce->set==NULL) return 1;
- /* LIB_DOIT is the free flag to tag library data */
+ totscene= 0;
for(scene= G.main->scene.first; scene; scene= scene->id.next)
- scene->id.flag &= ~LIB_DOIT;
-
- scene= sce;
- while(scene->set) {
- scene->id.flag |= LIB_DOIT;
- /* when set has flag set, we got a cycle */
- if(scene->set->id.flag & LIB_DOIT)
- break;
- scene= scene->set;
- }
-
- if(scene->set) {
- /* the tested scene gets zero'ed, that's typically current scene */
- sce->set= NULL;
- return 0;
+ totscene++;
+
+ for(a=0, scene=sce; scene->set; scene=scene->set, a++) {
+ /* more iterations than scenes means we have a cycle */
+ if(a > totscene) {
+ /* the tested scene gets zero'ed, that's typically current scene */
+ sce->set= NULL;
+ return 0;
+ }
}
+
return 1;
}
@@ -550,9 +591,9 @@ void scene_update_for_newframe(Scene *sce, unsigned int lay)
/* object ipos are calculated in where_is_object */
do_all_data_ipos();
-
- if (G.f & G_DOSCRIPTLINKS) BPY_do_all_scripts(SCRIPT_FRAMECHANGED);
-
+#ifndef DISABLE_PYTHON
+ if (G.f & G_DOSCRIPTLINKS) BPY_do_all_scripts(SCRIPT_FRAMECHANGED, 0);
+#endif
/* sets first, we allow per definition current scene to have dependencies on sets */
for(sce= sce->set; sce; sce= sce->set)
scene_update(sce, lay);
@@ -587,8 +628,10 @@ void sculptdata_init(Scene *sce)
sd= &sce->sculptdata;
- if(sd->cumap)
+ if(sd->cumap) {
curvemapping_free(sd->cumap);
+ sd->cumap = NULL;
+ }
memset(sd, 0, sizeof(SculptData));
@@ -600,9 +643,9 @@ void sculptdata_init(Scene *sce)
sd->grabbrush.strength = sd->layerbrush.strength =
sd->flattenbrush.strength = 25;
sd->drawbrush.dir = sd->pinchbrush.dir = sd->inflatebrush.dir = sd->layerbrush.dir= 1;
- sd->drawbrush.airbrush = sd->smoothbrush.airbrush =
- sd->pinchbrush.airbrush = sd->inflatebrush.airbrush =
- sd->layerbrush.airbrush = sd->flattenbrush.airbrush = 0;
+ sd->drawbrush.flag = sd->smoothbrush.flag =
+ sd->pinchbrush.flag = sd->inflatebrush.flag =
+ sd->layerbrush.flag = sd->flattenbrush.flag = 0;
sd->drawbrush.view= 0;
sd->brush_type= DRAW_BRUSH;
sd->texact= -1;
@@ -656,13 +699,8 @@ void sculptsession_free(Scene *sce)
if(ss->mats)
MEM_freeN(ss->mats);
- if(ss->propset) {
- if(ss->propset->texdata)
- MEM_freeN(ss->propset->texdata);
- if(ss->propset->num)
- MEM_freeN(ss->propset->num);
- MEM_freeN(ss->propset);
- }
+ if(ss->radialcontrol)
+ MEM_freeN(ss->radialcontrol);
sculpt_vertexusers_free(ss);
if(ss->texcache)
@@ -702,3 +740,38 @@ void sculpt_reset_curve(SculptData *sd)
curvemapping_changed(sd->cumap, 0);
}
+
+/* render simplification */
+
+int get_render_subsurf_level(RenderData *r, int lvl)
+{
+ if(G.rt == 1 && (r->mode & R_SIMPLIFY))
+ return MIN2(r->simplify_subsurf, lvl);
+ else
+ return lvl;
+}
+
+int get_render_child_particle_number(RenderData *r, int num)
+{
+ if(G.rt == 1 && (r->mode & R_SIMPLIFY))
+ return (int)(r->simplify_particles*num);
+ else
+ return num;
+}
+
+int get_render_shadow_samples(RenderData *r, int samples)
+{
+ if(G.rt == 1 && (r->mode & R_SIMPLIFY) && samples > 0)
+ return MIN2(r->simplify_shadowsamples, samples);
+ else
+ return samples;
+}
+
+float get_render_aosss_error(RenderData *r, float error)
+{
+ if(G.rt == 1 && (r->mode & R_SIMPLIFY))
+ return ((1.0f-r->simplify_aosss)*10.0f + 1.0f)*error;
+ else
+ return error;
+}
+
diff --git a/source/blender/blenkernel/intern/screen.c b/source/blender/blenkernel/intern/screen.c
index 926a62e9f69..bf2ed2c658e 100644
--- a/source/blender/blenkernel/intern/screen.c
+++ b/source/blender/blenkernel/intern/screen.c
@@ -20,7 +20,9 @@
* The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
* All rights reserved.
*
- * Contributor(s): Blender Foundation 2002-2008
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
*
* ***** END GPL LICENSE BLOCK *****
*/
diff --git a/source/blender/blenkernel/intern/script.c b/source/blender/blenkernel/intern/script.c
index ab7ae0e09fe..e34b1d0a1dd 100644
--- a/source/blender/blenkernel/intern/script.c
+++ b/source/blender/blenkernel/intern/script.c
@@ -32,18 +32,21 @@
*/
#include "BKE_script.h"
-//XXX #include "BPI_script.h"
+#include "DNA_space_types.h"
#include "MEM_guardedalloc.h"
-
+/*
#include "BLI_blenlib.h"
#include "BKE_utildefines.h"
#include "BKE_library.h"
#include "BKE_global.h"
#include "BKE_main.h"
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h" // Blender Python library
+#endif
+*/
/* XXX this function and so also the file should not be needed anymore,
* since we have to force clearing all Python related data before freeing
@@ -54,13 +57,8 @@
void free_script (Script *script)
{
if (!script) return;
-
- if (script->py_globaldict || script->py_button ||
- script->py_event || script->py_draw)
- {
- BPY_clear_script(script);
- }
-
- return;
+#ifndef DISABLE_PYTHON
+ BPY_clear_script(script);
+#endif
}
#endif
diff --git a/source/blender/blenkernel/intern/shrinkwrap.c b/source/blender/blenkernel/intern/shrinkwrap.c
new file mode 100644
index 00000000000..ab98fb1f007
--- /dev/null
+++ b/source/blender/blenkernel/intern/shrinkwrap.c
@@ -0,0 +1,599 @@
+/**
+ * shrinkwrap.c
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): André Pinto
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#include <string.h>
+#include <float.h>
+#include <math.h>
+#include <memory.h>
+#include <stdio.h>
+#include <time.h>
+#include <assert.h>
+
+#include "DNA_object_types.h"
+#include "DNA_modifier_types.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_mesh_types.h"
+
+#include "BKE_shrinkwrap.h"
+#include "BKE_DerivedMesh.h"
+#include "BKE_lattice.h"
+#include "BKE_utildefines.h"
+#include "BKE_deform.h"
+#include "BKE_cdderivedmesh.h"
+#include "BKE_displist.h"
+#include "BKE_global.h"
+#include "BKE_subsurf.h"
+
+#include "BLI_arithb.h"
+#include "BLI_kdtree.h"
+#include "BLI_kdopbvh.h"
+
+#include "RE_raytrace.h"
+#include "MEM_guardedalloc.h"
+
+
+/* Util macros */
+#define TO_STR(a) #a
+#define JOIN(a,b) a##b
+
+#define OUT_OF_MEMORY() ((void)printf("Shrinkwrap: Out of memory\n"))
+
+/* Benchmark macros */
+#if !defined(_WIN32) && 0
+
+#include <sys/time.h>
+
+#define BENCH(a) \
+ do { \
+ double _t1, _t2; \
+ struct timeval _tstart, _tend; \
+ clock_t _clock_init = clock(); \
+ gettimeofday ( &_tstart, NULL); \
+ (a); \
+ gettimeofday ( &_tend, NULL); \
+ _t1 = ( double ) _tstart.tv_sec + ( double ) _tstart.tv_usec/ ( 1000*1000 ); \
+ _t2 = ( double ) _tend.tv_sec + ( double ) _tend.tv_usec/ ( 1000*1000 ); \
+ printf("%s: %fs (real) %fs (cpu)\n", #a, _t2-_t1, (float)(clock()-_clock_init)/CLOCKS_PER_SEC);\
+ } while(0)
+
+#else
+
+#define BENCH(a) (a)
+
+#endif
+
+typedef void ( *Shrinkwrap_ForeachVertexCallback) (DerivedMesh *target, float *co, float *normal);
+
+/* get derived mesh */
+//TODO is anyfunction that does this? returning the derivedFinal witouth we caring if its in edit mode or not?
+DerivedMesh *object_get_derived_final(Object *ob, CustomDataMask dataMask)
+{
+ if (ob==G.obedit)
+ {
+ DerivedMesh *final = NULL;
+ editmesh_get_derived_cage_and_final(&final, dataMask);
+ return final;
+ }
+ else
+ return mesh_get_derived_final(ob, dataMask);
+}
+
+/* Space transform */
+void space_transform_from_matrixs(SpaceTransform *data, float local[4][4], float target[4][4])
+{
+ float itarget[4][4];
+ Mat4Invert(itarget, target);
+ Mat4MulSerie(data->local2target, itarget, local, 0, 0, 0, 0, 0, 0);
+ Mat4Invert(data->target2local, data->local2target);
+}
+
+void space_transform_apply(const SpaceTransform *data, float *co)
+{
+ VecMat4MulVecfl(co, ((SpaceTransform*)data)->local2target, co);
+}
+
+void space_transform_invert(const SpaceTransform *data, float *co)
+{
+ VecMat4MulVecfl(co, ((SpaceTransform*)data)->target2local, co);
+}
+
+void space_transform_apply_normal(const SpaceTransform *data, float *no)
+{
+ Mat4Mul3Vecfl( ((SpaceTransform*)data)->local2target, no);
+ Normalize(no); // TODO: could we just determine de scale value from the matrix?
+}
+
+void space_transform_invert_normal(const SpaceTransform *data, float *no)
+{
+ Mat4Mul3Vecfl(((SpaceTransform*)data)->target2local, no);
+ Normalize(no); // TODO: could we just determine de scale value from the matrix?
+}
+
+/*
+ * Returns the squared distance between two given points
+ */
+static float squared_dist(const float *a, const float *b)
+{
+ float tmp[3];
+ VECSUB(tmp, a, b);
+ return INPR(tmp, tmp);
+}
+
+/* Main shrinkwrap function */
+void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob, DerivedMesh *dm, float (*vertexCos)[3], int numVerts)
+{
+
+ ShrinkwrapCalcData calc = NULL_ShrinkwrapCalcData;
+
+ //remove loop dependencies on derived meshs (TODO should this be done elsewhere?)
+ if(smd->target == ob) smd->target = NULL;
+ if(smd->auxTarget == ob) smd->auxTarget = NULL;
+
+
+ //Configure Shrinkwrap calc data
+ calc.smd = smd;
+ calc.ob = ob;
+ calc.original = dm;
+ calc.numVerts = numVerts;
+ calc.vertexCos = vertexCos;
+
+ //DeformVertex
+ calc.vgroup = get_named_vertexgroup_num(calc.ob, calc.smd->vgroup_name);
+ if(calc.original)
+ {
+ calc.dvert = calc.original->getVertDataArray(calc.original, CD_MDEFORMVERT);
+ }
+ else if(calc.ob->type == OB_LATTICE)
+ {
+ calc.dvert = lattice_get_deform_verts(calc.ob);
+ }
+
+
+ if(smd->target)
+ {
+ //TODO currently we need a copy in case object_get_derived_final returns an emDM that does not defines getVertArray or getFace array
+ calc.target = CDDM_copy( object_get_derived_final(smd->target, CD_MASK_BAREMESH) );
+
+ //TODO there might be several "bugs" on non-uniform scales matrixs.. because it will no longer be nearest surface, not sphere projection
+ //because space has been deformed
+ space_transform_setup(&calc.local2target, ob, smd->target);
+
+ calc.keepDist = smd->keepDist; //TODO: smd->keepDist is in global units.. must change to local
+ }
+
+
+ //Projecting target defined - lets work!
+ if(calc.target)
+ {
+ switch(smd->shrinkType)
+ {
+ case MOD_SHRINKWRAP_NEAREST_SURFACE:
+ BENCH(shrinkwrap_calc_nearest_surface_point(&calc));
+ break;
+
+ case MOD_SHRINKWRAP_PROJECT:
+ BENCH(shrinkwrap_calc_normal_projection(&calc));
+ break;
+
+ case MOD_SHRINKWRAP_NEAREST_VERTEX:
+ BENCH(shrinkwrap_calc_nearest_vertex(&calc));
+ break;
+ }
+ }
+
+ //free memory
+ if(calc.target)
+ calc.target->release( calc.target );
+}
+
+/*
+ * Shrinkwrap to the nearest vertex
+ *
+ * it builds a kdtree of vertexs we can attach to and then
+ * for each vertex performs a nearest vertex search on the tree
+ */
+void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc)
+{
+ int i;
+
+ BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
+ BVHTreeNearest nearest = NULL_BVHTreeNearest;
+
+
+ BENCH(bvhtree_from_mesh_verts(&treeData, calc->target, 0.0, 2, 6));
+ if(treeData.tree == NULL)
+ {
+ OUT_OF_MEMORY();
+ return;
+ }
+
+ //Setup nearest
+ nearest.index = -1;
+ nearest.dist = FLT_MAX;
+
+#pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(treeData,calc) schedule(static)
+ for(i = 0; i<calc->numVerts; ++i)
+ {
+ float *co = calc->vertexCos[i];
+ float tmp_co[3];
+ float weight = vertexgroup_get_vertex_weight(calc->dvert, i, calc->vgroup);
+ if(weight == 0.0f) continue;
+
+ VECCOPY(tmp_co, co);
+ space_transform_apply(&calc->local2target, tmp_co); //Convert the coordinates to the tree coordinates
+
+ //Use local proximity heuristics (to reduce the nearest search)
+ //
+ //If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
+ //so we can initiate the "nearest.dist" with the expected value to that last hit.
+ //This will lead in prunning of the search tree.
+ if(nearest.index != -1)
+ nearest.dist = squared_dist(tmp_co, nearest.co);
+ else
+ nearest.dist = FLT_MAX;
+
+ BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);
+
+
+ //Found the nearest vertex
+ if(nearest.index != -1)
+ {
+ //Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position
+ float dist = sasqrt(nearest.dist);
+ if(dist > FLT_EPSILON) weight *= (dist - calc->keepDist)/dist;
+
+ //Convert the coordinates back to mesh coordinates
+ VECCOPY(tmp_co, nearest.co);
+ space_transform_invert(&calc->local2target, tmp_co);
+
+ VecLerpf(co, co, tmp_co, weight); //linear interpolation
+ }
+ }
+
+ free_bvhtree_from_mesh(&treeData);
+}
+
+/*
+ * This function raycast a single vertex and updates the hit if the "hit" is considered valid.
+ * Returns TRUE if "hit" was updated.
+ * Opts control whether an hit is valid or not
+ * Supported options are:
+ * MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE (front faces hits are ignored)
+ * MOD_SHRINKWRAP_CULL_TARGET_BACKFACE (back faces hits are ignored)
+ */
+int normal_projection_project_vertex(char options, const float *vert, const float *dir, const SpaceTransform *transf, BVHTree *tree, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata)
+{
+ float tmp_co[3], tmp_no[3];
+ const float *co, *no;
+ BVHTreeRayHit hit_tmp;
+
+ //Copy from hit (we need to convert hit rays from one space coordinates to the other
+ memcpy( &hit_tmp, hit, sizeof(hit_tmp) );
+
+ //Apply space transform (TODO readjust dist)
+ if(transf)
+ {
+ VECCOPY( tmp_co, vert );
+ space_transform_apply( transf, tmp_co );
+ co = tmp_co;
+
+ VECCOPY( tmp_no, dir );
+ space_transform_apply_normal( transf, tmp_no );
+ no = tmp_no;
+
+ hit_tmp.dist *= Mat4ToScalef( ((SpaceTransform*)transf)->local2target );
+ }
+ else
+ {
+ co = vert;
+ no = dir;
+ }
+
+ hit_tmp.index = -1;
+
+ BLI_bvhtree_ray_cast(tree, co, no, 0.0f, &hit_tmp, callback, userdata);
+
+ if(hit_tmp.index != -1)
+ {
+ float dot = INPR( dir, hit_tmp.no);
+
+ if(((options & MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE) && dot <= 0.0f)
+ || ((options & MOD_SHRINKWRAP_CULL_TARGET_BACKFACE) && dot >= 0.0f))
+ return FALSE; //Ignore hit
+
+
+ //Inverting space transform (TODO make coeherent with the initial dist readjust)
+ if(transf)
+ {
+ space_transform_invert( transf, hit_tmp.co );
+ space_transform_invert_normal( transf, hit_tmp.no );
+
+ hit_tmp.dist = VecLenf( (float*)vert, hit_tmp.co );
+ }
+
+ memcpy(hit, &hit_tmp, sizeof(hit_tmp) );
+ return TRUE;
+ }
+ return FALSE;
+}
+
+
+void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc)
+{
+ int i;
+
+ //Options about projection direction
+ const char use_normal = calc->smd->shrinkOpts;
+ float proj_axis[3] = {0.0f, 0.0f, 0.0f};
+ MVert *vert = NULL; //Needed in case of vertex normal
+ DerivedMesh* ss_mesh = NULL;
+
+ //Raycast and tree stuff
+ BVHTreeRayHit hit;
+ BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh; //target
+
+ //auxiliar target
+ DerivedMesh * aux_mesh = NULL;
+ BVHTreeFromMesh auxData= NULL_BVHTreeFromMesh;
+ SpaceTransform local2aux;
+
+do
+{
+
+ //Prepare data to retrieve the direction in which we should project each vertex
+ if(calc->smd->projAxis == MOD_SHRINKWRAP_PROJECT_OVER_NORMAL)
+ {
+ //No Mvert information: jump to "free memory and return" part
+ if(calc->original == NULL) break;
+
+ if(calc->smd->subsurfLevels)
+ {
+ SubsurfModifierData smd;
+ memset(&smd, 0, sizeof(smd));
+ smd.subdivType = ME_CC_SUBSURF; //catmull clark
+ smd.levels = calc->smd->subsurfLevels; //levels
+
+ ss_mesh = subsurf_make_derived_from_derived(calc->original, &smd, FALSE, NULL, 0, 0);
+
+ if(ss_mesh)
+ {
+ vert = ss_mesh->getVertDataArray(ss_mesh, CD_MVERT);
+ if(vert)
+ {
+ //TRICKY: this code assumes subsurface will have the transformed original vertices
+ //in their original order at the end of the vert array.
+ vert = vert
+ + ss_mesh->getNumVerts(ss_mesh)
+ - calc->original->getNumVerts(calc->original);
+ }
+ }
+
+ //To make sure we are not letting any memory behind
+ assert(smd.emCache == NULL);
+ assert(smd.mCache == NULL);
+ }
+ else
+ vert = calc->original->getVertDataArray(calc->original, CD_MVERT);
+
+ //Not able to get vert information: jump to "free memory and return" part
+ if(vert == NULL) break;
+ }
+ else
+ {
+ //The code supports any axis that is a combination of X,Y,Z.. altought currently UI only allows to set the 3 diferent axis
+ if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_X_AXIS) proj_axis[0] = 1.0f;
+ if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Y_AXIS) proj_axis[1] = 1.0f;
+ if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Z_AXIS) proj_axis[2] = 1.0f;
+
+ Normalize(proj_axis);
+
+ //Invalid projection direction: jump to "free memory and return" part
+ if(INPR(proj_axis, proj_axis) < FLT_EPSILON) break;
+ }
+
+ //If the user doesn't allows to project in any direction of projection axis... then theres nothing todo.
+ if((use_normal & (MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR | MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR)) == 0)
+ break; //jump to "free memory and return" part
+
+
+ //Build target tree
+ BENCH(bvhtree_from_mesh_faces(&treeData, calc->target, calc->keepDist, 4, 6));
+ if(treeData.tree == NULL)
+ break; //jump to "free memory and return" part
+
+
+ //Build auxiliar target
+ if(calc->smd->auxTarget)
+ {
+ space_transform_setup( &local2aux, calc->ob, calc->smd->auxTarget);
+
+ aux_mesh = CDDM_copy( object_get_derived_final(calc->smd->auxTarget, CD_MASK_BAREMESH) ); //TODO currently we need a copy in case object_get_derived_final returns an emDM that does not defines getVertArray or getFace array
+ if(aux_mesh)
+ BENCH(bvhtree_from_mesh_faces(&auxData, aux_mesh, 0.0, 4, 6));
+ else
+ printf("Auxiliar target finalDerived mesh is null\n");
+ }
+
+
+ //Now, everything is ready to project the vertexs!
+#pragma omp parallel for private(i,hit) schedule(static)
+ for(i = 0; i<calc->numVerts; ++i)
+ {
+ float *co = calc->vertexCos[i];
+ float tmp_co[3], tmp_no[3];
+ float lim = 10000.0f; //TODO: we should use FLT_MAX here, but sweepsphere code isnt prepared for that
+ float weight = vertexgroup_get_vertex_weight(calc->dvert, i, calc->vgroup);
+
+ if(weight == 0.0f) continue;
+
+ if(ss_mesh)
+ {
+ VECCOPY(tmp_co, vert[i].co);
+ }
+ else
+ {
+ VECCOPY(tmp_co, co);
+ }
+
+
+ if(vert)
+ NormalShortToFloat(tmp_no, vert[i].no);
+ else
+ VECCOPY( tmp_no, proj_axis );
+
+
+ hit.index = -1;
+ hit.dist = lim;
+
+
+ //Project over positive direction of axis
+ if(use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR)
+ {
+
+ if(auxData.tree)
+ normal_projection_project_vertex(0, tmp_co, tmp_no, &local2aux, auxData.tree, &hit, auxData.raycast_callback, &auxData);
+
+ normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, tmp_no, &calc->local2target, treeData.tree, &hit, treeData.raycast_callback, &treeData);
+ }
+
+ //Project over negative direction of axis
+ if(use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR)
+ {
+ float inv_no[3] = { -tmp_no[0], -tmp_no[1], -tmp_no[2] };
+
+
+ if(auxData.tree)
+ normal_projection_project_vertex(0, tmp_co, inv_no, &local2aux, auxData.tree, &hit, auxData.raycast_callback, &auxData);
+
+ normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, inv_no, &calc->local2target, treeData.tree, &hit, treeData.raycast_callback, &treeData);
+ }
+
+
+ if(hit.index != -1)
+ {
+ VecLerpf(co, co, hit.co, weight);
+ }
+ }
+
+
+//Simple do{} while(0) structure to allow to easily jump to the "free memory and return" part
+} while(0);
+
+ //free data structures
+
+ free_bvhtree_from_mesh(&treeData);
+ free_bvhtree_from_mesh(&auxData);
+
+ if(aux_mesh)
+ aux_mesh->release(aux_mesh);
+
+ if(ss_mesh)
+ ss_mesh->release(ss_mesh);
+}
+
+/*
+ * Shrinkwrap moving vertexs to the nearest surface point on the target
+ *
+ * it builds a BVHTree from the target mesh and then performs a
+ * NN matchs for each vertex
+ */
+void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc)
+{
+ int i;
+
+ BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
+ BVHTreeNearest nearest = NULL_BVHTreeNearest;
+
+
+
+ //Create a bvh-tree of the given target
+ BENCH(bvhtree_from_mesh_faces( &treeData, calc->target, 0.0, 2, 6));
+ if(treeData.tree == NULL)
+ {
+ OUT_OF_MEMORY();
+ return;
+ }
+
+ //Setup nearest
+ nearest.index = -1;
+ nearest.dist = FLT_MAX;
+
+
+ //Find the nearest vertex
+#pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(calc,treeData) schedule(static)
+ for(i = 0; i<calc->numVerts; ++i)
+ {
+ float *co = calc->vertexCos[i];
+ float tmp_co[3];
+ float weight = vertexgroup_get_vertex_weight(calc->dvert, i, calc->vgroup);
+ if(weight == 0.0f) continue;
+
+ //Convert the vertex to tree coordinates
+ VECCOPY(tmp_co, co);
+ space_transform_apply(&calc->local2target, tmp_co);
+
+ //Use local proximity heuristics (to reduce the nearest search)
+ //
+ //If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
+ //so we can initiate the "nearest.dist" with the expected value to that last hit.
+ //This will lead in prunning of the search tree.
+ if(nearest.index != -1)
+ nearest.dist = squared_dist(tmp_co, nearest.co);
+ else
+ nearest.dist = FLT_MAX;
+
+ BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);
+
+ //Found the nearest vertex
+ if(nearest.index != -1)
+ {
+ if(calc->smd->shrinkOpts & MOD_SHRINKWRAP_KEEP_ABOVE_SURFACE)
+ {
+ //Make the vertex stay on the front side of the face
+ VECADDFAC(tmp_co, nearest.co, nearest.no, calc->keepDist);
+ }
+ else
+ {
+ //Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position
+ float dist = sasqrt( nearest.dist );
+ if(dist > FLT_EPSILON)
+ VecLerpf(tmp_co, tmp_co, nearest.co, (dist - calc->keepDist)/dist); //linear interpolation
+ else
+ VECCOPY( tmp_co, nearest.co );
+ }
+
+ //Convert the coordinates back to mesh coordinates
+ space_transform_invert(&calc->local2target, tmp_co);
+ VecLerpf(co, co, tmp_co, weight); //linear interpolation
+ }
+ }
+
+
+ free_bvhtree_from_mesh(&treeData);
+}
+
diff --git a/source/blender/blenkernel/intern/simple_deform.c b/source/blender/blenkernel/intern/simple_deform.c
new file mode 100644
index 00000000000..2978a6f7f01
--- /dev/null
+++ b/source/blender/blenkernel/intern/simple_deform.c
@@ -0,0 +1,256 @@
+/**
+ * deform_simple.c
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): André Pinto
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#include "DNA_object_types.h"
+#include "DNA_modifier_types.h"
+#include "DNA_meshdata_types.h"
+
+#include "BKE_simple_deform.h"
+#include "BKE_DerivedMesh.h"
+#include "BKE_lattice.h"
+#include "BKE_deform.h"
+#include "BKE_utildefines.h"
+#include "BLI_arithb.h"
+#include "BKE_shrinkwrap.h"
+
+#include <string.h>
+#include <math.h>
+
+
+//Clamps/Limits the given coordinate to: limits[0] <= co[axis] <= limits[1]
+//The ammount of clamp is saved on dcut
+static void axis_limit(int axis, const float limits[2], float co[3], float dcut[3])
+{
+ float val = co[axis];
+ if(limits[0] > val) val = limits[0];
+ if(limits[1] < val) val = limits[1];
+
+ dcut[axis] = co[axis] - val;
+ co[axis] = val;
+}
+
+static void simpleDeform_taper(const float factor, const float dcut[3], float *co)
+{
+ float x = co[0], y = co[1], z = co[2];
+ float scale = z*factor;
+
+ co[0] = x + x*scale;
+ co[1] = y + y*scale;
+ co[2] = z;
+
+ if(dcut)
+ {
+ co[0] += dcut[0];
+ co[1] += dcut[1];
+ co[2] += dcut[2];
+ }
+}
+
+static void simpleDeform_stretch(const float factor, const float dcut[3], float *co)
+{
+ float x = co[0], y = co[1], z = co[2];
+ float scale;
+
+ scale = (z*z*factor-factor + 1.0);
+
+ co[0] = x*scale;
+ co[1] = y*scale;
+ co[2] = z*(1.0+factor);
+
+
+ if(dcut)
+ {
+ co[0] += dcut[0];
+ co[1] += dcut[1];
+ co[2] += dcut[2];
+ }
+}
+
+static void simpleDeform_twist(const float factor, const float *dcut, float *co)
+{
+ float x = co[0], y = co[1], z = co[2];
+ float theta, sint, cost;
+
+ theta = z*factor;
+ sint = sin(theta);
+ cost = cos(theta);
+
+ co[0] = x*cost - y*sint;
+ co[1] = x*sint + y*cost;
+ co[2] = z;
+
+ if(dcut)
+ {
+ co[0] += dcut[0];
+ co[1] += dcut[1];
+ co[2] += dcut[2];
+ }
+}
+
+static void simpleDeform_bend(const float factor, const float dcut[3], float *co)
+{
+ float x = co[0], y = co[1], z = co[2];
+ float theta, sint, cost;
+
+ theta = x*factor;
+ sint = sin(theta);
+ cost = cos(theta);
+
+ if(fabs(factor) > 1e-7f)
+ {
+ co[0] = -(y-1.0f/factor)*sint;
+ co[1] = (y-1.0f/factor)*cost + 1.0f/factor;
+ co[2] = z;
+ }
+
+
+ if(dcut)
+ {
+ co[0] += cost*dcut[0];
+ co[1] += sint*dcut[0];
+ co[2] += dcut[2];
+ }
+
+}
+
+
+/* simple deform modifier */
+void SimpleDeformModifier_do(SimpleDeformModifierData *smd, struct Object *ob, struct DerivedMesh *dm, float (*vertexCos)[3], int numVerts)
+{
+ static const float lock_axis[2] = {0.0f, 0.0f};
+
+ int i;
+ int limit_axis = 0;
+ float smd_limit[2], smd_factor;
+ SpaceTransform *transf = NULL, tmp_transf;
+ void (*simpleDeform_callback)(const float factor, const float dcut[3], float *co) = NULL; //Mode callback
+ int vgroup = get_named_vertexgroup_num(ob, smd->vgroup_name);
+ MDeformVert *dvert = NULL;
+
+ //Safe-check
+ if(smd->origin == ob) smd->origin = NULL; //No self references
+
+ if(smd->limit[0] < 0.0) smd->limit[0] = 0.0f;
+ if(smd->limit[0] > 1.0) smd->limit[0] = 1.0f;
+
+ smd->limit[0] = MIN2(smd->limit[0], smd->limit[1]); //Upper limit >= than lower limit
+
+ //Calculate matrixs do convert between coordinate spaces
+ if(smd->origin)
+ {
+ transf = &tmp_transf;
+
+ if(smd->originOpts & MOD_SIMPLEDEFORM_ORIGIN_LOCAL)
+ {
+ space_transform_from_matrixs(transf, ob->obmat, smd->origin->obmat);
+ }
+ else
+ {
+ Mat4CpyMat4(transf->local2target, smd->origin->obmat);
+ Mat4Invert(transf->target2local, transf->local2target);
+ }
+ }
+
+ //Setup vars
+ limit_axis = (smd->mode == MOD_SIMPLEDEFORM_MODE_BEND) ? 0 : 2; //Bend limits on X.. all other modes limit on Z
+
+ //Update limits if needed
+ {
+ float lower = FLT_MAX;
+ float upper = -FLT_MAX;
+
+ for(i=0; i<numVerts; i++)
+ {
+ float tmp[3];
+ VECCOPY(tmp, vertexCos[i]);
+
+ if(transf) space_transform_apply(transf, tmp);
+
+ lower = MIN2(lower, tmp[limit_axis]);
+ upper = MAX2(upper, tmp[limit_axis]);
+ }
+
+
+ //SMD values are normalized to the BV, calculate the absolut values
+ smd_limit[1] = lower + (upper-lower)*smd->limit[1];
+ smd_limit[0] = lower + (upper-lower)*smd->limit[0];
+
+ smd_factor = smd->factor / MAX2(FLT_EPSILON, smd_limit[1]-smd_limit[0]);
+ }
+
+
+ if(dm)
+ {
+ dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
+ }
+ else if(ob->type == OB_LATTICE)
+ {
+ dvert = lattice_get_deform_verts(ob);
+ }
+
+
+
+ switch(smd->mode)
+ {
+ case MOD_SIMPLEDEFORM_MODE_TWIST: simpleDeform_callback = simpleDeform_twist; break;
+ case MOD_SIMPLEDEFORM_MODE_BEND: simpleDeform_callback = simpleDeform_bend; break;
+ case MOD_SIMPLEDEFORM_MODE_TAPER: simpleDeform_callback = simpleDeform_taper; break;
+ case MOD_SIMPLEDEFORM_MODE_STRETCH: simpleDeform_callback = simpleDeform_stretch; break;
+ default:
+ return; //No simpledeform mode?
+ }
+
+ for(i=0; i<numVerts; i++)
+ {
+ float weight = vertexgroup_get_vertex_weight(dvert, i, vgroup);
+
+ if(weight != 0.0f)
+ {
+ float co[3], dcut[3] = {0.0f, 0.0f, 0.0f};
+
+ if(transf) space_transform_apply(transf, vertexCos[i]);
+
+ VECCOPY(co, vertexCos[i]);
+
+ //Apply axis limits
+ if(smd->mode != MOD_SIMPLEDEFORM_MODE_BEND) //Bend mode shoulnt have any lock axis
+ {
+ if(smd->axis & MOD_SIMPLEDEFORM_LOCK_AXIS_X) axis_limit(0, lock_axis, co, dcut);
+ if(smd->axis & MOD_SIMPLEDEFORM_LOCK_AXIS_Y) axis_limit(1, lock_axis, co, dcut);
+ }
+ axis_limit(limit_axis, smd_limit, co, dcut);
+
+ simpleDeform_callback(smd_factor, dcut, co); //Apply deform
+ VecLerpf(vertexCos[i], vertexCos[i], co, weight); //Use vertex weight has coef of linear interpolation
+
+ if(transf) space_transform_invert(transf, vertexCos[i]);
+ }
+ }
+}
+
+
diff --git a/source/blender/blenkernel/intern/softbody.c b/source/blender/blenkernel/intern/softbody.c
index ac56d876df7..1ae547ba7b8 100644
--- a/source/blender/blenkernel/intern/softbody.c
+++ b/source/blender/blenkernel/intern/softbody.c
@@ -69,6 +69,8 @@ variables on the UI for now
#include "BLI_blenlib.h"
#include "BLI_arithb.h"
#include "BLI_ghash.h"
+#include "BLI_threads.h"
+
#include "BKE_curve.h"
#include "BKE_effect.h"
#include "BKE_global.h"
@@ -84,6 +86,7 @@ variables on the UI for now
//XXX #include "BIF_editdeform.h"
//XXX #include "BIF_graphics.h"
#include "PIL_time.h"
+// #include "ONL_opennl.h" remove linking to ONL for now
/* callbacks for errors and interrupts and some goo */
static int (*SB_localInterruptCallBack)(void) = NULL;
@@ -94,7 +97,7 @@ static int (*SB_localInterruptCallBack)(void) = NULL;
typedef struct BodySpring {
int v1, v2;
- float len, strength, cf;
+ float len, strength, cf,load;
float ext_force[3]; /* edges colliding and sailing */
short order;
short flag;
@@ -102,7 +105,7 @@ typedef struct BodySpring {
typedef struct BodyFace {
int v1, v2, v3 ,v4;
- float ext_force[3]; /* edges colliding and sailing */
+ float ext_force[3]; /* faces colliding */
short flag;
} BodyFace;
@@ -117,6 +120,25 @@ typedef struct SBScratch {
float aabbmin[3],aabbmax[3];
}SBScratch;
+typedef struct SB_thread_context{
+ Object *ob;
+ float forcetime;
+ float timenow;
+ int ifirst;
+ int ilast;
+ ListBase *do_effector;
+ int do_deflector;
+ float fieldfactor;
+ float windfactor;
+ int nr;
+ int tot;
+}SB_thread_context;
+
+#define NLF_BUILD 1
+#define NLF_SOLVE 2
+
+#define MID_PRESERVE 1
+
#define SOFTGOALSNAP 0.999f
/* if bp-> goal is above make it a *forced follow original* and skip all ODE stuff for this bp
removes *unnecessary* stiffnes from ODE system
@@ -126,7 +148,9 @@ typedef struct SBScratch {
#define BSF_INTERSECT 1 /* edge intersects collider face */
#define SBF_DOFUZZY 1 /* edge intersects collider face */
-#define BFF_INTERSECT 1 /* edge intersects collider face */
+
+#define BFF_INTERSECT 1 /* collider edge intrudes face */
+#define BFF_CLOSEVERT 2 /* collider vertex repulses face */
float SoftHeunTol = 1.0f; /* humm .. this should be calculated from sb parameters and sizes */
@@ -212,7 +236,7 @@ typedef struct ccd_Mesh {
-ccd_Mesh *ccd_mesh_make(Object *ob, DerivedMesh *dm)
+static ccd_Mesh *ccd_mesh_make(Object *ob, DerivedMesh *dm)
{
ccd_Mesh *pccd_M = NULL;
ccdf_minmax *mima =NULL;
@@ -309,7 +333,7 @@ ccd_Mesh *ccd_mesh_make(Object *ob, DerivedMesh *dm)
}
return pccd_M;
}
-void ccd_mesh_update(Object *ob,ccd_Mesh *pccd_M, DerivedMesh *dm)
+static void ccd_mesh_update(Object *ob,ccd_Mesh *pccd_M, DerivedMesh *dm)
{
ccdf_minmax *mima =NULL;
MFace *mface=NULL;
@@ -448,7 +472,7 @@ void ccd_mesh_update(Object *ob,ccd_Mesh *pccd_M, DerivedMesh *dm)
return ;
}
-void ccd_mesh_free(ccd_Mesh *ccdm)
+static void ccd_mesh_free(ccd_Mesh *ccdm)
{
if(ccdm && (ccdm->savety == CCD_SAVETY )){ /*make sure we're not nuking objects we don't know*/
MEM_freeN(ccdm->mface);
@@ -460,7 +484,7 @@ void ccd_mesh_free(ccd_Mesh *ccdm)
}
}
-void ccd_build_deflector_hache(Object *vertexowner,GHash *hash)
+static void ccd_build_deflector_hache(Object *vertexowner,GHash *hash)
{
Base *base;
Object *ob;
@@ -512,7 +536,7 @@ void ccd_build_deflector_hache(Object *vertexowner,GHash *hash)
} /* while (base) */
}
-void ccd_update_deflector_hache(Object *vertexowner,GHash *hash)
+static void ccd_update_deflector_hache(Object *vertexowner,GHash *hash)
{
Base *base;
Object *ob;
@@ -582,6 +606,7 @@ static void add_mesh_quad_diag_springs(Object *ob)
if (ob->soft){
int nofquads;
+ float s_shear = ob->soft->shearstiff*ob->soft->shearstiff;
nofquads = count_mesh_quads(me);
if (nofquads) {
@@ -602,12 +627,12 @@ static void add_mesh_quad_diag_springs(Object *ob)
if(mface->v4) {
bs->v1= mface->v1;
bs->v2= mface->v3;
- bs->strength= 1.0;
+ bs->strength= s_shear;
bs->order =2;
bs++;
bs->v1= mface->v2;
bs->v2= mface->v4;
- bs->strength= 1.0;
+ bs->strength= s_shear;
bs->order =2;
bs++;
@@ -689,6 +714,7 @@ static void add_2nd_order_springs(Object *ob,float stiffness)
{
int counter = 0;
BodySpring *bs_new;
+ stiffness *=stiffness;
add_2nd_order_roller(ob,stiffness,&counter,0); /* counting */
if (counter) {
@@ -803,50 +829,6 @@ static void calculate_collision_balls(Object *ob)
}
-char set_octant_flags(float *ce, float *pos, float ball)
-{
- float x,y,z;
- char res = 0;
- int a;
-
- for (a=0;a<7;a++){
- switch(a){
- case 0: x=pos[0]; y=pos[1]; z=pos[2]; break;
- case 1: x=pos[0]+ball; y=pos[1]; z=pos[2]; break;
- case 2: x=pos[0]-ball; y=pos[1]; z=pos[2]; break;
- case 3: x=pos[0]; y=pos[1]+ball; z=pos[2]; break;
- case 4: x=pos[0]; y=pos[1]-ball; z=pos[2]; break;
- case 5: x=pos[0]; y=pos[1]; z=pos[2]+ball; break;
- case 6: x=pos[0]; y=pos[1]; z=pos[2]-ball; break;
- }
-
- x=pos[0]; y=pos[1]; z=pos[2];
-
- if (x > ce[0]){
- if (y > ce[1]){
- if (z > ce[2]) res|= 1;
- else res|= 2;
- }
- else{
- if (z > ce[2]) res|= 4;
- else res|= 8;
- }
- }
-
- else{
- if (y > ce[1]){
- if (z > ce[2]) res|= 16;
- else res|= 32;
- }
- else{
- if (z > ce[2]) res|= 64;
- else res|= 128;
- }
- }
- }
- return res;
-}
-
/* creates new softbody if didn't exist yet, makes new points and springs arrays */
static void renew_softbody(Object *ob, int totpoint, int totspring)
{
@@ -881,6 +863,8 @@ static void renew_softbody(Object *ob, int totpoint, int totspring)
bp->nofsprings= 0;
bp->springs= NULL;
bp->choke = 0.0f;
+ bp->choke2 = 0.0f;
+ bp->frozen = 1.0f;
bp->colball = 0.0f;
bp->flag = 0;
@@ -985,6 +969,7 @@ static void Vec3PlusStVec(float *v, float s, float *v1)
}
/* +++ dependancy information functions*/
+
static int are_there_deflectors(unsigned int layer)
{
Base *base;
@@ -1002,40 +987,11 @@ static int query_external_colliders(Object *me)
{
return(are_there_deflectors(me->lay));
}
-
-#if 0
-static int query_external_forces(Object *me)
-{
-/* silly but true: we need to create effector cache to see if anything is in it */
- ListBase *ec = pdInitEffectors(me,NULL);
- int result = 0;
- if (ec){
- result = 1;
- pdEndEffectors(ec); /* sorry ec, yes i'm an idiot, but i needed to know if you were there */
- }
- return result;
-}
-
-/*
-any of that external objects may have an IPO or something alike ..
-so unless we can ask them if they are moving we have to assume they do
-*/
-static int query_external_time(Object *me)
-{
- if (query_external_colliders(me)) return 1;
- if (query_external_forces(me)) return 1;
- return 0;
-}
-static int query_internal_time(Object *me)
-{
- if (me->softflag & OB_SB_GOAL) return 1;
- return 0;
-}
-#endif
/* --- dependancy information functions*/
+
/* +++ the aabb "force" section*/
-int sb_detect_aabb_collisionCached( float force[3], unsigned int par_layer,struct Object *vertexowner,float time)
+static int sb_detect_aabb_collisionCached( float force[3], unsigned int par_layer,struct Object *vertexowner,float time)
{
Object *ob;
SoftBody *sb=vertexowner->soft;
@@ -1099,15 +1055,112 @@ int sb_detect_aabb_collisionCached( float force[3], unsigned int par_layer,struc
/* +++ the face external section*/
+static int sb_detect_face_pointCached(float face_v1[3],float face_v2[3],float face_v3[3],float *damp,
+ float force[3], unsigned int par_layer,struct Object *vertexowner,float time)
+ {
+ Object *ob;
+ GHash *hash;
+ GHashIterator *ihash;
+ float nv1[3], edge1[3], edge2[3], d_nvect[3], aabbmin[3],aabbmax[3];
+ float facedist,outerfacethickness,tune = 10.f;
+ int a, deflected=0;
+
+ aabbmin[0] = MIN3(face_v1[0],face_v2[0],face_v3[0]);
+ aabbmin[1] = MIN3(face_v1[1],face_v2[1],face_v3[1]);
+ aabbmin[2] = MIN3(face_v1[2],face_v2[2],face_v3[2]);
+ aabbmax[0] = MAX3(face_v1[0],face_v2[0],face_v3[0]);
+ aabbmax[1] = MAX3(face_v1[1],face_v2[1],face_v3[1]);
+ aabbmax[2] = MAX3(face_v1[2],face_v2[2],face_v3[2]);
+
+ /* calculate face normal once again SIGH */
+ VECSUB(edge1, face_v1, face_v2);
+ VECSUB(edge2, face_v3, face_v2);
+ Crossf(d_nvect, edge2, edge1);
+ Normalize(d_nvect);
+
-int sb_detect_face_collisionCached(float face_v1[3],float face_v2[3],float face_v3[3],float *damp,
+ hash = vertexowner->soft->scratch->colliderhash;
+ ihash = BLI_ghashIterator_new(hash);
+ while (!BLI_ghashIterator_isDone(ihash) ) {
+
+ ccd_Mesh *ccdm = BLI_ghashIterator_getValue (ihash);
+ ob = BLI_ghashIterator_getKey (ihash);
+ /* only with deflecting set */
+ if(ob->pd && ob->pd->deflect) {
+ MVert *mvert= NULL;
+ MVert *mprevvert= NULL;
+ if(ccdm){
+ mvert= ccdm->mvert;
+ a = ccdm->totvert;
+ mprevvert= ccdm->mprevvert;
+ outerfacethickness =ob->pd->pdef_sboft;
+ if ((aabbmax[0] < ccdm->bbmin[0]) ||
+ (aabbmax[1] < ccdm->bbmin[1]) ||
+ (aabbmax[2] < ccdm->bbmin[2]) ||
+ (aabbmin[0] > ccdm->bbmax[0]) ||
+ (aabbmin[1] > ccdm->bbmax[1]) ||
+ (aabbmin[2] > ccdm->bbmax[2]) ) {
+ /* boxes dont intersect */
+ BLI_ghashIterator_step(ihash);
+ continue;
+ }
+
+ }
+ else{
+ /*aye that should be cached*/
+ printf("missing cache error \n");
+ BLI_ghashIterator_step(ihash);
+ continue;
+ }
+
+
+ /* use mesh*/
+ if (mvert) {
+ while(a){
+ VECCOPY(nv1,mvert[a-1].co);
+ if(mprevvert){
+ VecMulf(nv1,time);
+ Vec3PlusStVec(nv1,(1.0f-time),mprevvert[a-1].co);
+ }
+ /* origin to face_v2*/
+ VECSUB(nv1, nv1, face_v2);
+ facedist = Inpf(nv1,d_nvect);
+ if (ABS(facedist)<outerfacethickness){
+ if (point_in_tri_prism(nv1, face_v1,face_v2,face_v3) ){
+ float df;
+ if (facedist > 0){
+ df = (outerfacethickness-facedist)/outerfacethickness;
+ }
+ else {
+ df = (outerfacethickness+facedist)/outerfacethickness;
+ }
+
+ *damp=df*tune*ob->pd->pdef_sbdamp;
+
+ df = 0.01f*exp(- 100.0f*df);
+ Vec3PlusStVec(force,-df,d_nvect);
+ deflected = 3;
+ }
+ }
+ a--;
+ }/* while(a)*/
+ } /* if (mvert) */
+ } /* if(ob->pd && ob->pd->deflect) */
+ BLI_ghashIterator_step(ihash);
+ } /* while () */
+ BLI_ghashIterator_free(ihash);
+ return deflected;
+}
+
+
+static int sb_detect_face_collisionCached(float face_v1[3],float face_v2[3],float face_v3[3],float *damp,
float force[3], unsigned int par_layer,struct Object *vertexowner,float time)
{
Object *ob;
GHash *hash;
GHashIterator *ihash;
float nv1[3], nv2[3], nv3[3], nv4[3], edge1[3], edge2[3], d_nvect[3], aabbmin[3],aabbmax[3];
- float t;
+ float t,tune = 10.0f;
int a, deflected=0;
aabbmin[0] = MIN3(face_v1[0],face_v2[0],face_v3[0]);
@@ -1206,8 +1259,8 @@ int sb_detect_face_collisionCached(float face_v1[3],float face_v2[3],float face_
LineIntersectsTriangle(nv1, nv2, face_v1, face_v2, face_v3, &t, NULL) ||
LineIntersectsTriangle(nv2, nv3, face_v1, face_v2, face_v3, &t, NULL) ||
LineIntersectsTriangle(nv3, nv1, face_v1, face_v2, face_v3, &t, NULL) ){
- Vec3PlusStVec(force,-1.0f,d_nvect);
- *damp=ob->pd->pdef_sbdamp;
+ Vec3PlusStVec(force,-0.5f,d_nvect);
+ *damp=tune*ob->pd->pdef_sbdamp;
deflected = 2;
}
if (mface->v4){ /* quad */
@@ -1217,11 +1270,12 @@ int sb_detect_face_collisionCached(float face_v1[3],float face_v2[3],float face_
Crossf(d_nvect, edge2, edge1);
Normalize(d_nvect);
if (
- LineIntersectsTriangle(nv1, nv3, face_v1, face_v2, face_v3, &t, NULL) ||
+ /* LineIntersectsTriangle(nv1, nv3, face_v1, face_v2, face_v3, &t, NULL) ||
+ we did that edge allready */
LineIntersectsTriangle(nv3, nv4, face_v1, face_v2, face_v3, &t, NULL) ||
LineIntersectsTriangle(nv4, nv1, face_v1, face_v2, face_v3, &t, NULL) ){
- Vec3PlusStVec(force,-1.0f,d_nvect);
- *damp=ob->pd->pdef_sbdamp;
+ Vec3PlusStVec(force,-0.5f,d_nvect);
+ *damp=tune*ob->pd->pdef_sbdamp;
deflected = 2;
}
}
@@ -1237,12 +1291,12 @@ int sb_detect_face_collisionCached(float face_v1[3],float face_v2[3],float face_
-void scan_for_ext_face_forces(Object *ob,float timenow)
+static void scan_for_ext_face_forces(Object *ob,float timenow)
{
SoftBody *sb = ob->soft;
BodyFace *bf;
int a;
- float damp;
+ float damp=0.0f,choke=1.0f;
float tune = -10.0f;
float feedback[3];
@@ -1252,43 +1306,71 @@ void scan_for_ext_face_forces(Object *ob,float timenow)
bf = sb->scratch->bodyface;
for(a=0; a<sb->scratch->totface; a++, bf++) {
bf->ext_force[0]=bf->ext_force[1]=bf->ext_force[2]=0.0f;
+/*+++edges intruding*/
+ bf->flag &= ~BFF_INTERSECT;
feedback[0]=feedback[1]=feedback[2]=0.0f;
- bf->flag &= ~BFF_INTERSECT;
-
if (sb_detect_face_collisionCached(sb->bpoint[bf->v1].pos,sb->bpoint[bf->v2].pos, sb->bpoint[bf->v3].pos,
&damp, feedback, ob->lay ,ob , timenow)){
- Vec3PlusStVec(bf->ext_force,tune,feedback);
+ Vec3PlusStVec(sb->bpoint[bf->v1].force,tune,feedback);
+ Vec3PlusStVec(sb->bpoint[bf->v2].force,tune,feedback);
+ Vec3PlusStVec(sb->bpoint[bf->v3].force,tune,feedback);
+// Vec3PlusStVec(bf->ext_force,tune,feedback);
bf->flag |= BFF_INTERSECT;
+ choke = MIN2(MAX2(damp,choke),1.0f);
}
feedback[0]=feedback[1]=feedback[2]=0.0f;
if ((bf->v4) && (sb_detect_face_collisionCached(sb->bpoint[bf->v1].pos,sb->bpoint[bf->v3].pos, sb->bpoint[bf->v4].pos,
&damp, feedback, ob->lay ,ob , timenow))){
- Vec3PlusStVec(bf->ext_force,tune,feedback);
- bf->flag |= BFF_INTERSECT;
+ Vec3PlusStVec(sb->bpoint[bf->v1].force,tune,feedback);
+ Vec3PlusStVec(sb->bpoint[bf->v3].force,tune,feedback);
+ Vec3PlusStVec(sb->bpoint[bf->v4].force,tune,feedback);
+// Vec3PlusStVec(bf->ext_force,tune,feedback);
+ bf->flag |= BFF_INTERSECT;
+ choke = MIN2(MAX2(damp,choke),1.0f);
}
- }
+/*---edges intruding*/
+
+/*+++ close vertices*/
+ if (( bf->flag & BFF_INTERSECT)==0){
+ bf->flag &= ~BFF_CLOSEVERT;
+ tune = -1.0f;
+ feedback[0]=feedback[1]=feedback[2]=0.0f;
+ if (sb_detect_face_pointCached(sb->bpoint[bf->v1].pos,sb->bpoint[bf->v2].pos, sb->bpoint[bf->v3].pos,
+ &damp, feedback, ob->lay ,ob , timenow)){
+ Vec3PlusStVec(sb->bpoint[bf->v1].force,tune,feedback);
+ Vec3PlusStVec(sb->bpoint[bf->v2].force,tune,feedback);
+ Vec3PlusStVec(sb->bpoint[bf->v3].force,tune,feedback);
+// Vec3PlusStVec(bf->ext_force,tune,feedback);
+ bf->flag |= BFF_CLOSEVERT;
+ choke = MIN2(MAX2(damp,choke),1.0f);
+ }
-
-
+ feedback[0]=feedback[1]=feedback[2]=0.0f;
+ if ((bf->v4) && (sb_detect_face_pointCached(sb->bpoint[bf->v1].pos,sb->bpoint[bf->v3].pos, sb->bpoint[bf->v4].pos,
+ &damp, feedback, ob->lay ,ob , timenow))){
+ Vec3PlusStVec(sb->bpoint[bf->v1].force,tune,feedback);
+ Vec3PlusStVec(sb->bpoint[bf->v3].force,tune,feedback);
+ Vec3PlusStVec(sb->bpoint[bf->v4].force,tune,feedback);
+// Vec3PlusStVec(bf->ext_force,tune,feedback);
+ bf->flag |= BFF_CLOSEVERT;
+ choke = MIN2(MAX2(damp,choke),1.0f);
+ }
+ }
+/*--- close vertices*/
+ }
bf = sb->scratch->bodyface;
for(a=0; a<sb->scratch->totface; a++, bf++) {
- if ( bf->flag & BFF_INTERSECT)
+ if (( bf->flag & BFF_INTERSECT) || ( bf->flag & BFF_CLOSEVERT))
{
- VECADD(sb->bpoint[bf->v1].force,sb->bpoint[bf->v1].force,bf->ext_force);
- VECADD(sb->bpoint[bf->v2].force,sb->bpoint[bf->v2].force,bf->ext_force);
- VECADD(sb->bpoint[bf->v3].force,sb->bpoint[bf->v3].force,bf->ext_force);
+ sb->bpoint[bf->v1].choke2=MAX2(sb->bpoint[bf->v1].choke2,choke);
+ sb->bpoint[bf->v2].choke2=MAX2(sb->bpoint[bf->v2].choke2,choke);
+ sb->bpoint[bf->v3].choke2=MAX2(sb->bpoint[bf->v3].choke2,choke);
if (bf->v4){
- VECADD(sb->bpoint[bf->v4].force,sb->bpoint[bf->v4].force,bf->ext_force);
+ sb->bpoint[bf->v2].choke2=MAX2(sb->bpoint[bf->v2].choke2,choke);
}
-
- }
-
+ }
}
-
-
-
-
}
}
@@ -1297,7 +1379,7 @@ void scan_for_ext_face_forces(Object *ob,float timenow)
/* +++ the spring external section*/
-int sb_detect_edge_collisionCached(float edge_v1[3],float edge_v2[3],float *damp,
+static int sb_detect_edge_collisionCached(float edge_v1[3],float edge_v2[3],float *damp,
float force[3], unsigned int par_layer,struct Object *vertexowner,float time)
{
Object *ob;
@@ -1447,17 +1529,16 @@ int sb_detect_edge_collisionCached(float edge_v1[3],float edge_v2[3],float *damp
}
-void scan_for_ext_spring_forces(Object *ob,float timenow)
+
+static void _scan_for_ext_spring_forces(Object *ob,float timenow,int ifirst,int ilast, struct ListBase *do_effector)
{
SoftBody *sb = ob->soft;
- ListBase *do_effector;
int a;
float damp;
float feedback[3];
- do_effector= pdInitEffectors(ob,NULL);
if (sb && sb->totspring){
- for(a=0; a<sb->totspring; a++) {
+ for(a=ifirst; a<ilast; a++) {
BodySpring *bs = &sb->bspring[a];
bs->ext_force[0]=bs->ext_force[1]=bs->ext_force[2]=0.0f;
feedback[0]=feedback[1]=feedback[2]=0.0f;
@@ -1498,25 +1579,110 @@ void scan_for_ext_spring_forces(Object *ob,float timenow)
}
f = Normalize(vel);
f = -0.0001f*f*f*sb->aeroedge;
- /* todo add a nice angle dependant function */
- /* look up one at bergman scheafer */
+ /* (todo) add a nice angle dependant function done for now BUT */
+ /* still there could be some nice drag/lift function, but who needs it */
VECSUB(sp, sb->bpoint[bs->v1].pos , sb->bpoint[bs->v2].pos);
Projf(pr,vel,sp);
VECSUB(vel,vel,pr);
Normalize(vel);
- Vec3PlusStVec(bs->ext_force,f,vel);
+ if (ob->softflag & OB_SB_AERO_ANGLE){
+ Normalize(sp);
+ Vec3PlusStVec(bs->ext_force,f*(1.0f-ABS(Inpf(vel,sp))),vel);
+ }
+ else{
+ Vec3PlusStVec(bs->ext_force,f,vel); // to keep compatible with 2.45 release files
+ }
}
/* --- springs seeing wind */
}
}
}
- if(do_effector)
- pdEndEffectors(do_effector);
}
+
+
+static void scan_for_ext_spring_forces(Object *ob,float timenow)
+{
+ SoftBody *sb = ob->soft;
+ ListBase *do_effector= NULL;
+ do_effector= pdInitEffectors(ob,NULL);
+ if (sb){
+ _scan_for_ext_spring_forces(ob,timenow,0,sb->totspring,do_effector);
+ }
+ if(do_effector)
+ pdEndEffectors(do_effector);
+}
+
+static void *exec_scan_for_ext_spring_forces(void *data)
+{
+ SB_thread_context *pctx = (SB_thread_context*)data;
+ _scan_for_ext_spring_forces(pctx->ob,pctx->timenow,pctx->ifirst,pctx->ilast,pctx->do_effector);
+ return 0;
+}
+
+static void sb_sfesf_threads_run(struct Object *ob, float timenow,int totsprings,int *ptr_to_break_func())
+{
+ ListBase *do_effector = NULL;
+ ListBase threads;
+ SB_thread_context *sb_threads;
+ int i, totthread,left,dec;
+ int lowsprings =100; /* wild guess .. may increase with better thread management 'above' or even be UI option sb->spawn_cf_threads_nopts */
+
+ do_effector= pdInitEffectors(ob,NULL);
+
+ /* figure the number of threads while preventing pretty pointless threading overhead */
+ if(G.scene->r.mode & R_FIXED_THREADS)
+ totthread= G.scene->r.threads;
+ else
+ totthread= BLI_system_thread_count();
+ /* what if we got zillions of CPUs running but less to spread*/
+ while ((totsprings/totthread < lowsprings) && (totthread > 1)) {
+ totthread--;
+ }
+
+ sb_threads= MEM_callocN(sizeof(SB_thread_context)*totthread, "SBSpringsThread");
+ memset(sb_threads, 0, sizeof(SB_thread_context)*totthread);
+ left = totsprings;
+ dec = totsprings/totthread +1;
+ for(i=0; i<totthread; i++) {
+ sb_threads[i].ob = ob;
+ sb_threads[i].forcetime = 0.0; // not used here
+ sb_threads[i].timenow = timenow;
+ sb_threads[i].ilast = left;
+ left = left - dec;
+ if (left >0){
+ sb_threads[i].ifirst = left;
+ }
+ else
+ sb_threads[i].ifirst = 0;
+ sb_threads[i].do_effector = do_effector;
+ sb_threads[i].do_deflector = 0;// not used here
+ sb_threads[i].fieldfactor = 0.0f;// not used here
+ sb_threads[i].windfactor = 0.0f;// not used here
+ sb_threads[i].nr= i;
+ sb_threads[i].tot= totthread;
+ }
+ if(totthread > 1) {
+ BLI_init_threads(&threads, exec_scan_for_ext_spring_forces, totthread);
+
+ for(i=0; i<totthread; i++)
+ BLI_insert_thread(&threads, &sb_threads[i]);
+
+ BLI_end_threads(&threads);
+ }
+ else
+ exec_scan_for_ext_spring_forces(&sb_threads[0]);
+ /* clean up */
+ MEM_freeN(sb_threads);
+
+ if(do_effector)
+ pdEndEffectors(do_effector);
+}
+
+
/* --- the spring external section*/
-int choose_winner(float*w, float* pos,float*a,float*b,float*c,float*ca,float*cb,float*cc)
+static int choose_winner(float*w, float* pos,float*a,float*b,float*c,float*ca,float*cb,float*cc)
{
float mindist,cp;
int winner =1;
@@ -1543,7 +1709,7 @@ int choose_winner(float*w, float* pos,float*a,float*b,float*c,float*ca,float*cb,
-int sb_detect_vertex_collisionCached(float opco[3], float facenormal[3], float *damp,
+static int sb_detect_vertex_collisionCached(float opco[3], float facenormal[3], float *damp,
float force[3], unsigned int par_layer,struct Object *vertexowner,
float time,float vel[3], float *intrusion)
{
@@ -1833,253 +1999,6 @@ int sb_detect_vertex_collisionCached(float opco[3], float facenormal[3], float *
return deflected;
}
-/* not complete yet ..
- try to find a pos resolving all inside collisions
-*/
-#if 0 //mute it for now
-int sb_detect_vertex_collisionCachedEx(float opco[3], float facenormal[3], float *damp,
- float force[3], unsigned int par_layer,struct Object *vertexowner,
- float time,float vel[3], float *intrusion)
-{
- Object *ob;
- GHash *hash;
- GHashIterator *ihash;
- float nv1[3], nv2[3], nv3[3], nv4[3], edge1[3], edge2[3],d_nvect[3], dv1[3],ve[3],avel[3],
- vv1[3], vv2[3], vv3[3], vv4[3],
- facedist,n_mag,force_mag_norm,minx,miny,minz,maxx,maxy,maxz,
- innerfacethickness,outerfacethickness,
- closestinside,
- ee = 5.0f, ff = 0.1f, fa;
- int a, deflected=0, cavel=0;
-/* init */
- *intrusion = 0.0f;
- hash = vertexowner->soft->scratch->colliderhash;
- ihash = BLI_ghashIterator_new(hash);
-/* go */
- while (!BLI_ghashIterator_isDone(ihash) ) {
-
- ccd_Mesh *ccdm = BLI_ghashIterator_getValue (ihash);
- ob = BLI_ghashIterator_getKey (ihash);
- /* only with deflecting set */
- if(ob->pd && ob->pd->deflect) {
- MFace *mface= NULL;
- MVert *mvert= NULL;
- MVert *mprevvert= NULL;
- ccdf_minmax *mima= NULL;
-
- if(ccdm){
- mface= ccdm->mface;
- mvert= ccdm->mvert;
- mprevvert= ccdm->mprevvert;
- mima= ccdm->mima;
- a = ccdm->totface;
-
- minx =ccdm->bbmin[0];
- miny =ccdm->bbmin[1];
- minz =ccdm->bbmin[2];
-
- maxx =ccdm->bbmax[0];
- maxy =ccdm->bbmax[1];
- maxz =ccdm->bbmax[2];
-
- if ((opco[0] < minx) ||
- (opco[1] < miny) ||
- (opco[2] < minz) ||
- (opco[0] > maxx) ||
- (opco[1] > maxy) ||
- (opco[2] > maxz) ) {
- /* outside the padded boundbox --> collision object is too far away */
- BLI_ghashIterator_step(ihash);
- continue;
- }
- }
- else{
- /*aye that should be cached*/
- printf("missing cache error \n");
- BLI_ghashIterator_step(ihash);
- continue;
- }
-
- /* do object level stuff */
- /* need to have user control for that since it depends on model scale */
- innerfacethickness =-ob->pd->pdef_sbift;
- outerfacethickness =ob->pd->pdef_sboft;
- closestinside = innerfacethickness;
- fa = (ff*outerfacethickness-outerfacethickness);
- fa *= fa;
- fa = 1.0f/fa;
- avel[0]=avel[1]=avel[2]=0.0f;
- /* use mesh*/
- while (a--) {
- if (
- (opco[0] < mima->minx) ||
- (opco[0] > mima->maxx) ||
- (opco[1] < mima->miny) ||
- (opco[1] > mima->maxy) ||
- (opco[2] < mima->minz) ||
- (opco[2] > mima->maxz)
- ) {
- mface++;
- mima++;
- continue;
- }
-
- if (mvert){
-
- VECCOPY(nv1,mvert[mface->v1].co);
- VECCOPY(nv2,mvert[mface->v2].co);
- VECCOPY(nv3,mvert[mface->v3].co);
- if (mface->v4){
- VECCOPY(nv4,mvert[mface->v4].co);
- }
-
- if (mprevvert){
- /* grab the average speed of the collider vertices
- before we spoil nvX
- humm could be done once a SB steps but then we' need to store that too
- since the AABB reduced propabitlty to get here drasticallly
- it might be a nice tradeof CPU <--> memory
- */
- VECSUB(vv1,nv1,mprevvert[mface->v1].co);
- VECSUB(vv2,nv2,mprevvert[mface->v2].co);
- VECSUB(vv3,nv3,mprevvert[mface->v3].co);
- if (mface->v4){
- VECSUB(vv4,nv4,mprevvert[mface->v4].co);
- }
-
- VecMulf(nv1,time);
- Vec3PlusStVec(nv1,(1.0f-time),mprevvert[mface->v1].co);
-
- VecMulf(nv2,time);
- Vec3PlusStVec(nv2,(1.0f-time),mprevvert[mface->v2].co);
-
- VecMulf(nv3,time);
- Vec3PlusStVec(nv3,(1.0f-time),mprevvert[mface->v3].co);
-
- if (mface->v4){
- VecMulf(nv4,time);
- Vec3PlusStVec(nv4,(1.0f-time),mprevvert[mface->v4].co);
- }
- }
- }
-
- /* switch origin to be nv2*/
- VECSUB(edge1, nv1, nv2);
- VECSUB(edge2, nv3, nv2);
- VECSUB(dv1,opco,nv2); /* abuse dv1 to have vertex in question at *origin* of triangle */
-
- Crossf(d_nvect, edge2, edge1);
- n_mag = Normalize(d_nvect);
- facedist = Inpf(dv1,d_nvect);
-
- if ((facedist > closestinside) && (facedist < outerfacethickness)){
-// if ((facedist > innerfacethickness) && (facedist < outerfacethickness)){
- if (point_in_tri_prism(opco, nv1, nv2, nv3) ){
- force_mag_norm =(float)exp(-ee*facedist);
- if (facedist > outerfacethickness*ff)
- force_mag_norm =(float)force_mag_norm*fa*(facedist - outerfacethickness)*(facedist - outerfacethickness);
- *damp=ob->pd->pdef_sbdamp;
-
- if (facedist > 0.0f){
- *damp *= (1.0f - facedist/outerfacethickness);
- Vec3PlusStVec(force,force_mag_norm,d_nvect);
- if (deflected < 2){
- deflected = 1;
- if ((mprevvert) && (*damp > 0.0f)){
- choose_winner(ve,opco,nv1,nv2,nv3,vv1,vv2,vv3);
- VECADD(avel,avel,ve);
- cavel ++;
- }
- }
-
- }
- else{
- Vec3PlusStVec(force,force_mag_norm,d_nvect);
- VECCOPY(facenormal,d_nvect);
- if ((mprevvert) && (*damp > 0.0f)){
- choose_winner(avel,opco,nv1,nv2,nv3,vv1,vv2,vv3);
- cavel = 1;
- deflected = 2;
- closestinside = facedist;
- }
- }
- *intrusion = facedist;
- }
- }
- if (mface->v4){ /* quad */
- /* switch origin to be nv4 */
- VECSUB(edge1, nv3, nv4);
- VECSUB(edge2, nv1, nv4);
- VECSUB(dv1,opco,nv4); /* abuse dv1 to have vertex in question at *origin* of triangle */
-
- Crossf(d_nvect, edge2, edge1);
- n_mag = Normalize(d_nvect);
- facedist = Inpf(dv1,d_nvect);
-
- if ((facedist > innerfacethickness) && (facedist < outerfacethickness)){
- if (point_in_tri_prism(opco, nv1, nv3, nv4) ){
- force_mag_norm =(float)exp(-ee*facedist);
- if (facedist > outerfacethickness*ff)
- force_mag_norm =(float)force_mag_norm*fa*(facedist - outerfacethickness)*(facedist - outerfacethickness);
- Vec3PlusStVec(force,force_mag_norm,d_nvect);
- *damp=ob->pd->pdef_sbdamp;
-
- if (facedist > 0.0f){
- *damp *= (1.0f - facedist/outerfacethickness);
- Vec3PlusStVec(force,force_mag_norm,d_nvect);
- if (deflected < 2){
- deflected = 1;
- if ((mprevvert) && (*damp > 0.0f)){
- choose_winner(ve,opco,nv1,nv3,nv4,vv1,vv3,vv4);
- VECADD(avel,avel,ve);
- cavel ++;
- }
- }
-
- }
- else{
- Vec3PlusStVec(force,force_mag_norm,d_nvect);
- VECCOPY(facenormal,d_nvect);
- if ((mprevvert) && (*damp > 0.0f)){
- choose_winner(avel,opco,nv1,nv3,nv4,vv1,vv3,vv4);
- cavel = 1;
- deflected = 2;
- closestinside = facedist;
- }
- }
-
-
-
- *intrusion = facedist;
- }
-
- }
- }
- mface++;
- mima++;
- }/* while a */
- } /* if(ob->pd && ob->pd->deflect) */
- BLI_ghashIterator_step(ihash);
- } /* while () */
- BLI_ghashIterator_free(ihash);
- if (cavel) VecMulf(avel,1.0f/(float)cavel);
- VECCOPY(vel,avel);
-
- /* we did stay "outside" but have some close to contact forces
- just to be complete fake a face normal
- */
- if (deflected ==1){
- VECCOPY(facenormal,force);
- Normalize(facenormal);
- }
- else{
- facenormal[0] = facenormal[1] = facenormal[2] = 0.0f;
- }
- return deflected;
-}
-#endif
-
-
/* sandbox to plug in various deflection algos */
static int sb_deflect_face(Object *ob,float *actpos,float *facenormal,float *force,float *cf,float time,float *vel,float *intrusion)
@@ -2092,102 +2011,191 @@ static int sb_deflect_face(Object *ob,float *actpos,float *facenormal,float *for
return(deflected);
}
+/* hiding this for now .. but the jacobian may pop up on other tasks .. so i'd like to keep it
+static void dfdx_spring(int ia, int ic, int op, float dir[3],float L,float len,float factor)
+{
+ float m,delta_ij;
+ int i ,j;
+ if (L < len){
+ for(i=0;i<3;i++)
+ for(j=0;j<3;j++){
+ delta_ij = (i==j ? (1.0f): (0.0f));
+ m=factor*(dir[i]*dir[j] + (1-L/len)*(delta_ij - dir[i]*dir[j]));
+ nlMatrixAdd(ia+i,op+ic+j,m);
+ }
+ }
+ else{
+ for(i=0;i<3;i++)
+ for(j=0;j<3;j++){
+ m=factor*dir[i]*dir[j];
+ nlMatrixAdd(ia+i,op+ic+j,m);
+ }
+ }
+}
+
+
+static void dfdx_goal(int ia, int ic, int op, float factor)
+{
+ int i;
+ for(i=0;i<3;i++) nlMatrixAdd(ia+i,op+ic+i,factor);
+}
-static void softbody_calc_forces(Object *ob, float forcetime, float timenow)
+static void dfdv_goal(int ia, int ic,float factor)
+{
+ int i;
+ for(i=0;i<3;i++) nlMatrixAdd(ia+i,ic+i,factor);
+}
+*/
+static void sb_spring_force(Object *ob,int bpi,BodySpring *bs,float iks,float forcetime,int nl_flags)
{
-/* rule we never alter free variables :bp->vec bp->pos in here !
- * this will ruin adaptive stepsize AKA heun! (BM)
- */
+ SoftBody *sb= ob->soft; /* is supposed to be there */
+ BodyPoint *bp1,*bp2;
+
+ float dir[3],dvel[3];
+ float distance,forcefactor,kd,absvel,projvel;
+ int ia,ic;
+ /* prepare depending on which side of the spring we are on */
+ if (bpi == bs->v1){
+ bp1 = &sb->bpoint[bs->v1];
+ bp2 = &sb->bpoint[bs->v2];
+ ia =3*bs->v1;
+ ic =3*bs->v2;
+ }
+ else if (bpi == bs->v2){
+ bp1 = &sb->bpoint[bs->v2];
+ bp2 = &sb->bpoint[bs->v1];
+ ia =3*bs->v2;
+ ic =3*bs->v1;
+ }
+ else{
+ /* TODO make this debug option */
+ /**/
+ printf("bodypoint <bpi> is not attached to spring <*bs> --> sb_spring_force()\n");
+ return;
+ }
+
+ /* do bp1 <--> bp2 elastic */
+ VecSubf(dir,bp1->pos,bp2->pos);
+ distance = Normalize(dir);
+ if (bs->len < distance)
+ iks = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
+ else
+ iks = 1.0f/(1.0f-sb->inpush)-1.0f ;/* inner spring constants function */
+
+ if(bs->len > 0.0f) /* check for degenerated springs */
+ forcefactor = iks/bs->len;
+ else
+ forcefactor = iks;
+ forcefactor *= bs->strength;
+ Vec3PlusStVec(bp1->force,(bs->len - distance)*forcefactor,dir);
+
+ /* do bp1 <--> bp2 viscous */
+ VecSubf(dvel,bp1->vec,bp2->vec);
+ kd = sb->infrict * sb_fric_force_scale(ob);
+ absvel = Normalize(dvel);
+ projvel = Inpf(dir,dvel);
+ kd *= absvel * projvel;
+ Vec3PlusStVec(bp1->force,-kd,dir);
+
+ /* do jacobian stuff if needed */
+ if(nl_flags & NLF_BUILD){
+ //int op =3*sb->totpoint;
+ //float mvel = -forcetime*kd;
+ //float mpos = -forcetime*forcefactor;
+ /* depending on my pos */
+ // dfdx_spring(ia,ia,op,dir,bs->len,distance,-mpos);
+ /* depending on my vel */
+ // dfdv_goal(ia,ia,mvel); // well that ignores geometie
+ if(bp2->goal < SOFTGOALSNAP){ /* ommit this bp when it snaps */
+ /* depending on other pos */
+ // dfdx_spring(ia,ic,op,dir,bs->len,distance,mpos);
+ /* depending on other vel */
+ // dfdv_goal(ia,ia,-mvel); // well that ignores geometie
+ }
+ }
+}
+
+
+/* since this is definitely the most CPU consuming task here .. try to spread it */
+/* core function _softbody_calc_forces_slice_in_a_thread */
+/* result is int to be able to flag user break */
+static int _softbody_calc_forces_slice_in_a_thread(Object *ob, float forcetime, float timenow,int ifirst,int ilast,int *ptr_to_break_func(),ListBase *do_effector,int do_deflector,float fieldfactor, float windfactor)
+{
+ float iks;
+ int bb,do_selfcollision,do_springcollision,do_aero;
+ int number_of_points_here = ilast - ifirst;
SoftBody *sb= ob->soft; /* is supposed to be there */
BodyPoint *bp;
- BodyPoint *bproot;
- BodySpring *bs;
- ListBase *do_effector;
- float iks, ks, kd, gravity, actspringlen, forcefactor, sd[3];
- float fieldfactor = 1000.0f, windfactor = 250.0f;
- float tune = sb->ballstiff;
- int a, b, do_deflector,do_selfcollision,do_springcollision,do_aero;
-
-
- gravity = sb->grav * sb_grav_force_scale(ob);
-
+ /* intitialize */
+ if (sb) {
/* check conditions for various options */
- do_deflector= query_external_colliders(ob);
- do_effector= pdInitEffectors(ob,NULL);
+ /* +++ could be done on object level to squeeze out the last bits of it */
do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF));
do_springcollision=do_deflector && (ob->softflag & OB_SB_EDGES) &&(ob->softflag & OB_SB_EDGECOLL);
do_aero=((sb->aeroedge)&& (ob->softflag & OB_SB_EDGES));
-
- iks = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
- bproot= sb->bpoint; /* need this for proper spring addressing */
-
-
-
- if (do_springcollision || do_aero) scan_for_ext_spring_forces(ob,timenow);
- if (do_deflector) {
- float defforce[3];
- do_deflector = sb_detect_aabb_collisionCached(defforce,ob->lay,ob,timenow);
+ /* --- could be done on object level to squeeze out the last bits of it */
+ }
+ else {
+ printf("Error expected a SB here \n");
+ return (999);
}
- if (do_selfcollision ){
- float ce[3];
- VecMidf(ce,sb->scratch->aabbmax,sb->scratch->aabbmin);
- for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
- bp->octantflag = set_octant_flags(ce,bp->pos,bp->colball);
- }
+/* debugerin */
+ if (sb->totpoint < ifirst) {
+ printf("Aye 998");
+ return (998);
}
+/* debugerin */
- for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+
+ bp = &sb->bpoint[ifirst];
+ for(bb=number_of_points_here; bb>0; bb--, bp++) {
/* clear forces accumulator */
bp->force[0]= bp->force[1]= bp->force[2]= 0.0;
-
/* naive ball self collision */
/* needs to be done if goal snaps or not */
if(do_selfcollision){
int attached;
BodyPoint *obp;
+ BodySpring *bs;
int c,b;
float velcenter[3],dvel[3],def[3];
float distance;
float compare;
+ float bstune = sb->ballstiff;
- for(c=sb->totpoint, obp= sb->bpoint; c>=a; c--, obp++) {
-
- if ((bp->octantflag & obp->octantflag) == 0) continue;
-
+ for(c=sb->totpoint, obp= sb->bpoint; c>=ifirst+bb; c--, obp++) {
compare = (obp->colball + bp->colball);
VecSubf(def, bp->pos, obp->pos);
-
/* rather check the AABBoxes before ever calulating the real distance */
/* mathematically it is completly nuts, but performace is pretty much (3) times faster */
if ((ABS(def[0]) > compare) || (ABS(def[1]) > compare) || (ABS(def[2]) > compare)) continue;
-
distance = Normalize(def);
if (distance < compare ){
/* exclude body points attached with a spring */
attached = 0;
for(b=obp->nofsprings;b>0;b--){
bs = sb->bspring + obp->springs[b-1];
- if (( sb->totpoint-a == bs->v2) || ( sb->totpoint-a == bs->v1)){
+ if (( ilast-bb == bs->v2) || ( ilast-bb == bs->v1)){
attached=1;
continue;}
}
if (!attached){
- float f = tune/(distance) + tune/(compare*compare)*distance - 2.0f*tune/compare ;
+ float f = bstune/(distance) + bstune/(compare*compare)*distance - 2.0f*bstune/compare ;
VecMidf(velcenter, bp->vec, obp->vec);
VecSubf(dvel,velcenter,bp->vec);
VecMulf(dvel,sb->nodemass);
- Vec3PlusStVec(bp->force,sb->balldamp,dvel);
Vec3PlusStVec(bp->force,f*(1.0f-sb->balldamp),def);
+ Vec3PlusStVec(bp->force,sb->balldamp,dvel);
+
/* exploit force(a,b) == -force(b,a) part2/2 */
VecSubf(dvel,velcenter,obp->vec);
VecMulf(dvel,sb->nodemass);
Vec3PlusStVec(obp->force,sb->balldamp,dvel);
Vec3PlusStVec(obp->force,-f*(1.0f-sb->balldamp),def);
-
}
}
}
@@ -2197,24 +2205,26 @@ static void softbody_calc_forces(Object *ob, float forcetime, float timenow)
if(bp->goal < SOFTGOALSNAP){ /* ommit this bp when it snaps */
float auxvect[3];
float velgoal[3];
- float absvel =0, projvel= 0;
-
+
/* do goal stuff */
if(ob->softflag & OB_SB_GOAL) {
/* true elastic goal */
- VecSubf(auxvect,bp->origT,bp->pos);
+ float ks,kd;
+ VecSubf(auxvect,bp->pos,bp->origT);
ks = 1.0f/(1.0f- bp->goal*sb->goalspring)-1.0f ;
- bp->force[0]+= ks*(auxvect[0]);
- bp->force[1]+= ks*(auxvect[1]);
- bp->force[2]+= ks*(auxvect[2]);
+ bp->force[0]+= -ks*(auxvect[0]);
+ bp->force[1]+= -ks*(auxvect[1]);
+ bp->force[2]+= -ks*(auxvect[2]);
+
/* calulate damping forces generated by goals*/
VecSubf(velgoal,bp->origS, bp->origE);
kd = sb->goalfrict * sb_fric_force_scale(ob) ;
+ VecAddf(auxvect,velgoal,bp->vec);
if (forcetime > 0.0 ) { /* make sure friction does not become rocket motor on time reversal */
- bp->force[0]-= kd * (velgoal[0] + bp->vec[0]);
- bp->force[1]-= kd * (velgoal[1] + bp->vec[1]);
- bp->force[2]-= kd * (velgoal[2] + bp->vec[2]);
+ bp->force[0]-= kd * (auxvect[0]);
+ bp->force[1]-= kd * (auxvect[1]);
+ bp->force[2]-= kd * (auxvect[2]);
}
else {
bp->force[0]-= kd * (velgoal[0] - bp->vec[0]);
@@ -2224,13 +2234,15 @@ static void softbody_calc_forces(Object *ob, float forcetime, float timenow)
}
/* done goal stuff */
-
/* gravitation */
+ if (sb){
+ float gravity = sb->grav * sb_grav_force_scale(ob);
bp->force[2]-= gravity*sb->nodemass; /* individual mass of node here */
-
+ }
/* particle field & vortex */
if(do_effector) {
+ float kd;
float force[3]= {0.0f, 0.0f, 0.0f};
float speed[3]= {0.0f, 0.0f, 0.0f};
float eval_sb_fric_force_scale = sb_fric_force_scale(ob); /* just for calling function once */
@@ -2251,7 +2263,7 @@ static void softbody_calc_forces(Object *ob, float forcetime, float timenow)
}
else {
/* BP friction in media (not) moving*/
- kd= sb->mediafrict* sb_fric_force_scale(ob);
+ float kd = sb->mediafrict* sb_fric_force_scale(ob);
/* assume it to be proportional to actual velocity */
bp->force[0]-= bp->vec[0]*kd;
bp->force[1]-= bp->vec[1]*kd;
@@ -2260,40 +2272,34 @@ static void softbody_calc_forces(Object *ob, float forcetime, float timenow)
}
/* +++cached collision targets */
bp->choke = 0.0f;
+ bp->choke2 = 0.0f;
bp->flag &= ~SBF_DOFUZZY;
if(do_deflector) {
float cfforce[3],defforce[3] ={0.0f,0.0f,0.0f}, vel[3] = {0.0f,0.0f,0.0f}, facenormal[3], cf = 1.0f,intrusion;
- kd = 1.0f;
+ float kd = 1.0f;
if (sb_deflect_face(ob,bp->pos,facenormal,defforce,&cf,timenow,vel,&intrusion)){
- if (intrusion < 0.0f){
- /*bjornmose: uugh.. what an evil hack
- violation of the 'don't touch bp->pos in here' rule
- but works nice, like this-->
- we predict the solution beeing out of the collider
- in heun step No1 and leave the heun step No2 adapt to it
- so we kind of introduced a implicit solver for this case
- */
- Vec3PlusStVec(bp->pos,-intrusion,facenormal);
-
- sb->scratch->flag |= SBF_DOFUZZY;
- bp->flag |= SBF_DOFUZZY;
- bp->choke = sb->choke*0.01f;
- }
- else{
+ if (intrusion < 0.0f){
+ sb->scratch->flag |= SBF_DOFUZZY;
+ bp->flag |= SBF_DOFUZZY;
+ bp->choke = sb->choke*0.01f;
+ }
+
VECSUB(cfforce,bp->vec,vel);
Vec3PlusStVec(bp->force,-cf*50.0f,cfforce);
- }
-
- Vec3PlusStVec(bp->force,kd,defforce);
+
+ Vec3PlusStVec(bp->force,kd,defforce);
}
}
/* ---cached collision targets */
/* +++springs */
+ iks = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
if(ob->softflag & OB_SB_EDGES) {
if (sb->bspring){ /* spring list exists at all ? */
+ int b;
+ BodySpring *bs;
for(b=bp->nofsprings;b>0;b--){
bs = sb->bspring + bp->springs[b-1];
if (do_springcollision || do_aero){
@@ -2302,67 +2308,532 @@ static void softbody_calc_forces(Object *ob, float forcetime, float timenow)
bp->choke = bs->cf;
}
-
- if (( (sb->totpoint-a) == bs->v1) ){
- actspringlen= VecLenf( (bproot+bs->v2)->pos, bp->pos);
- VecSubf(sd,(bproot+bs->v2)->pos, bp->pos);
- Normalize(sd);
-
- /* friction stuff V1 */
- VecSubf(velgoal,bp->vec,(bproot+bs->v2)->vec);
- kd = sb->infrict * sb_fric_force_scale(ob);
- absvel = Normalize(velgoal);
- projvel = ABS(Inpf(sd,velgoal));
- kd *= absvel * projvel;
- Vec3PlusStVec(bp->force,-kd,velgoal);
-
- if(bs->len > 0.0f) /* check for degenerated springs */
- forcefactor = (bs->len - actspringlen)/bs->len * iks;
- else
- forcefactor = actspringlen * iks;
- forcefactor *= bs->strength;
-
- Vec3PlusStVec(bp->force,-forcefactor,sd);
-
- }
-
- if (( (sb->totpoint-a) == bs->v2) ){
- actspringlen= VecLenf( (bproot+bs->v1)->pos, bp->pos);
- VecSubf(sd,bp->pos,(bproot+bs->v1)->pos);
- Normalize(sd);
-
- /* friction stuff V2 */
- VecSubf(velgoal,bp->vec,(bproot+bs->v1)->vec);
- kd = sb->infrict * sb_fric_force_scale(ob);
- absvel = Normalize(velgoal);
- projvel = ABS(Inpf(sd,velgoal));
- kd *= absvel * projvel;
- Vec3PlusStVec(bp->force,-kd,velgoal);
-
- if(bs->len > 0.0)
- forcefactor = (bs->len - actspringlen)/bs->len * iks;
- else
- forcefactor = actspringlen * iks;
- forcefactor *= bs->strength;
- Vec3PlusStVec(bp->force,+forcefactor,sd);
- }
+ // sb_spring_force(Object *ob,int bpi,BodySpring *bs,float iks,float forcetime,int nl_flags)
+ sb_spring_force(ob,ilast-bb,bs,iks,forcetime,0);
}/* loop springs */
}/* existing spring list */
}/*any edges*/
/* ---springs */
}/*omit on snap */
}/*loop all bp's*/
+return 0; /*done fine*/
+}
+
+static void *exec_softbody_calc_forces(void *data)
+{
+ SB_thread_context *pctx = (SB_thread_context*)data;
+ _softbody_calc_forces_slice_in_a_thread(pctx->ob,pctx->forcetime,pctx->timenow,pctx->ifirst,pctx->ilast,NULL,pctx->do_effector,pctx->do_deflector,pctx->fieldfactor,pctx->windfactor);
+ return 0;
+}
+
+static void sb_cf_threads_run(struct Object *ob, float forcetime, float timenow,int totpoint,int *ptr_to_break_func(),struct ListBase *do_effector,int do_deflector,float fieldfactor, float windfactor)
+{
+ ListBase threads;
+ SB_thread_context *sb_threads;
+ int i, totthread,left,dec;
+ int lowpoints =100; /* wild guess .. may increase with better thread management 'above' or even be UI option sb->spawn_cf_threads_nopts */
+
+ /* figure the number of threads while preventing pretty pointless threading overhead */
+ if(G.scene->r.mode & R_FIXED_THREADS)
+ totthread= G.scene->r.threads;
+ else
+ totthread= BLI_system_thread_count();
+ /* what if we got zillions of CPUs running but less to spread*/
+ while ((totpoint/totthread < lowpoints) && (totthread > 1)) {
+ totthread--;
+ }
+
+ /* printf("sb_cf_threads_run spawning %d threads \n",totthread); */
+
+ sb_threads= MEM_callocN(sizeof(SB_thread_context)*totthread, "SBThread");
+ memset(sb_threads, 0, sizeof(SB_thread_context)*totthread);
+ left = totpoint;
+ dec = totpoint/totthread +1;
+ for(i=0; i<totthread; i++) {
+ sb_threads[i].ob = ob;
+ sb_threads[i].forcetime = forcetime;
+ sb_threads[i].timenow = timenow;
+ sb_threads[i].ilast = left;
+ left = left - dec;
+ if (left >0){
+ sb_threads[i].ifirst = left;
+ }
+ else
+ sb_threads[i].ifirst = 0;
+ sb_threads[i].do_effector = do_effector;
+ sb_threads[i].do_deflector = do_deflector;
+ sb_threads[i].fieldfactor = fieldfactor;
+ sb_threads[i].windfactor = windfactor;
+ sb_threads[i].nr= i;
+ sb_threads[i].tot= totthread;
+ }
+
+
+ if(totthread > 1) {
+ BLI_init_threads(&threads, exec_softbody_calc_forces, totthread);
+
+ for(i=0; i<totthread; i++)
+ BLI_insert_thread(&threads, &sb_threads[i]);
+
+ BLI_end_threads(&threads);
+ }
+ else
+ exec_softbody_calc_forces(&sb_threads[0]);
+ /* clean up */
+ MEM_freeN(sb_threads);
+}
+static void softbody_calc_forcesEx(Object *ob, float forcetime, float timenow, int nl_flags)
+{
+/* rule we never alter free variables :bp->vec bp->pos in here !
+ * this will ruin adaptive stepsize AKA heun! (BM)
+ */
+ SoftBody *sb= ob->soft; /* is supposed to be there */
+ BodyPoint *bproot;
+ ListBase *do_effector;
+ float iks, gravity;
+ float fieldfactor = 1000.0f, windfactor = 250.0f;
+ int do_deflector,do_selfcollision,do_springcollision,do_aero;
+
+ gravity = sb->grav * sb_grav_force_scale(ob);
+
+ /* check conditions for various options */
+ do_deflector= query_external_colliders(ob);
+ do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF));
+ do_springcollision=do_deflector && (ob->softflag & OB_SB_EDGES) &&(ob->softflag & OB_SB_EDGECOLL);
+ do_aero=((sb->aeroedge)&& (ob->softflag & OB_SB_EDGES));
+
+ iks = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
+ bproot= sb->bpoint; /* need this for proper spring addressing */
+
+ if (do_springcollision || do_aero)
+ sb_sfesf_threads_run(ob,timenow,sb->totspring,NULL);
+
+ /* after spring scan because it uses Effoctors too */
+ do_effector= pdInitEffectors(ob,NULL);
+
+ if (do_deflector) {
+ float defforce[3];
+ do_deflector = sb_detect_aabb_collisionCached(defforce,ob->lay,ob,timenow);
+ }
+
+ sb_cf_threads_run(ob,forcetime,timenow,sb->totpoint,NULL,do_effector,do_deflector,fieldfactor,windfactor);
/* finally add forces caused by face collision */
- if (ob->softflag & OB_SB_FACECOLL) scan_for_ext_face_forces(ob,timenow);
- /* cleanup */
+ if (ob->softflag & OB_SB_FACECOLL) scan_for_ext_face_forces(ob,timenow);
+
+ /* finish matrix and solve */
if(do_effector) pdEndEffectors(do_effector);
}
-static void softbody_apply_forces(Object *ob, float forcetime, int mode, float *err)
+
+static void softbody_calc_forces(Object *ob, float forcetime, float timenow, int nl_flags)
+{
+ /* redirection to the new threaded Version */
+ if (!(G.rt & 0x10)){ // 16
+ softbody_calc_forcesEx(ob, forcetime, timenow, nl_flags);
+ return;
+ }
+ else{
+ /* so the following will die */
+ /* |||||||||||||||||||||||||| */
+ /* VVVVVVVVVVVVVVVVVVVVVVVVVV */
+ /*backward compatibility note:
+ fixing bug [17428] which forces adaptive step size to tiny steps
+ in some situations
+ .. keeping G.rt==17 0x11 option for old files 'needing' the bug*/
+
+ /* rule we never alter free variables :bp->vec bp->pos in here !
+ * this will ruin adaptive stepsize AKA heun! (BM)
+ */
+ SoftBody *sb= ob->soft; /* is supposed to be there */
+ BodyPoint *bp;
+ BodyPoint *bproot;
+ BodySpring *bs;
+ ListBase *do_effector;
+ float iks, ks, kd, gravity;
+ float fieldfactor = 1000.0f, windfactor = 250.0f;
+ float tune = sb->ballstiff;
+ int a, b, do_deflector,do_selfcollision,do_springcollision,do_aero;
+
+
+ /* jacobian
+ NLboolean success;
+
+ if(nl_flags){
+ nlBegin(NL_SYSTEM);
+ nlBegin(NL_MATRIX);
+ }
+ */
+
+
+ gravity = sb->grav * sb_grav_force_scale(ob);
+
+ /* check conditions for various options */
+ do_deflector= query_external_colliders(ob);
+ do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF));
+ do_springcollision=do_deflector && (ob->softflag & OB_SB_EDGES) &&(ob->softflag & OB_SB_EDGECOLL);
+ do_aero=((sb->aeroedge)&& (ob->softflag & OB_SB_EDGES));
+
+ iks = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
+ bproot= sb->bpoint; /* need this for proper spring addressing */
+
+ if (do_springcollision || do_aero) scan_for_ext_spring_forces(ob,timenow);
+ /* after spring scan because it uses Effoctors too */
+ do_effector= pdInitEffectors(ob,NULL);
+
+ if (do_deflector) {
+ float defforce[3];
+ do_deflector = sb_detect_aabb_collisionCached(defforce,ob->lay,ob,timenow);
+ }
+
+ for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+ /* clear forces accumulator */
+ bp->force[0]= bp->force[1]= bp->force[2]= 0.0;
+ if(nl_flags & NLF_BUILD){
+ //int ia =3*(sb->totpoint-a);
+ //int op =3*sb->totpoint;
+ /* dF/dV = v */
+ /* jacobioan
+ nlMatrixAdd(op+ia,ia,-forcetime);
+ nlMatrixAdd(op+ia+1,ia+1,-forcetime);
+ nlMatrixAdd(op+ia+2,ia+2,-forcetime);
+
+ nlMatrixAdd(ia,ia,1);
+ nlMatrixAdd(ia+1,ia+1,1);
+ nlMatrixAdd(ia+2,ia+2,1);
+
+ nlMatrixAdd(op+ia,op+ia,1);
+ nlMatrixAdd(op+ia+1,op+ia+1,1);
+ nlMatrixAdd(op+ia+2,op+ia+2,1);
+ */
+
+
+ }
+
+ /* naive ball self collision */
+ /* needs to be done if goal snaps or not */
+ if(do_selfcollision){
+ int attached;
+ BodyPoint *obp;
+ int c,b;
+ float velcenter[3],dvel[3],def[3];
+ float distance;
+ float compare;
+
+ for(c=sb->totpoint, obp= sb->bpoint; c>=a; c--, obp++) {
+
+ //if ((bp->octantflag & obp->octantflag) == 0) continue;
+
+ compare = (obp->colball + bp->colball);
+ VecSubf(def, bp->pos, obp->pos);
+
+ /* rather check the AABBoxes before ever calulating the real distance */
+ /* mathematically it is completly nuts, but performace is pretty much (3) times faster */
+ if ((ABS(def[0]) > compare) || (ABS(def[1]) > compare) || (ABS(def[2]) > compare)) continue;
+
+ distance = Normalize(def);
+ if (distance < compare ){
+ /* exclude body points attached with a spring */
+ attached = 0;
+ for(b=obp->nofsprings;b>0;b--){
+ bs = sb->bspring + obp->springs[b-1];
+ if (( sb->totpoint-a == bs->v2) || ( sb->totpoint-a == bs->v1)){
+ attached=1;
+ continue;}
+ }
+ if (!attached){
+ float f = tune/(distance) + tune/(compare*compare)*distance - 2.0f*tune/compare ;
+
+ VecMidf(velcenter, bp->vec, obp->vec);
+ VecSubf(dvel,velcenter,bp->vec);
+ VecMulf(dvel,sb->nodemass);
+
+ Vec3PlusStVec(bp->force,f*(1.0f-sb->balldamp),def);
+ Vec3PlusStVec(bp->force,sb->balldamp,dvel);
+
+ if(nl_flags & NLF_BUILD){
+ //int ia =3*(sb->totpoint-a);
+ //int ic =3*(sb->totpoint-c);
+ //int op =3*sb->totpoint;
+ //float mvel = forcetime*sb->nodemass*sb->balldamp;
+ //float mpos = forcetime*tune*(1.0f-sb->balldamp);
+ /*some quick and dirty entries to the jacobian*/
+ //dfdx_goal(ia,ia,op,mpos);
+ //dfdv_goal(ia,ia,mvel);
+ /* exploit force(a,b) == -force(b,a) part1/2 */
+ //dfdx_goal(ic,ic,op,mpos);
+ //dfdv_goal(ic,ic,mvel);
+
+
+ /*TODO sit down an X-out the true jacobian entries*/
+ /*well does not make to much sense because the eigenvalues
+ of the jacobian go negative; and negative eigenvalues
+ on a complex iterative system z(n+1)=A * z(n)
+ give imaginary roots in the charcateristic polynom
+ --> solutions that to z(t)=u(t)* exp ( i omega t) --> oscilations we don't want here
+ where u(t) is a unknown amplitude function (worst case rising fast)
+ */
+ }
+
+ /* exploit force(a,b) == -force(b,a) part2/2 */
+ VecSubf(dvel,velcenter,obp->vec);
+ VecMulf(dvel,sb->nodemass);
+
+ Vec3PlusStVec(obp->force,sb->balldamp,dvel);
+ Vec3PlusStVec(obp->force,-f*(1.0f-sb->balldamp),def);
+
+
+ }
+ }
+ }
+ }
+ /* naive ball self collision done */
+
+ if(bp->goal < SOFTGOALSNAP){ /* ommit this bp when it snaps */
+ float auxvect[3];
+ float velgoal[3];
+
+ /* do goal stuff */
+ if(ob->softflag & OB_SB_GOAL) {
+ /* true elastic goal */
+ VecSubf(auxvect,bp->pos,bp->origT);
+ ks = 1.0f/(1.0f- bp->goal*sb->goalspring)-1.0f ;
+ bp->force[0]+= -ks*(auxvect[0]);
+ bp->force[1]+= -ks*(auxvect[1]);
+ bp->force[2]+= -ks*(auxvect[2]);
+
+ if(nl_flags & NLF_BUILD){
+ //int ia =3*(sb->totpoint-a);
+ //int op =3*(sb->totpoint);
+ /* depending on my pos */
+ //dfdx_goal(ia,ia,op,ks*forcetime);
+ }
+
+
+ /* calulate damping forces generated by goals*/
+ VecSubf(velgoal,bp->origS, bp->origE);
+ kd = sb->goalfrict * sb_fric_force_scale(ob) ;
+ VecAddf(auxvect,velgoal,bp->vec);
+
+ if (forcetime > 0.0 ) { /* make sure friction does not become rocket motor on time reversal */
+ bp->force[0]-= kd * (auxvect[0]);
+ bp->force[1]-= kd * (auxvect[1]);
+ bp->force[2]-= kd * (auxvect[2]);
+ if(nl_flags & NLF_BUILD){
+ //int ia =3*(sb->totpoint-a);
+ Normalize(auxvect);
+ /* depending on my vel */
+ //dfdv_goal(ia,ia,kd*forcetime);
+ }
+
+ }
+ else {
+ bp->force[0]-= kd * (velgoal[0] - bp->vec[0]);
+ bp->force[1]-= kd * (velgoal[1] - bp->vec[1]);
+ bp->force[2]-= kd * (velgoal[2] - bp->vec[2]);
+ }
+ }
+ /* done goal stuff */
+
+
+ /* gravitation */
+ bp->force[2]-= gravity*sb->nodemass; /* individual mass of node here */
+ //bp->force[1]-= gravity*sb->nodemass; /* individual mass of node here */
+
+
+ /* particle field & vortex */
+ if(do_effector) {
+ float force[3]= {0.0f, 0.0f, 0.0f};
+ float speed[3]= {0.0f, 0.0f, 0.0f};
+ float eval_sb_fric_force_scale = sb_fric_force_scale(ob); /* just for calling function once */
+
+ pdDoEffectors(do_effector, bp->pos, force, speed, (float)G.scene->r.cfra, 0.0f, PE_WIND_AS_SPEED);
+
+ /* apply forcefield*/
+ VecMulf(force,fieldfactor* eval_sb_fric_force_scale);
+ VECADD(bp->force, bp->force, force);
+
+ /* BP friction in moving media */
+ kd= sb->mediafrict* eval_sb_fric_force_scale;
+ bp->force[0] -= kd * (bp->vec[0] + windfactor*speed[0]/eval_sb_fric_force_scale);
+ bp->force[1] -= kd * (bp->vec[1] + windfactor*speed[1]/eval_sb_fric_force_scale);
+ bp->force[2] -= kd * (bp->vec[2] + windfactor*speed[2]/eval_sb_fric_force_scale);
+ /* now we'll have nice centrifugal effect for vortex */
+
+ }
+ else {
+ /* BP friction in media (not) moving*/
+ kd= sb->mediafrict* sb_fric_force_scale(ob);
+ /* assume it to be proportional to actual velocity */
+ bp->force[0]-= bp->vec[0]*kd;
+ bp->force[1]-= bp->vec[1]*kd;
+ bp->force[2]-= bp->vec[2]*kd;
+ /* friction in media done */
+ if(nl_flags & NLF_BUILD){
+ //int ia =3*(sb->totpoint-a);
+ /* da/dv = */
+
+ // nlMatrixAdd(ia,ia,forcetime*kd);
+ // nlMatrixAdd(ia+1,ia+1,forcetime*kd);
+ // nlMatrixAdd(ia+2,ia+2,forcetime*kd);
+ }
+
+ }
+ /* +++cached collision targets */
+ bp->choke = 0.0f;
+ bp->choke2 = 0.0f;
+ bp->flag &= ~SBF_DOFUZZY;
+ if(do_deflector) {
+ float cfforce[3],defforce[3] ={0.0f,0.0f,0.0f}, vel[3] = {0.0f,0.0f,0.0f}, facenormal[3], cf = 1.0f,intrusion;
+ kd = 1.0f;
+
+ if (sb_deflect_face(ob,bp->pos,facenormal,defforce,&cf,timenow,vel,&intrusion)){
+ if ((!nl_flags)&&(intrusion < 0.0f)){
+ if(G.rt & 0x01){ // 17 we did check for bit 0x10 before
+ /*fixing bug [17428] this forces adaptive step size to tiny steps
+ in some situations .. keeping G.rt==17 option for old files 'needing' the bug
+ */
+ /*bjornmose: uugh.. what an evil hack
+ violation of the 'don't touch bp->pos in here' rule
+ but works nice, like this-->
+ we predict the solution beeing out of the collider
+ in heun step No1 and leave the heun step No2 adapt to it
+ so we kind of introduced a implicit solver for this case
+ */
+ Vec3PlusStVec(bp->pos,-intrusion,facenormal);
+ }
+ else{
+
+ VECSUB(cfforce,bp->vec,vel);
+ Vec3PlusStVec(bp->force,-cf*50.0f,cfforce);
+ }
+
+
+ sb->scratch->flag |= SBF_DOFUZZY;
+ bp->flag |= SBF_DOFUZZY;
+ bp->choke = sb->choke*0.01f;
+ }
+ else{
+ VECSUB(cfforce,bp->vec,vel);
+ Vec3PlusStVec(bp->force,-cf*50.0f,cfforce);
+ }
+ Vec3PlusStVec(bp->force,kd,defforce);
+ if (nl_flags & NLF_BUILD){
+ // int ia =3*(sb->totpoint-a);
+ // int op =3*sb->totpoint;
+ //dfdx_goal(ia,ia,op,mpos); // don't do unless you know
+ //dfdv_goal(ia,ia,-cf);
+
+ }
+
+ }
+
+ }
+ /* ---cached collision targets */
+
+ /* +++springs */
+ if(ob->softflag & OB_SB_EDGES) {
+ if (sb->bspring){ /* spring list exists at all ? */
+ for(b=bp->nofsprings;b>0;b--){
+ bs = sb->bspring + bp->springs[b-1];
+ if (do_springcollision || do_aero){
+ VecAddf(bp->force,bp->force,bs->ext_force);
+ if (bs->flag & BSF_INTERSECT)
+ bp->choke = bs->cf;
+
+ }
+ // sb_spring_force(Object *ob,int bpi,BodySpring *bs,float iks,float forcetime,int nl_flags)
+ // rather remove nl_falgs from code .. will make things a lot cleaner
+ sb_spring_force(ob,sb->totpoint-a,bs,iks,forcetime,0);
+ }/* loop springs */
+ }/* existing spring list */
+ }/*any edges*/
+ /* ---springs */
+ }/*omit on snap */
+ }/*loop all bp's*/
+
+
+ /* finally add forces caused by face collision */
+ if (ob->softflag & OB_SB_FACECOLL) scan_for_ext_face_forces(ob,timenow);
+
+ /* finish matrix and solve */
+#if (0) // remove onl linking for now .. still i am not sure .. the jacobian can be usefull .. so keep that BM
+ if(nl_flags & NLF_SOLVE){
+ //double sct,sst=PIL_check_seconds_timer();
+ for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+ int iv =3*(sb->totpoint-a);
+ int ip =3*(2*sb->totpoint-a);
+ int n;
+ for (n=0;n<3;n++) {nlRightHandSideSet(0, iv+n, bp->force[0+n]);}
+ for (n=0;n<3;n++) {nlRightHandSideSet(0, ip+n, bp->vec[0+n]);}
+ }
+ nlEnd(NL_MATRIX);
+ nlEnd(NL_SYSTEM);
+
+ if ((G.rt == 32) && (nl_flags & NLF_BUILD))
+ {
+ printf("####MEE#####\n");
+ nlPrintMatrix();
+ }
+
+ success= nlSolveAdvanced(NULL, 1);
+
+ // nlPrintMatrix(); /* for debug purpose .. anyhow cropping B vector looks like working */
+ if(success){
+ float f;
+ int index =0;
+ /* for debug purpose .. anyhow cropping B vector looks like working */
+ if (G.rt ==32)
+ for(a=2*sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+ f=nlGetVariable(0,index);
+ printf("(%f ",f);index++;
+ f=nlGetVariable(0,index);
+ printf("%f ",f);index++;
+ f=nlGetVariable(0,index);
+ printf("%f)",f);index++;
+ }
+
+ index =0;
+ for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+ f=nlGetVariable(0,index);
+ bp->impdv[0] = f; index++;
+ f=nlGetVariable(0,index);
+ bp->impdv[1] = f; index++;
+ f=nlGetVariable(0,index);
+ bp->impdv[2] = f; index++;
+ }
+ /*
+ for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+ f=nlGetVariable(0,index);
+ bp->impdx[0] = f; index++;
+ f=nlGetVariable(0,index);
+ bp->impdx[1] = f; index++;
+ f=nlGetVariable(0,index);
+ bp->impdx[2] = f; index++;
+ }
+ */
+ }
+ else{
+ printf("Matrix inversion failed \n");
+ for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+ VECCOPY(bp->impdv,bp->force);
+ }
+
+ }
+
+ //sct=PIL_check_seconds_timer();
+ //if (sct-sst > 0.01f) printf(" implicit solver time %f %s \r",sct-sst,ob->id.name);
+ }
+ /* cleanup */
+#endif
+ if(do_effector) pdEndEffectors(do_effector);
+ }
+}
+
+static void softbody_apply_forces(Object *ob, float forcetime, int mode, float *err, int mid_flags)
{
/* time evolution */
/* actually does an explicit euler step mode == 0 */
@@ -2370,7 +2841,7 @@ static void softbody_apply_forces(Object *ob, float forcetime, int mode, float *
SoftBody *sb= ob->soft; /* is supposed to be there */
BodyPoint *bp;
float dx[3],dv[3],aabbmin[3],aabbmax[3],cm[3]={0.0f,0.0f,0.0f};
- float timeovermass;
+ float timeovermass/*,freezeloc=0.00001f,freezeforce=0.00000000001f*/;
float maxerrpos= 0.0f,maxerrvel = 0.0f;
int a,fuzzy=0;
@@ -2385,14 +2856,14 @@ static void softbody_apply_forces(Object *ob, float forcetime, int mode, float *
for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
if(bp->goal < SOFTGOALSNAP){
+ /* this makes t~ = t */
+ if(mid_flags & MID_PRESERVE) VECCOPY(dx,bp->vec);
/* so here is (v)' = a(cceleration) = sum(F_springs)/m + gravitation + some friction forces + more forces*/
/* the ( ... )' operator denotes derivate respective time */
/* the euler step for velocity then becomes */
/* v(t + dt) = v(t) + a(t) * dt */
- bp->force[0]*= timeovermass; /* individual mass of node here */
- bp->force[1]*= timeovermass;
- bp->force[2]*= timeovermass;
+ VecMulf(bp->force,timeovermass);/* individual mass of node here */
/* some nasty if's to have heun in here too */
VECCOPY(dv,bp->force);
@@ -2413,14 +2884,24 @@ static void softbody_apply_forces(Object *ob, float forcetime, int mode, float *
}
else {VECADD(bp->vec, bp->vec, bp->force);}
+ /* this makes t~ = t+dt */
+ if(!(mid_flags & MID_PRESERVE)) VECCOPY(dx,bp->vec);
+
/* so here is (x)'= v(elocity) */
/* the euler step for location then becomes */
- /* x(t + dt) = x(t) + v(t) * dt */
-
- VECCOPY(dx,bp->vec);
- dx[0]*=forcetime;
- dx[1]*=forcetime;
- dx[2]*=forcetime;
+ /* x(t + dt) = x(t) + v(t~) * dt */
+ VecMulf(dx,forcetime);
+
+ /* the freezer coming sooner or later */
+ /*
+ if ((Inpf(dx,dx)<freezeloc )&&(Inpf(bp->force,bp->force)<freezeforce )){
+ bp->frozen /=2;
+ }
+ else{
+ bp->frozen =MIN2(bp->frozen*1.05f,1.0f);
+ }
+ VecMulf(dx,bp->frozen);
+ */
/* again some nasty if's to have heun in here too */
if (mode ==1){
VECCOPY(bp->prevpos,bp->pos);
@@ -2430,7 +2911,7 @@ static void softbody_apply_forces(Object *ob, float forcetime, int mode, float *
if (mode ==2){
bp->pos[0] = bp->prevpos[0] + 0.5f * ( dx[0] + bp->prevdx[0]);
bp->pos[1] = bp->prevpos[1] + 0.5f * ( dx[1] + bp->prevdx[1]);
- bp->pos[2] = bp->prevpos[2] + 0.5f* ( dx[2] + bp->prevdx[2]);
+ bp->pos[2] = bp->prevpos[2] + 0.5f * ( dx[2] + bp->prevdx[2]);
maxerrpos = MAX2(maxerrpos,ABS(dx[0] - bp->prevdx[0]));
maxerrpos = MAX2(maxerrpos,ABS(dx[1] - bp->prevdx[1]));
maxerrpos = MAX2(maxerrpos,ABS(dx[2] - bp->prevdx[2]));
@@ -2439,10 +2920,11 @@ static void softbody_apply_forces(Object *ob, float forcetime, int mode, float *
the collider object signals to get out by pushing hard. on the other hand
we don't want to end up in deep space so we add some <viscosity>
to balance that out */
+ if (bp->choke2 > 0.0f){
+ VecMulf(bp->vec,(1.0f - bp->choke2));
+ }
if (bp->choke > 0.0f){
- bp->vec[0] = bp->vec[0]*(1.0f - bp->choke);
- bp->vec[1] = bp->vec[1]*(1.0f - bp->choke);
- bp->vec[2] = bp->vec[2]*(1.0f - bp->choke);
+ VecMulf(bp->vec,(1.0f - bp->choke));
}
}
@@ -2489,6 +2971,81 @@ static void softbody_restore_prev_step(Object *ob)
}
}
+#if 0
+static void softbody_store_step(Object *ob)
+{
+ SoftBody *sb= ob->soft; /* is supposed to be there*/
+ BodyPoint *bp;
+ int a;
+
+ for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+ VECCOPY(bp->prevvec,bp->vec);
+ VECCOPY(bp->prevpos,bp->pos);
+ }
+}
+
+
+/* used by predictors and correctors */
+static void softbody_store_state(Object *ob,float *ppos,float *pvel)
+{
+ SoftBody *sb= ob->soft; /* is supposed to be there*/
+ BodyPoint *bp;
+ int a;
+ float *pp=ppos,*pv=pvel;
+
+ for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+
+ VECCOPY(pv, bp->vec);
+ pv+=3;
+
+ VECCOPY(pp, bp->pos);
+ pp+=3;
+ }
+}
+
+/* used by predictors and correctors */
+static void softbody_retrieve_state(Object *ob,float *ppos,float *pvel)
+{
+ SoftBody *sb= ob->soft; /* is supposed to be there*/
+ BodyPoint *bp;
+ int a;
+ float *pp=ppos,*pv=pvel;
+
+ for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+
+ VECCOPY(bp->vec,pv);
+ pv+=3;
+
+ VECCOPY(bp->pos,pp);
+ pp+=3;
+ }
+}
+
+/* used by predictors and correctors */
+static void softbody_swap_state(Object *ob,float *ppos,float *pvel)
+{
+ SoftBody *sb= ob->soft; /* is supposed to be there*/
+ BodyPoint *bp;
+ int a;
+ float *pp=ppos,*pv=pvel;
+ float temp[3];
+
+ for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
+
+ VECCOPY(temp, bp->vec);
+ VECCOPY(bp->vec,pv);
+ VECCOPY(pv,temp);
+ pv+=3;
+
+ VECCOPY(temp, bp->pos);
+ VECCOPY(bp->pos,pp);
+ VECCOPY(pp,temp);
+ pp+=3;
+ }
+}
+#endif
+
+
/* care for bodypoints taken out of the 'ordinary' solver step
** because they are screwed to goal by bolts
** they just need to move along with the goal in time
@@ -2509,6 +3066,30 @@ static void softbody_apply_goalsnap(Object *ob)
}
}
+
+static void apply_spring_memory(Object *ob)
+{
+ SoftBody *sb = ob->soft;
+ BodySpring *bs;
+ BodyPoint *bp1, *bp2;
+ int a;
+ float b,l,r;
+
+ b = sb->plastic;
+ if (sb && sb->totspring){
+ for(a=0; a<sb->totspring; a++) {
+ bs = &sb->bspring[a];
+ bp1 =&sb->bpoint[bs->v1];
+ bp2 =&sb->bpoint[bs->v2];
+ l = VecLenf(bp1->pos,bp2->pos);
+ r = bs->len/l;
+ if (( r > 1.05f) || (r < 0.95)){
+ bs->len = ((100.0f - b) * bs->len + b*l)/100.0f;
+ }
+ }
+ }
+}
+
/* expects full initialized softbody */
static void interpolate_exciter(Object *ob, int timescale, int time)
{
@@ -2597,9 +3178,9 @@ static void springs_from_mesh(Object *ob)
}
/* recalculate spring length for meshes here */
- /* special hidden feature! shrink to fit */
- if (G.rt > 500){
- scale = (G.rt - 500) / 100.0f;
+ /* public version shrink to fit */
+ if (sb->springpreload != 0 ){
+ scale = sb->springpreload / 100.0f;
}
for(a=0; a<sb->totspring; a++) {
BodySpring *bs = &sb->bspring[a];
@@ -2712,7 +3293,7 @@ static void mesh_faces_to_scratch(Object *ob)
helper function to get proper spring length
when object is rescaled
*/
-float globallen(float *v1,float *v2,Object *ob)
+static float globallen(float *v1,float *v2,Object *ob)
{
float p1[3],p2[3];
VECCOPY(p1,v1);
@@ -3002,9 +3583,12 @@ static void particles_to_softbody(Object *ob)
/* renew ends with ob->soft with points and edges, also checks & makes ob->soft */
renew_softbody(ob, totpoint, totedge);
- psys->particles->bpi = 0;
- for(a=1, pa=psys->particles+1; a<psys->totpart; a++, pa++)
- pa->bpi = (pa-1)->bpi + pa->totkey;
+ /* find first BodyPoint index for each particle */
+ if(psys->totpart > 0) {
+ psys->particles->bpi = 0;
+ for(a=1, pa=psys->particles+1; a<psys->totpart; a++, pa++)
+ pa->bpi = (pa-1)->bpi + (pa-1)->totkey;
+ }
/* we always make body points */
sb= ob->soft;
@@ -3066,97 +3650,68 @@ static void softbody_to_object(Object *ob, float (*vertexCos)[3], int numVerts,
}
}
-void softbody_clear_cache(Object *ob, float framenr)
-{
- SoftBody *sb = ob->soft;
- ModifierData *md = ob->modifiers.first;
- int stack_index = -1;
- int a;
-
- if(sb==NULL) return;
-
- if(sb->particles)
- stack_index = modifiers_indexInObject(ob,(ModifierData*)psys_get_modifier(ob,sb->particles));
- else {
- for(a=0; md; md=md->next, a++) {
- if(md->type == eModifierType_Softbody) {
- stack_index = a;
- break;
- }
- }
- }
-
- BKE_ptcache_id_clear((ID *)ob, PTCACHE_CLEAR_ALL, framenr, stack_index);
-}
-static void softbody_write_cache(Object *ob, float framenr)
+void sbWriteCache(Object *ob, int framenr)
{
- FILE *fp = NULL;
- SoftBody *sb = ob->soft;
+ SoftBody *sb= ob->soft;
BodyPoint *bp;
- ModifierData *md = ob->modifiers.first;
- int stack_index = -1;
+ PTCacheID pid;
+ PTCacheFile *pf;
int a;
- if(sb->totpoint == 0) return;
-
- if(sb->particles)
- stack_index = modifiers_indexInObject(ob,(ModifierData*)psys_get_modifier(ob,sb->particles));
- else {
- for(a=0; md; md=md->next, a++) {
- if(md->type == eModifierType_Softbody) {
- stack_index = a;
- break;
- }
- }
- }
+ if(sb->totpoint == 0)
+ return;
- fp = BKE_ptcache_id_fopen((ID *)ob, 'w', framenr, stack_index);
- if(!fp) return;
+ BKE_ptcache_id_from_softbody(&pid, ob, sb);
+ pf= BKE_ptcache_file_open(&pid, PTCACHE_FILE_WRITE, framenr);
+ if(!pf)
+ return;
+
+ for(a=0, bp=sb->bpoint; a<sb->totpoint; a++, bp++)
+ BKE_ptcache_file_write_floats(pf, bp->pos, 3);
for(a=0, bp=sb->bpoint; a<sb->totpoint; a++, bp++)
- fwrite(&bp->pos, sizeof(float), 3, fp);
-
- fclose(fp);
+ BKE_ptcache_file_write_floats(pf, bp->vec, 3);
+
+ BKE_ptcache_file_close(pf);
}
+
static int softbody_read_cache(Object *ob, float framenr)
{
- FILE *fp = NULL;
- SoftBody *sb = ob->soft;
+ SoftBody *sb= ob->soft;
BodyPoint *bp;
- ModifierData *md = ob->modifiers.first;
- int stack_index = -1;
- int a, ret = 1;
+ PTCacheID pid;
+ PTCacheFile *pf;
+ int a;
- if(sb->totpoint == 0) return 0;
+ if(sb->totpoint == 0)
+ return 0;
+
+ BKE_ptcache_id_from_softbody(&pid, ob, sb);
+ pf= BKE_ptcache_file_open(&pid, PTCACHE_FILE_READ, framenr);
+ if(!pf)
+ return 0;
- if(sb->particles)
- stack_index = modifiers_indexInObject(ob,(ModifierData*)psys_get_modifier(ob,sb->particles));
- else {
- for(a=0; md; md=md->next, a++) {
- if(md->type == eModifierType_Softbody) {
- stack_index = a;
- break;
- }
+ for(a=0, bp=sb->bpoint; a<sb->totpoint; a++, bp++) {
+ if(!BKE_ptcache_file_read_floats(pf, bp->pos, 3)) {
+ BKE_ptcache_file_close(pf);
+ return 0;
}
}
- fp = BKE_ptcache_id_fopen((ID *)ob, 'r', framenr, stack_index);
- if(!fp)
- ret = 0;
- else {
- for(a=0, bp=sb->bpoint; a<sb->totpoint; a++, bp++)
- if(fread(&bp->pos, sizeof(float), 3, fp) != 3) {
- ret = 0;
- break;
- }
-
- fclose(fp);
+ for(a=0, bp=sb->bpoint; a<sb->totpoint; a++, bp++) {
+ if(!BKE_ptcache_file_read_floats(pf, bp->vec, 3)) {
+ BKE_ptcache_file_close(pf);
+ return 0;
+ }
}
- return ret;
+ BKE_ptcache_file_close(pf);
+
+ return 1;
}
+
/* +++ ************ maintaining scratch *************** */
-void sb_new_scratch(SoftBody *sb)
+static void sb_new_scratch(SoftBody *sb)
{
if (!sb) return;
sb->scratch = MEM_callocN(sizeof(SBScratch), "SBScratch");
@@ -3192,6 +3747,8 @@ SoftBody *sbNew(void)
sb->inspring= 0.5f;
sb->infrict= 0.5f;
+ /*todo backward file compat should copy inspring to inpush while reading old files*/
+ sb->inpush = 0.5f;
sb->interval= 10;
sb->sfra= G.scene->r.sfra;
@@ -3204,9 +3761,16 @@ SoftBody *sbNew(void)
sb->minloops = 10;
+ sb->maxloops = 300;
sb->choke = 3;
sb_new_scratch(sb);
+ /*todo backward file compat should set sb->shearstiff = 1.0f while reading old files*/
+ sb->shearstiff = 1.0f;
+ sb->solverflags |= SBSO_OLDERR;
+
+ sb->pointcache = BKE_ptcache_add();
+
return sb;
}
@@ -3214,14 +3778,19 @@ SoftBody *sbNew(void)
void sbFree(SoftBody *sb)
{
free_softbody_intern(sb);
+ BKE_ptcache_free(sb->pointcache);
MEM_freeN(sb);
}
+void sbFreeSimulation(SoftBody *sb)
+{
+ free_softbody_intern(sb);
+}
/* makes totally fresh start situation */
void sbObjectToSoftbody(Object *ob)
{
- ob->softflag |= OB_SB_REDO;
+ //ob->softflag |= OB_SB_REDO;
free_softbody_intern(ob->soft);
}
@@ -3245,306 +3814,408 @@ void sbSetInterruptCallBack(int (*f)(void))
SB_localInterruptCallBack = f;
}
-
-/* simulates one step. framenr is in frames */
-void sbObjectStep(Object *ob, float framenr, float (*vertexCos)[3], int numVerts)
+static void softbody_update_positions(Object *ob, SoftBody *sb, float (*vertexCos)[3], int numVerts)
{
- ParticleSystemModifierData *psmd=0;
- ParticleData *pa=0;
- SoftBody *sb;
+ ParticleSystemModifierData *psmd= NULL;
+ ParticleData *pa= NULL;
HairKey *key= NULL;
BodyPoint *bp;
+ float hairmat[4][4];
int a;
- float dtime,ctime,forcetime,err;
+
+ /* update the vertex locations */
+ if(sb->particles && sb->particles->totpart>0) {
+ psmd= psys_get_modifier(ob,sb->particles);
+
+ pa= sb->particles->particles;
+ key= pa->hair;
+
+ psys_mat_hair_to_global(ob, psmd->dm, sb->particles->part->from, pa, hairmat);
+ }
+
+ for(a=0,bp=sb->bpoint; a<numVerts; a++, bp++) {
+ /* store where goals are now */
+ VECCOPY(bp->origS, bp->origE);
+ /* copy the position of the goals at desired end time */
+ if(sb->particles) {
+ if(key == pa->hair + pa->totkey) {
+ pa++;
+ key = pa->hair;
+
+ psys_mat_hair_to_global(ob, psmd->dm, sb->particles->part->from, pa, hairmat);
+ }
+ VECCOPY(bp->origE, key->co);
+ Mat4MulVecfl(hairmat,bp->origE);
+
+ key++;
+ }
+ else{
+ VECCOPY(bp->origE, vertexCos[a]);
+ /* vertexCos came from local world, go global */
+ Mat4MulVecfl(ob->obmat, bp->origE);
+ }
+ /* just to be save give bp->origT a defined value
+ will be calulated in interpolate_exciter()*/
+ VECCOPY(bp->origT, bp->origE);
+ }
+}
+
+static void softbody_reset(Object *ob, SoftBody *sb, float (*vertexCos)[3], int numVerts)
+{
+ ParticleSystemModifierData *psmd= NULL;
+ HairKey *key= NULL;
+ ParticleData *pa= NULL;
+ BodyPoint *bp;
float hairmat[4][4];
+ int a;
- /* This part only sets goals and springs, based on original mesh/curve/lattice data.
- Copying coordinates happens in next chunk by setting softbody flag OB_SB_RESET */
- /* remake softbody if: */
- if( (ob->softflag & OB_SB_REDO) || /* signal after weightpainting */
- (ob->soft==NULL) || /* just to be nice we allow full init */
- (ob->soft->bpoint==NULL) || /* after reading new file, or acceptable as signal to refresh */
- (numVerts!=ob->soft->totpoint) || /* should never happen, just to be safe */
- ((ob->softflag & OB_SB_EDGES) && !ob->soft->bspring && object_has_edges(ob))) /* happens when in UI edges was set */
- {
- if(ob->soft && ob->soft->bpoint) /* don't clear on file load */
- softbody_clear_cache(ob, framenr);
+ if(sb->particles && sb->particles->totpart>0) {
+ psmd= psys_get_modifier(ob, sb->particles);
+ pa= sb->particles->particles;
+ key= pa->hair;
- if(ob->soft->particles){
- particles_to_softbody(ob);
+ psys_mat_hair_to_global(ob, psmd->dm, sb->particles->part->from, pa, hairmat);
+ }
+
+ for(a=0,bp=sb->bpoint; a<numVerts; a++, bp++) {
+ if(sb->particles) {
+ if(key == pa->hair + pa->totkey) {
+ pa++;
+ key = pa->hair;
+
+ psys_mat_hair_to_global(ob, psmd->dm, sb->particles->part->from, pa, hairmat);
+ }
+ VECCOPY(bp->pos, key->co);
+ Mat4MulVecfl(hairmat, bp->pos);
+ key++;
+ }
+ else {
+ VECCOPY(bp->pos, vertexCos[a]);
+ Mat4MulVecfl(ob->obmat, bp->pos); /* yep, sofbody is global coords*/
}
- else switch(ob->type) {
+ VECCOPY(bp->origS, bp->pos);
+ VECCOPY(bp->origE, bp->pos);
+ VECCOPY(bp->origT, bp->pos);
+ bp->vec[0]= bp->vec[1]= bp->vec[2]= 0.0f;
+
+ /* the bp->prev*'s are for rolling back from a canceled try to propagate in time
+ adaptive step size algo in a nutshell:
+ 1. set sheduled time step to new dtime
+ 2. try to advance the sheduled time step, beeing optimistic execute it
+ 3. check for success
+ 3.a we 're fine continue, may be we can increase sheduled time again ?? if so, do so!
+ 3.b we did exceed error limit --> roll back, shorten the sheduled time and try again at 2.
+ 4. check if we did reach dtime
+ 4.a nope we need to do some more at 2.
+ 4.b yup we're done
+ */
+
+ VECCOPY(bp->prevpos, bp->pos);
+ VECCOPY(bp->prevvec, bp->vec);
+ VECCOPY(bp->prevdx, bp->vec);
+ VECCOPY(bp->prevdv, bp->vec);
+ }
+
+ /* make a nice clean scratch struc */
+ free_scratch(sb); /* clear if any */
+ sb_new_scratch(sb); /* make a new */
+ sb->scratch->needstobuildcollider=1;
+
+ if((sb->particles)==0) {
+ /* copy some info to scratch */
+ switch(ob->type) {
case OB_MESH:
- mesh_to_softbody(ob);
+ if (ob->softflag & OB_SB_FACECOLL) mesh_faces_to_scratch(ob);
break;
case OB_LATTICE:
- lattice_to_softbody(ob);
break;
case OB_CURVE:
case OB_SURF:
- curve_surf_to_softbody(ob);
break;
default:
- renew_softbody(ob, numVerts, 0);
break;
}
+ }
+}
+
+static void softbody_step(Object *ob, SoftBody *sb, float dtime)
+{
+ /* the simulator */
+ float forcetime;
+ double sct,sst=PIL_check_seconds_timer();
+ ccd_update_deflector_hache(ob,sb->scratch->colliderhash);
- /* still need to update to correct vertex locations, happens on next step */
- ob->softflag |= OB_SB_RESET;
- ob->softflag &= ~OB_SB_REDO;
+ if(sb->scratch->needstobuildcollider){
+ if (query_external_colliders(ob)){
+ ccd_build_deflector_hache(ob,sb->scratch->colliderhash);
+ }
+ sb->scratch->needstobuildcollider=0;
}
- sb= ob->soft;
+ if (sb->solver_ID < 2) {
+ /* special case of 2nd order Runge-Kutta type AKA Heun */
+ int mid_flags=0;
+ float err = 0;
+ float forcetimemax = 1.0f;
+ float forcetimemin = 0.001f;
+ float timedone =0.0; /* how far did we get without violating error condition */
+ /* loops = counter for emergency brake
+ * we don't want to lock up the system if physics fail
+ */
+ int loops =0 ;
+
+ SoftHeunTol = sb->rklimit; /* humm .. this should be calculated from sb parameters and sizes */
+ if (sb->minloops > 0) forcetimemax = 1.0f / sb->minloops;
+
+ if (sb->maxloops > 0) forcetimemin = 1.0f / sb->maxloops;
- /* still no points? go away */
- if(sb->totpoint==0) return;
+ if(sb->solver_ID>0) mid_flags |= MID_PRESERVE;
+
+ //forcetime = dtime; /* hope for integrating in one step */
+ forcetime =forcetimemax; /* hope for integrating in one step */
+ while ( (ABS(timedone) < ABS(dtime)) && (loops < 2000) )
+ {
+ /* set goals in time */
+ interpolate_exciter(ob,200,(int)(200.0*(timedone/dtime)));
+
+ sb->scratch->flag &= ~SBF_DOFUZZY;
+ /* do predictive euler step */
+ softbody_calc_forces(ob, forcetime,timedone/dtime,0);
- if(sb->particles){
- psmd=psys_get_modifier(ob,sb->particles);
- pa=sb->particles->particles;
- }
+ softbody_apply_forces(ob, forcetime, 1, NULL,mid_flags);
- /* checking time: */
+ /* crop new slope values to do averaged slope step */
+ softbody_calc_forces(ob, forcetime,timedone/dtime,0);
- ctime= bsystem_time(ob, framenr, 0.0);
+ softbody_apply_forces(ob, forcetime, 2, &err,mid_flags);
+ softbody_apply_goalsnap(ob);
+
+ if (err > SoftHeunTol) { /* error needs to be scaled to some quantity */
+
+ if (forcetime > forcetimemin){
+ forcetime = MAX2(forcetime / 2.0f,forcetimemin);
+ softbody_restore_prev_step(ob);
+ //printf("down,");
+ }
+ else {
+ timedone += forcetime;
+ }
+ }
+ else {
+ float newtime = forcetime * 1.1f; /* hope for 1.1 times better conditions in next step */
+
+ if (sb->scratch->flag & SBF_DOFUZZY){
+ //if (err > SoftHeunTol/(2.0f*sb->fuzzyness)) { /* stay with this stepsize unless err really small */
+ newtime = forcetime;
+ //}
+ }
+ else {
+ if (err > SoftHeunTol/2.0f) { /* stay with this stepsize unless err really small */
+ newtime = forcetime;
+ }
+ }
+ timedone += forcetime;
+ newtime=MIN2(forcetimemax,MAX2(newtime,forcetimemin));
+ //if (newtime > forcetime) printf("up,");
+ if (forcetime > 0.0)
+ forcetime = MIN2(dtime - timedone,newtime);
+ else
+ forcetime = MAX2(dtime - timedone,newtime);
+ }
+ loops++;
+ if(sb->solverflags & SBSO_MONITOR ){
+ sct=PIL_check_seconds_timer();
+ if (sct-sst > 0.5f) printf("%3.0f%% \r",100.0f*timedone);
+ }
+ /* ask for user break */
+ if (SB_localInterruptCallBack && SB_localInterruptCallBack()) break;
- if (ob->softflag&OB_SB_RESET) {
- dtime = 0.0;
- } else {
- dtime= ctime - sb->ctime;
+ }
+ /* move snapped to final position */
+ interpolate_exciter(ob, 2, 2);
+ softbody_apply_goalsnap(ob);
+
+ // if(G.f & G_DEBUG){
+ if(sb->solverflags & SBSO_MONITOR ){
+ if (loops > HEUNWARNLIMIT) /* monitor high loop counts */
+ printf("\r needed %d steps/frame",loops);
+ }
+
}
+ else if (sb->solver_ID == 2)
+ {/* do semi "fake" implicit euler */
+ //removed
+ }/*SOLVER SELECT*/
+ else if (sb->solver_ID == 4)
+ {
+ /* do semi "fake" implicit euler */
+ }/*SOLVER SELECT*/
+ else if (sb->solver_ID == 3){
+ /* do "stupid" semi "fake" implicit euler */
+ //removed
- if(softbody_read_cache(ob, framenr)) {
- if(sb->particles==0)
- softbody_to_object(ob, vertexCos, numVerts, sb->local);
- sb->ctime = ctime;
- return;
+ }/*SOLVER SELECT*/
+ else{
+ printf("softbody no valid solver ID!");
+ }/*SOLVER SELECT*/
+ if(sb->plastic){ apply_spring_memory(ob);}
+
+ if(sb->solverflags & SBSO_MONITOR ){
+ sct=PIL_check_seconds_timer();
+ if ((sct-sst > 0.5f) || (G.f & G_DEBUG)) printf(" solver time %f sec %s \n",sct-sst,ob->id.name);
}
+}
- /* the simulator */
+/* simulates one step. framenr is in frames */
+void sbObjectStep(Object *ob, float cfra, float (*vertexCos)[3], int numVerts)
+{
+ ParticleSystemModifierData *psmd=0;
+ ParticleData *pa=0;
+ SoftBody *sb= ob->soft;
+ PointCache *cache;
+ PTCacheID pid;
+ float dtime, timescale;
+ int framedelta, framenr, startframe, endframe;
- /* update the vertex locations */
- if (dtime!=0.0) {
- if(sb->particles) {
- pa=sb->particles->particles;
- key = pa->hair;
+ cache= sb->pointcache;
- psys_mat_hair_to_global(ob, psmd->dm, sb->particles->part->from, pa, hairmat);
- }
+ framenr= (int)cfra;
+ framedelta= framenr - cache->simframe;
- for(a=0,bp=sb->bpoint; a<numVerts; a++, bp++) {
- /* store where goals are now */
- VECCOPY(bp->origS, bp->origE);
- /* copy the position of the goals at desired end time */
- if(sb->particles) {
- if(key == pa->hair + pa->totkey) {
- pa++;
- key = pa->hair;
+ BKE_ptcache_id_from_softbody(&pid, ob, sb);
+ BKE_ptcache_id_time(&pid, framenr, &startframe, &endframe, &timescale);
- psys_mat_hair_to_global(ob, psmd->dm, sb->particles->part->from, pa, hairmat);
- }
- VECCOPY(bp->origE, key->co);
- Mat4MulVecfl(hairmat,bp->origE);
+ /* check for changes in mesh, should only happen in case the mesh
+ * structure changes during an animation */
+ if(sb->bpoint && numVerts != sb->totpoint) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
- key++;
- }
- else{
- VECCOPY(bp->origE, vertexCos[a]);
- /* vertexCos came from local world, go global */
- Mat4MulVecfl(ob->obmat, bp->origE);
- }
- /* just to be save give bp->origT a defined value
- will be calulated in interpolate_exciter()*/
- VECCOPY(bp->origT, bp->origE);
- }
+ return;
}
- if((ob->softflag&OB_SB_RESET) || /* got a reset signal */
- (dtime<0.0) || /* back in time */
- (dtime>=9.9*G.scene->r.framelen) /* too far forward in time --> goals won't be accurate enough */
- )
- {
- if(sb->particles) {
- pa=sb->particles->particles;
- key = pa->hair;
+ /* clamp frame ranges */
+ if(framenr < startframe) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
- psys_mat_hair_to_global(ob, psmd->dm, sb->particles->part->from, pa, hairmat);
- }
+ return;
+ }
+ else if(framenr > endframe) {
+ framenr = endframe;
+ }
- for(a=0,bp=sb->bpoint; a<numVerts; a++, bp++) {
- if(sb->particles) {
- if(key == pa->hair + pa->totkey) {
- pa++;
- key = pa->hair;
+ /* verify if we need to create the softbody data */
+ if(sb->bpoint == NULL ||
+ ((ob->softflag & OB_SB_EDGES) && !ob->soft->bspring && object_has_edges(ob))) {
- psys_mat_hair_to_global(ob, psmd->dm, sb->particles->part->from, pa, hairmat);
- }
- VECCOPY(bp->pos, key->co);
- Mat4MulVecfl(hairmat, bp->pos);
- key++;
- }
- else {
- VECCOPY(bp->pos, vertexCos[a]);
- Mat4MulVecfl(ob->obmat, bp->pos); /* yep, sofbody is global coords*/
- }
- VECCOPY(bp->origS, bp->pos);
- VECCOPY(bp->origE, bp->pos);
- VECCOPY(bp->origT, bp->pos);
- bp->vec[0]= bp->vec[1]= bp->vec[2]= 0.0f;
-
- /* the bp->prev*'s are for rolling back from a canceled try to propagate in time
- adaptive step size algo in a nutshell:
- 1. set sheduled time step to new dtime
- 2. try to advance the sheduled time step, beeing optimistic execute it
- 3. check for success
- 3.a we 're fine continue, may be we can increase sheduled time again ?? if so, do so!
- 3.b we did exceed error limit --> roll back, shorten the sheduled time and try again at 2.
- 4. check if we did reach dtime
- 4.a nope we need to do some more at 2.
- 4.b yup we're done
- */
-
- VECCOPY(bp->prevpos, bp->pos);
- VECCOPY(bp->prevvec, bp->vec);
- VECCOPY(bp->prevdx, bp->vec);
- VECCOPY(bp->prevdv, bp->vec);
+ if(sb->particles){
+ particles_to_softbody(ob);
}
- /* make a nice clean scratch struc */
- free_scratch(sb); /* clear if any */
- sb_new_scratch(sb); /* make a new */
- sb->scratch->needstobuildcollider=1;
-
- if((sb->particles)==0) {
- /* copy some info to scratch */
+ else {
switch(ob->type) {
- case OB_MESH:
- if (ob->softflag & OB_SB_FACECOLL) mesh_faces_to_scratch(ob);
- break;
- case OB_LATTICE:
- break;
- case OB_CURVE:
- case OB_SURF:
- break;
- default:
- break;
+ case OB_MESH:
+ mesh_to_softbody(ob);
+ break;
+ case OB_LATTICE:
+ lattice_to_softbody(ob);
+ break;
+ case OB_CURVE:
+ case OB_SURF:
+ curve_surf_to_softbody(ob);
+ break;
+ default:
+ renew_softbody(ob, numVerts, 0);
+ break;
}
}
- ob->softflag &= ~OB_SB_RESET;
+ softbody_update_positions(ob, sb, vertexCos, numVerts);
+ softbody_reset(ob, sb, vertexCos, numVerts);
}
- else if(dtime>0.0) {
- double sct,sst=PIL_check_seconds_timer();
- ccd_update_deflector_hache(ob,sb->scratch->colliderhash);
+ /* continue physics special case */
+ if(BKE_ptcache_get_continue_physics()) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
- if(sb->scratch->needstobuildcollider){
- if (query_external_colliders(ob)){
- ccd_build_deflector_hache(ob,sb->scratch->colliderhash);
- }
- sb->scratch->needstobuildcollider=0;
- }
+ /* do simulation */
+ dtime = timescale;
+ softbody_update_positions(ob, sb, vertexCos, numVerts);
+ softbody_step(ob, sb, dtime);
- if (TRUE) { /* */
- /* special case of 2nd order Runge-Kutta type AKA Heun */
- float forcetimemax = 1.0f;
- float forcetimemin = 0.001f;
- float timedone =0.0; /* how far did we get without violating error condition */
- /* loops = counter for emergency brake
- * we don't want to lock up the system if physics fail
- */
- int loops =0 ;
- SoftHeunTol = sb->rklimit; /* humm .. this should be calculated from sb parameters and sizes */
- if (sb->minloops > 0) forcetimemax = 1.0f / sb->minloops;
-
- if (sb->maxloops > 0) forcetimemin = 1.0f / sb->maxloops;
-
-
- //forcetime = dtime; /* hope for integrating in one step */
- forcetime =forcetimemax; /* hope for integrating in one step */
- while ( (ABS(timedone) < ABS(dtime)) && (loops < 2000) )
- {
- /* set goals in time */
- interpolate_exciter(ob,200,(int)(200.0*(timedone/dtime)));
-
- sb->scratch->flag &= ~SBF_DOFUZZY;
- /* do predictive euler step */
- softbody_calc_forces(ob, forcetime,timedone/dtime);
- softbody_apply_forces(ob, forcetime, 1, NULL);
+ if(sb->particles==0)
+ softbody_to_object(ob, vertexCos, numVerts, 0);
+ return;
+ }
- /* crop new slope values to do averaged slope step */
- softbody_calc_forces(ob, forcetime,timedone/dtime);
- softbody_apply_forces(ob, forcetime, 2, &err);
+ /* still no points? go away */
+ if(sb->totpoint==0) return;
- softbody_apply_goalsnap(ob);
-
- if (err > SoftHeunTol) { /* error needs to be scaled to some quantity */
-
- if (forcetime > forcetimemin){
- forcetime = MAX2(forcetime / 2.0f,forcetimemin);
- softbody_restore_prev_step(ob);
- //printf("down,");
- }
- else {
- timedone += forcetime;
- }
- }
- else {
- float newtime = forcetime * 1.1f; /* hope for 1.1 times better conditions in next step */
-
- if (sb->scratch->flag & SBF_DOFUZZY){
- //if (err > SoftHeunTol/(2.0f*sb->fuzzyness)) { /* stay with this stepsize unless err really small */
- newtime = forcetime;
- //}
- }
- else {
- if (err > SoftHeunTol/2.0f) { /* stay with this stepsize unless err really small */
- newtime = forcetime;
- }
- }
- timedone += forcetime;
- newtime=MIN2(forcetimemax,MAX2(newtime,forcetimemin));
- //if (newtime > forcetime) printf("up,");
- if (forcetime > 0.0)
- forcetime = MIN2(dtime - timedone,newtime);
- else
- forcetime = MAX2(dtime - timedone,newtime);
- }
- loops++;
- if(sb->solverflags & SBSO_MONITOR ){
- sct=PIL_check_seconds_timer();
- if (sct-sst > 0.5f) printf("%3.0f%% \r",100.0f*timedone);
- }
- if (SB_localInterruptCallBack && SB_localInterruptCallBack()) break;
+ if(sb->particles){
+ psmd= psys_get_modifier(ob, sb->particles);
+ pa= sb->particles->particles;
+ }
- }
- /* move snapped to final position */
- interpolate_exciter(ob, 2, 2);
- softbody_apply_goalsnap(ob);
-
- // if(G.f & G_DEBUG){
- if(sb->solverflags & SBSO_MONITOR ){
- if (loops > HEUNWARNLIMIT) /* monitor high loop counts */
- printf("\r needed %d steps/frame ",loops);
- }
-
- }
- else{
- /* do brute force explicit euler */
- /* removed but left this branch for better integrators / solvers (BM) */
- /* yah! Nicholas Guttenberg (NichG) here is the place to plug in */
- }
- if(sb->solverflags & SBSO_MONITOR ){
- sct=PIL_check_seconds_timer();
- if (sct-sst > 0.5f) printf(" solver time %f %s \r",sct-sst,ob->id.name);
- }
+ /* try to read from cache */
+ if(softbody_read_cache(ob, framenr)) {
+ if(sb->particles==0)
+ softbody_to_object(ob, vertexCos, numVerts, sb->local);
+
+ cache->flag |= PTCACHE_SIMULATION_VALID;
+ cache->simframe= framenr;
+
+ return;
+ }
+ else if(ob->id.lib || (cache->flag & PTCACHE_BAKED)) {
+ /* if baked and nothing in cache, do nothing */
+ if(cache->flag & PTCACHE_SIMULATION_VALID) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ }
+
+ return;
}
- if(sb->particles==0)
- softbody_to_object(ob, vertexCos, numVerts, 0);
- sb->ctime= ctime;
+ if(framenr == startframe) {
+ /* first frame, no simulation to do, just set the positions */
+ softbody_update_positions(ob, sb, vertexCos, numVerts);
+
+ cache->flag |= PTCACHE_SIMULATION_VALID;
+ cache->simframe= framenr;
+
+ /* don't write cache on first frame, but on second frame write
+ * cache for frame 1 and 2 */
+ }
+ else if(framedelta == 1) {
+ /* if on second frame, write cache for first frame */
+ if(framenr == startframe+1)
+ sbWriteCache(ob, startframe);
+
+ softbody_update_positions(ob, sb, vertexCos, numVerts);
+
+ /* do simulation */
+ cache->flag |= PTCACHE_SIMULATION_VALID;
+ cache->simframe= framenr;
+
+ /* checking time: */
+ dtime = framedelta*timescale;
- softbody_write_cache(ob, framenr);
+ softbody_step(ob, sb, dtime);
+
+ if(sb->particles==0)
+ softbody_to_object(ob, vertexCos, numVerts, 0);
+
+ sbWriteCache(ob, framenr);
+ }
+ else {
+ /* time step backwards or too large forward - do nothing */
+ if(cache->flag & PTCACHE_SIMULATION_VALID) {
+ cache->flag &= ~PTCACHE_SIMULATION_VALID;
+ cache->simframe= 0;
+ }
+ }
}
diff --git a/source/blender/blenkernel/intern/sound.c b/source/blender/blenkernel/intern/sound.c
index 3b14cb8adac..2c5b49246fb 100644
--- a/source/blender/blenkernel/intern/sound.c
+++ b/source/blender/blenkernel/intern/sound.c
@@ -109,13 +109,13 @@ PackedFile* sound_find_packedfile(bSound *sound)
// convert sound->name to abolute filename
strcpy(soundname, sound->name);
- BLI_convertstringcode(soundname, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(soundname, G.sce);
search = G.main->sound.first;
while (search) {
if (search->sample && search->sample->packedfile) {
strcpy(searchname, search->sample->name);
- BLI_convertstringcode(searchname, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(searchname, G.sce);
if (BLI_streq(searchname, soundname)) {
pf = search->sample->packedfile;
@@ -125,7 +125,7 @@ PackedFile* sound_find_packedfile(bSound *sound)
if (search->newpackedfile) {
strcpy(searchname, search->name);
- BLI_convertstringcode(searchname, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(searchname, G.sce);
if (BLI_streq(searchname, soundname)) {
pf = search->newpackedfile;
break;
diff --git a/source/blender/blenkernel/intern/subsurf_ccg.c b/source/blender/blenkernel/intern/subsurf_ccg.c
index 60e01181f2d..f5124ed9056 100644
--- a/source/blender/blenkernel/intern/subsurf_ccg.c
+++ b/source/blender/blenkernel/intern/subsurf_ccg.c
@@ -39,15 +39,17 @@
#include "DNA_meshdata_types.h"
#include "DNA_modifier_types.h"
#include "DNA_object_types.h"
+#include "DNA_scene_types.h"
#include "BKE_cdderivedmesh.h"
#include "BKE_customdata.h"
+#include "BKE_DerivedMesh.h"
+#include "BKE_displist.h"
#include "BKE_utildefines.h"
#include "BKE_global.h"
#include "BKE_mesh.h"
+#include "BKE_scene.h"
#include "BKE_subsurf.h"
-#include "BKE_displist.h"
-#include "BKE_DerivedMesh.h"
#include "BLI_blenlib.h"
#include "BLI_editVert.h"
@@ -58,6 +60,10 @@
#include "BIF_gl.h"
+#include "GPU_draw.h"
+#include "GPU_extensions.h"
+#include "GPU_material.h"
+
#include "CCGSubSurf.h"
typedef struct _VertData {
@@ -79,9 +85,9 @@ struct CCGDerivedMesh {
typedef struct CCGDerivedMesh CCGDerivedMesh;
-static int ccgDM_getVertMapIndex(CCGDerivedMesh *ccgdm, CCGSubSurf *ss, CCGVert *v);
-static int ccgDM_getEdgeMapIndex(CCGDerivedMesh *ccgdm, CCGSubSurf *ss, CCGEdge *e);
-static int ccgDM_getFaceMapIndex(CCGDerivedMesh *ccgdm, CCGSubSurf *ss, CCGFace *f);
+static int ccgDM_getVertMapIndex(CCGSubSurf *ss, CCGVert *v);
+static int ccgDM_getEdgeMapIndex(CCGSubSurf *ss, CCGEdge *e);
+static int ccgDM_getFaceMapIndex(CCGSubSurf *ss, CCGFace *f);
///
@@ -154,8 +160,8 @@ static CCGSubSurf *_getSubSurf(CCGSubSurf *prevSS, int subdivLevels, int useAgin
}
static int getEdgeIndex(CCGSubSurf *ss, CCGEdge *e, int x, int edgeSize) {
- CCGVert *v0 = ccgSubSurf_getEdgeVert0(ss, e);
- CCGVert *v1 = ccgSubSurf_getEdgeVert1(ss, e);
+ CCGVert *v0 = ccgSubSurf_getEdgeVert0(e);
+ CCGVert *v1 = ccgSubSurf_getEdgeVert1(e);
int v0idx = *((int*) ccgSubSurf_getVertUserData(ss, v0));
int v1idx = *((int*) ccgSubSurf_getVertUserData(ss, v1));
int edgeBase = *((int*) ccgSubSurf_getEdgeUserData(ss, e));
@@ -170,7 +176,7 @@ static int getEdgeIndex(CCGSubSurf *ss, CCGEdge *e, int x, int edgeSize) {
}
static int getFaceIndex(CCGSubSurf *ss, CCGFace *f, int S, int x, int y, int edgeSize, int gridSize) {
int faceBase = *((int*) ccgSubSurf_getFaceUserData(ss, f));
- int numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int numVerts = ccgSubSurf_getFaceNumVerts(f);
if (x==gridSize-1 && y==gridSize-1) {
CCGVert *v = ccgSubSurf_getFaceVert(ss, f, S);
@@ -179,7 +185,7 @@ static int getFaceIndex(CCGSubSurf *ss, CCGFace *f, int S, int x, int y, int edg
CCGVert *v = ccgSubSurf_getFaceVert(ss, f, S);
CCGEdge *e = ccgSubSurf_getFaceEdge(ss, f, S);
int edgeBase = *((int*) ccgSubSurf_getEdgeUserData(ss, e));
- if (v==ccgSubSurf_getEdgeVert0(ss, e)) {
+ if (v==ccgSubSurf_getEdgeVert0(e)) {
return edgeBase + (gridSize-1-y)-1;
} else {
return edgeBase + (edgeSize-2-1)-((gridSize-1-y)-1);
@@ -188,7 +194,7 @@ static int getFaceIndex(CCGSubSurf *ss, CCGFace *f, int S, int x, int y, int edg
CCGVert *v = ccgSubSurf_getFaceVert(ss, f, S);
CCGEdge *e = ccgSubSurf_getFaceEdge(ss, f, (S+numVerts-1)%numVerts);
int edgeBase = *((int*) ccgSubSurf_getEdgeUserData(ss, e));
- if (v==ccgSubSurf_getEdgeVert0(ss, e)) {
+ if (v==ccgSubSurf_getEdgeVert0(e)) {
return edgeBase + (gridSize-1-x)-1;
} else {
return edgeBase + (edgeSize-2-1)-((gridSize-1-x)-1);
@@ -218,7 +224,7 @@ static void get_face_uv_map_vert(UvVertMap *vmap, struct MFace *mf, int fi, CCGV
break;
}
- fverts[j]= (CCGVertHDL)(nv->f*4 + nv->tfindex);
+ fverts[j]= SET_INT_IN_POINTER(nv->f*4 + nv->tfindex);
}
}
@@ -235,7 +241,7 @@ static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm,
EdgeHash *ehash;
float creaseFactor = (float)ccgSubSurf_getSubdivisionLevels(ss);
- limit[0]= limit[1]= 0.0001f;
+ limit[0]= limit[1]= STD_UV_CONNECT_LIMIT;
vmap= make_uv_vert_map(mface, tface, totface, totvert, 0, limit);
if (!vmap)
return 0;
@@ -256,7 +262,7 @@ static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm,
for (v=get_uv_map_vert(vmap, i); v; v=v->next) {
if (v->separate) {
CCGVert *ssv;
- CCGVertHDL vhdl = (CCGVertHDL)(v->f*4 + v->tfindex);
+ CCGVertHDL vhdl = SET_INT_IN_POINTER(v->f*4 + v->tfindex);
float uv[3];
uv[0]= (tface+v->f)->uv[v->tfindex][0];
@@ -274,26 +280,26 @@ static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm,
for (i=0; i<totface; i++) {
MFace *mf = &((MFace*) mface)[i];
int nverts= mf->v4? 4: 3;
- CCGFace *origf= ccgSubSurf_getFace(origss, (CCGFaceHDL)i);
+ CCGFace *origf= ccgSubSurf_getFace(origss, SET_INT_IN_POINTER(i));
unsigned int *fv = &mf->v1;
get_face_uv_map_vert(vmap, mf, i, fverts);
for (j=0; j<nverts; j++) {
- int v0 = (int)fverts[j];
- int v1 = (int)fverts[(j+1)%nverts];
+ int v0 = GET_INT_FROM_POINTER(fverts[j]);
+ int v1 = GET_INT_FROM_POINTER(fverts[(j+1)%nverts]);
MVert *mv0 = mvert + *(fv+j);
MVert *mv1 = mvert + *(fv+((j+1)%nverts));
if (!BLI_edgehash_haskey(ehash, v0, v1)) {
CCGEdge *e, *orige= ccgSubSurf_getFaceEdge(origss, origf, j);
- CCGEdgeHDL ehdl= (CCGEdgeHDL)(i*4 + j);
+ CCGEdgeHDL ehdl= SET_INT_IN_POINTER(i*4 + j);
float crease;
if ((mv0->flag&mv1->flag) & ME_VERT_MERGED)
crease = creaseFactor;
else
- crease = ccgSubSurf_getEdgeCrease(origss, orige);
+ crease = ccgSubSurf_getEdgeCrease(orige);
ccgSubSurf_syncEdge(ss, ehdl, fverts[j], fverts[(j+1)%nverts], crease, &e);
BLI_edgehash_insert(ehash, v0, v1, NULL);
@@ -310,7 +316,7 @@ static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm,
CCGFace *f;
get_face_uv_map_vert(vmap, mf, i, fverts);
- ccgSubSurf_syncFace(ss, (CCGFaceHDL)i, nverts, fverts, &f);
+ ccgSubSurf_syncFace(ss, SET_INT_IN_POINTER(i), nverts, fverts, &f);
}
free_uv_vert_map(vmap);
@@ -352,7 +358,7 @@ static void set_subsurf_uv(CCGSubSurf *ss, DerivedMesh *dm, DerivedMesh *result,
fi = ccgSubSurf_getFaceIterator(uvss);
for(; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- faceMap[(int) ccgSubSurf_getFaceFaceHandle(uvss, f)] = f;
+ faceMap[GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(uvss, f))] = f;
}
ccgFaceIterator_free(fi);
@@ -361,7 +367,7 @@ static void set_subsurf_uv(CCGSubSurf *ss, DerivedMesh *dm, DerivedMesh *result,
for(index = 0; index < totface; index++) {
CCGFace *f = faceMap[index];
- int numVerts = ccgSubSurf_getFaceNumVerts(uvss, f);
+ int numVerts = ccgSubSurf_getFaceNumVerts(f);
for (S=0; S<numVerts; S++) {
VertData *faceGridData= ccgSubSurf_getFaceGridDataArray(uvss, f, S);
@@ -392,12 +398,12 @@ static void set_subsurf_uv(CCGSubSurf *ss, DerivedMesh *dm, DerivedMesh *result,
static unsigned int ss_getEdgeFlags(CCGSubSurf *ss, CCGEdge *e, int ssFromEditmesh, DispListMesh *dlm, MEdge *medge, MTFace *tface)
{
unsigned int flags = 0;
- int N = ccgSubSurf_getEdgeNumFaces(ss, e);
+ int N = ccgSubSurf_getEdgeNumFaces(e);
if (!N) flags |= ME_LOOSEEDGE;
if (ssFromEditmesh) {
- EditEdge *eed = ccgSubSurf_getEdgeEdgeHandle(ss, e);
+ EditEdge *eed = ccgSubSurf_getEdgeEdgeHandle(e);
flags |= ME_EDGEDRAW|ME_EDGERENDER;
if (eed->seam) {
@@ -463,7 +469,7 @@ static void calc_ss_weights(int gridFaces,
}
}
-DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
+static DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
int drawInteriorEdges, int useSubsurfUv,
DerivedMesh *dm)
{
@@ -473,7 +479,6 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
int gridFaces = gridSize - 1;
int edgeBase, faceBase;
int i, j, k, S, x, y, index;
- int vertBase = 0;
CCGVertIterator *vi;
CCGEdgeIterator *ei;
CCGFaceIterator *fi;
@@ -496,7 +501,7 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
for(; !ccgVertIterator_isStopped(vi); ccgVertIterator_next(vi)) {
CCGVert *v = ccgVertIterator_getCurrent(vi);
- vertMap2[(int) ccgSubSurf_getVertVertHandle(ss, v)] = v;
+ vertMap2[GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v))] = v;
}
ccgVertIterator_free(vi);
@@ -506,7 +511,7 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
for(; !ccgEdgeIterator_isStopped(ei); ccgEdgeIterator_next(ei)) {
CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
- edgeMap2[(int) ccgSubSurf_getEdgeEdgeHandle(ss, e)] = e;
+ edgeMap2[GET_INT_FROM_POINTER(ccgSubSurf_getEdgeEdgeHandle(e))] = e;
}
totface = ccgSubSurf_getNumFaces(ss);
@@ -515,7 +520,7 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
for(; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- faceMap2[(int) ccgSubSurf_getFaceFaceHandle(ss, f)] = f;
+ faceMap2[GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(ss, f))] = f;
}
ccgFaceIterator_free(fi);
@@ -536,18 +541,18 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
for(index = 0; index < totface; index++) {
CCGFace *f = faceMap2[index];
- int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
FaceVertWeight *weight = (numVerts == 4) ? qweight : tweight;
int vertIdx[4];
for(S = 0; S < numVerts; S++) {
CCGVert *v = ccgSubSurf_getFaceVert(ss, f, S);
- vertIdx[S] = (int)ccgSubSurf_getVertVertHandle(ss, v);
+ vertIdx[S] = GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v));
}
DM_interp_vert_data(dm, result, vertIdx, weight[0][0], numVerts, i);
- VecCopyf(mvert->co, ccgSubSurf_getFaceCenterData(ss, f));
+ VecCopyf(mvert->co, ccgSubSurf_getFaceCenterData(f));
*origIndex = ORIGINDEX_NONE;
++mvert;
++origIndex;
@@ -606,10 +611,10 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
int vertIdx[2];
CCGVert *v;
- v = ccgSubSurf_getEdgeVert0(ss, e);
- vertIdx[0] = (int)ccgSubSurf_getVertVertHandle(ss, v);
- v = ccgSubSurf_getEdgeVert1(ss, e);
- vertIdx[1] = (int)ccgSubSurf_getVertVertHandle(ss, v);
+ v = ccgSubSurf_getEdgeVert0(e);
+ vertIdx[0] = GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v));
+ v = ccgSubSurf_getEdgeVert1(e);
+ vertIdx[1] = GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v));
for(x = 1; x < edgeSize - 1; x++) {
float w[2];
@@ -627,18 +632,17 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
edgeBase += edgeSize-2;
}
- vertBase = i;
for(index = 0; index < totvert; index++) {
CCGVert *v = vertMap2[index];
int vertIdx;
- vertIdx = (int)ccgSubSurf_getVertVertHandle(ss, v);
+ vertIdx = GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v));
DM_copy_vert_data(dm, result, vertIdx, i, 1);
VecCopyf(mvert->co, ccgSubSurf_getVertData(ss, v));
*((int*)ccgSubSurf_getVertUserData(ss, v)) = i;
- *origIndex = ccgDM_getVertMapIndex(NULL, ss, v);
+ *origIndex = ccgDM_getVertMapIndex(ss, v);
++mvert;
++origIndex;
i++;
@@ -651,7 +655,7 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
for(index = 0; index < totface; index++) {
CCGFace *f = faceMap2[index];
- int numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int numVerts = ccgSubSurf_getFaceNumVerts(f);
for(k = 0; k < numVerts; k++) {
for(x = 0; x < gridFaces; x++) {
@@ -693,9 +697,10 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
for(index = 0; index < totedge; index++) {
CCGEdge *e = edgeMap2[index];
unsigned int flags = 0;
- int edgeIdx = (int)ccgSubSurf_getEdgeEdgeHandle(ss, e);
+ char bweight = 0;
+ int edgeIdx = GET_INT_FROM_POINTER(ccgSubSurf_getEdgeEdgeHandle(e));
- if(!ccgSubSurf_getEdgeNumFaces(ss, e)) flags |= ME_LOOSEEDGE;
+ if(!ccgSubSurf_getEdgeNumFaces(e)) flags |= ME_LOOSEEDGE;
if(edgeIdx != -1 && dm) {
@@ -703,13 +708,15 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
dm->getEdge(dm, edgeIdx, &origMed);
flags |= origMed.flag;
+ bweight = origMed.bweight;
}
for(x = 0; x < edgeSize - 1; x++) {
med->v1 = getEdgeIndex(ss, e, x, edgeSize);
med->v2 = getEdgeIndex(ss, e, x + 1, edgeSize);
med->flag = flags;
- *origIndex = ccgDM_getEdgeMapIndex(NULL, ss, e);
+ med->bweight = bweight;
+ *origIndex = ccgDM_getEdgeMapIndex(ss, e);
++med;
++origIndex;
i++;
@@ -723,11 +730,11 @@ DerivedMesh *ss_to_cdderivedmesh(CCGSubSurf *ss, int ssFromEditmesh,
for(index = 0; index < totface; index++) {
CCGFace *f = faceMap2[index];
- int numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int numVerts = ccgSubSurf_getFaceNumVerts(f);
int mat_nr;
int flag;
- int mapIndex = ccgDM_getFaceMapIndex(NULL, ss, f);
- int faceIdx = (int)ccgSubSurf_getFaceFaceHandle(ss, f);
+ int mapIndex = ccgDM_getFaceMapIndex(ss, f);
+ int faceIdx = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(ss, f));
if(!ssFromEditmesh) {
MFace origMFace;
@@ -831,9 +838,9 @@ static void ss_sync_from_derivedmesh(CCGSubSurf *ss, DerivedMesh *dm,
CCGVert *v;
if(vertexCos) {
- ccgSubSurf_syncVert(ss, (CCGVertHDL)i, vertexCos[i], 0, &v);
+ ccgSubSurf_syncVert(ss, SET_INT_IN_POINTER(i), vertexCos[i], 0, &v);
} else {
- ccgSubSurf_syncVert(ss, (CCGVertHDL)i, mv->co, 0, &v);
+ ccgSubSurf_syncVert(ss, SET_INT_IN_POINTER(i), mv->co, 0, &v);
}
((int*)ccgSubSurf_getVertUserData(ss, v))[1] = *index;
@@ -848,8 +855,8 @@ static void ss_sync_from_derivedmesh(CCGSubSurf *ss, DerivedMesh *dm,
crease = useFlatSubdiv ? creaseFactor :
me->crease * creaseFactor / 255.0f;
- ccgSubSurf_syncEdge(ss, (CCGEdgeHDL)i, (CCGVertHDL)me->v1,
- (CCGVertHDL)me->v2, crease, &e);
+ ccgSubSurf_syncEdge(ss, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(me->v1),
+ SET_INT_IN_POINTER(me->v2), crease, &e);
((int*)ccgSubSurf_getEdgeUserData(ss, e))[1] = *index;
}
@@ -859,16 +866,16 @@ static void ss_sync_from_derivedmesh(CCGSubSurf *ss, DerivedMesh *dm,
for (i = 0; i < totface; i++, mf++, index++) {
CCGFace *f;
- fVerts[0] = (CCGVertHDL) mf->v1;
- fVerts[1] = (CCGVertHDL) mf->v2;
- fVerts[2] = (CCGVertHDL) mf->v3;
- fVerts[3] = (CCGVertHDL) mf->v4;
+ fVerts[0] = SET_INT_IN_POINTER(mf->v1);
+ fVerts[1] = SET_INT_IN_POINTER(mf->v2);
+ fVerts[2] = SET_INT_IN_POINTER(mf->v3);
+ fVerts[3] = SET_INT_IN_POINTER(mf->v4);
// this is very bad, means mesh is internally consistent.
// it is not really possible to continue without modifying
// other parts of code significantly to handle missing faces.
// since this really shouldn't even be possible we just bail.
- if(ccgSubSurf_syncFace(ss, (CCGFaceHDL)i, fVerts[3] ? 4 : 3,
+ if(ccgSubSurf_syncFace(ss, SET_INT_IN_POINTER(i), fVerts[3] ? 4 : 3,
fVerts, &f) == eCCGError_InvalidValue) {
static int hasGivenError = 0;
@@ -890,15 +897,15 @@ static void ss_sync_from_derivedmesh(CCGSubSurf *ss, DerivedMesh *dm,
/***/
-static int ccgDM_getVertMapIndex(CCGDerivedMesh *ccgdm, CCGSubSurf *ss, CCGVert *v) {
+static int ccgDM_getVertMapIndex(CCGSubSurf *ss, CCGVert *v) {
return ((int*) ccgSubSurf_getVertUserData(ss, v))[1];
}
-static int ccgDM_getEdgeMapIndex(CCGDerivedMesh *ccgdm, CCGSubSurf *ss, CCGEdge *e) {
+static int ccgDM_getEdgeMapIndex(CCGSubSurf *ss, CCGEdge *e) {
return ((int*) ccgSubSurf_getEdgeUserData(ss, e))[1];
}
-static int ccgDM_getFaceMapIndex(CCGDerivedMesh *ccgdm, CCGSubSurf *ss, CCGFace *f) {
+static int ccgDM_getFaceMapIndex(CCGSubSurf *ss, CCGFace *f) {
return ((int*) ccgSubSurf_getFaceUserData(ss, f))[1];
}
@@ -931,7 +938,7 @@ static void ccgDM_getMinMax(DerivedMesh *dm, float min_r[3], float max_r[3]) {
for (; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
for (S=0; S<numVerts; S++) {
VertData *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
@@ -970,7 +977,7 @@ static void ccgDM_getFinalVert(DerivedMesh *dm, int vertNum, MVert *mv)
memset(mv, 0, sizeof(*mv));
- if(vertNum < ccgdm->edgeMap[0].startVert) {
+ if((vertNum < ccgdm->edgeMap[0].startVert) && (ccgSubSurf_getNumFaces(ss) > 0)) {
/* this vert comes from face data */
int lastface = ccgSubSurf_getNumFaces(ss) - 1;
CCGFace *f;
@@ -987,7 +994,7 @@ static void ccgDM_getFinalVert(DerivedMesh *dm, int vertNum, MVert *mv)
++i;
f = ccgdm->faceMap[i].face;
- numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ numVerts = ccgSubSurf_getFaceNumVerts(f);
gridSideVerts = gridSize - 2;
gridInternalVerts = gridSideVerts * gridSideVerts;
@@ -997,7 +1004,7 @@ static void ccgDM_getFinalVert(DerivedMesh *dm, int vertNum, MVert *mv)
offset = vertNum - ccgdm->faceMap[i].startVert;
if(offset < 1) {
- VecCopyf(mv->co, ccgSubSurf_getFaceCenterData(ss, f));
+ VecCopyf(mv->co, ccgSubSurf_getFaceCenterData(f));
} else if(offset < gridSideEnd) {
offset -= 1;
grid = offset / gridSideVerts;
@@ -1011,7 +1018,7 @@ static void ccgDM_getFinalVert(DerivedMesh *dm, int vertNum, MVert *mv)
x = offset % gridSideVerts + 1;
VecCopyf(mv->co, ccgSubSurf_getFaceGridData(ss, f, grid, x, y));
}
- } else if(vertNum < ccgdm->vertMap[0].startVert) {
+ } else if((vertNum < ccgdm->vertMap[0].startVert) && (ccgSubSurf_getNumEdges(ss) > 0)) {
/* this vert comes from edge data */
CCGEdge *e;
int lastedge = ccgSubSurf_getNumEdges(ss) - 1;
@@ -1059,7 +1066,7 @@ static void ccgDM_getFinalEdge(DerivedMesh *dm, int edgeNum, MEdge *med)
++i;
f = ccgdm->faceMap[i].face;
- numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ numVerts = ccgSubSurf_getFaceNumVerts(f);
gridSideEdges = gridSize - 1;
gridInternalEdges = (gridSideEdges - 1) * gridSideEdges * 2;
@@ -1095,7 +1102,7 @@ static void ccgDM_getFinalEdge(DerivedMesh *dm, int edgeNum, MEdge *med)
e = ccgdm->edgeMap[i].edge;
- if(!ccgSubSurf_getEdgeNumFaces(ss, e)) flags |= ME_LOOSEEDGE;
+ if(!ccgSubSurf_getEdgeNumFaces(e)) flags |= ME_LOOSEEDGE;
x = edgeNum - ccgdm->edgeMap[i].startEdge;
@@ -1137,7 +1144,7 @@ static void ccgDM_getFinalFace(DerivedMesh *dm, int faceNum, MFace *mf)
++i;
f = ccgdm->faceMap[i].face;
- numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ numVerts = ccgSubSurf_getFaceNumVerts(f);
offset = faceNum - ccgdm->faceMap[i].startFace;
grid = offset / gridFaces;
@@ -1167,9 +1174,9 @@ static void ccgDM_copyFinalVertArray(DerivedMesh *dm, MVert *mvert)
totface = ccgSubSurf_getNumFaces(ss);
for(index = 0; index < totface; index++) {
CCGFace *f = ccgdm->faceMap[index].face;
- int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
- VecCopyf(mvert[i++].co, ccgSubSurf_getFaceCenterData(ss, f));
+ VecCopyf(mvert[i++].co, ccgSubSurf_getFaceCenterData(f));
for(S = 0; S < numVerts; S++) {
for(x = 1; x < gridSize - 1; x++) {
@@ -1222,7 +1229,7 @@ static void ccgDM_copyFinalEdgeArray(DerivedMesh *dm, MEdge *medge)
totface = ccgSubSurf_getNumFaces(ss);
for(index = 0; index < totface; index++) {
CCGFace *f = ccgdm->faceMap[index].face;
- int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
for(S = 0; S < numVerts; S++) {
for(x = 0; x < gridSize - 1; x++) {
@@ -1266,9 +1273,9 @@ static void ccgDM_copyFinalEdgeArray(DerivedMesh *dm, MEdge *medge)
CCGEdge *e = ccgdm->edgeMap[index].edge;
unsigned int flags = 0;
int x;
- int edgeIdx = (int)ccgSubSurf_getEdgeEdgeHandle(ss, e);
+ int edgeIdx = GET_INT_FROM_POINTER(ccgSubSurf_getEdgeEdgeHandle(e));
- if(!ccgSubSurf_getEdgeNumFaces(ss, e)) flags |= ME_LOOSEEDGE;
+ if(!ccgSubSurf_getEdgeNumFaces(e)) flags |= ME_LOOSEEDGE;
if(edgeFlags) {
if(edgeIdx != -1) {
@@ -1303,7 +1310,7 @@ static void ccgDM_copyFinalFaceArray(DerivedMesh *dm, MFace *mface)
totface = ccgSubSurf_getNumFaces(ss);
for(index = 0; index < totface; index++) {
CCGFace *f = ccgdm->faceMap[index].face;
- int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
int mat_nr = 0;
int flag = ME_SMOOTH; /* assume face is smooth by default */
@@ -1350,7 +1357,7 @@ static void ccgdm_getVertCos(DerivedMesh *dm, float (*cos)[3]) {
for (; !ccgVertIterator_isStopped(vi); ccgVertIterator_next(vi)) {
CCGVert *v = ccgVertIterator_getCurrent(vi);
- vertMap2[(int) ccgSubSurf_getVertVertHandle(ss, v)] = v;
+ vertMap2[GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v))] = v;
}
ccgVertIterator_free(vi);
@@ -1360,7 +1367,7 @@ static void ccgdm_getVertCos(DerivedMesh *dm, float (*cos)[3]) {
for (i=0; !ccgEdgeIterator_isStopped(ei); i++,ccgEdgeIterator_next(ei)) {
CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
- edgeMap2[(int) ccgSubSurf_getEdgeEdgeHandle(ss, e)] = e;
+ edgeMap2[GET_INT_FROM_POINTER(ccgSubSurf_getEdgeEdgeHandle(e))] = e;
}
totface = ccgSubSurf_getNumFaces(ss);
@@ -1369,16 +1376,16 @@ static void ccgdm_getVertCos(DerivedMesh *dm, float (*cos)[3]) {
for (; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- faceMap2[(int) ccgSubSurf_getFaceFaceHandle(ss, f)] = f;
+ faceMap2[GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(ss, f))] = f;
}
ccgFaceIterator_free(fi);
i = 0;
for (index=0; index<totface; index++) {
CCGFace *f = faceMap2[index];
- int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
- VecCopyf(cos[i++], ccgSubSurf_getFaceCenterData(ss, f));
+ VecCopyf(cos[i++], ccgSubSurf_getFaceCenterData(f));
for (S=0; S<numVerts; S++) {
for (x=1; x<gridSize-1; x++) {
@@ -1420,7 +1427,7 @@ static void ccgDM_foreachMappedVert(DerivedMesh *dm, void (*func)(void *userData
for (; !ccgVertIterator_isStopped(vi); ccgVertIterator_next(vi)) {
CCGVert *v = ccgVertIterator_getCurrent(vi);
VertData *vd = ccgSubSurf_getVertData(ccgdm->ss, v);
- int index = ccgDM_getVertMapIndex(ccgdm, ccgdm->ss, v);
+ int index = ccgDM_getVertMapIndex(ccgdm->ss, v);
if (index!=-1)
func(userData, index, vd->co, vd->no, NULL);
@@ -1437,7 +1444,7 @@ static void ccgDM_foreachMappedEdge(DerivedMesh *dm, void (*func)(void *userData
for (; !ccgEdgeIterator_isStopped(ei); ccgEdgeIterator_next(ei)) {
CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
VertData *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
- int index = ccgDM_getEdgeMapIndex(ccgdm, ss, e);
+ int index = ccgDM_getEdgeMapIndex(ss, e);
if (index!=-1) {
for (i=0; i<edgeSize-1; i++)
@@ -1478,9 +1485,9 @@ static void ccgDM_drawVerts(DerivedMesh *dm) {
fi = ccgSubSurf_getFaceIterator(ss);
for (; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
- glVertex3fv(ccgSubSurf_getFaceCenterData(ss, f));
+ glVertex3fv(ccgSubSurf_getFaceCenterData(f));
for (S=0; S<numVerts; S++)
for (x=1; x<gridSize-1; x++)
glVertex3fv(ccgSubSurf_getFaceGridEdgeData(ss, f, S, x));
@@ -1507,7 +1514,7 @@ static void ccgDM_drawEdges(DerivedMesh *dm, int drawLooseEdges) {
CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
VertData *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
- if (!drawLooseEdges && !ccgSubSurf_getEdgeNumFaces(ss, e))
+ if (!drawLooseEdges && !ccgSubSurf_getEdgeNumFaces(e))
continue;
if (useAging && !(G.f&G_BACKBUFSEL)) {
@@ -1530,7 +1537,7 @@ static void ccgDM_drawEdges(DerivedMesh *dm, int drawLooseEdges) {
if (ccgdm->drawInteriorEdges) {
for (; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
for (S=0; S<numVerts; S++) {
VertData *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
@@ -1568,7 +1575,7 @@ static void ccgDM_drawLooseEdges(DerivedMesh *dm) {
CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
VertData *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
- if (!ccgSubSurf_getEdgeNumFaces(ss, e)) {
+ if (!ccgSubSurf_getEdgeNumFaces(e)) {
glBegin(GL_LINE_STRIP);
for (i=0; i<edgeSize-1; i++) {
glVertex3fv(edgeData[i].co);
@@ -1596,7 +1603,7 @@ static void ccgDM_glNormalFast(float *a, float *b, float *c, float *d)
}
/* Only used by non-editmesh types */
-static void ccgDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int)) {
+static void ccgDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int, void *attribs)) {
CCGDerivedMesh *ccgdm = (CCGDerivedMesh*) dm;
CCGSubSurf *ss = ccgdm->ss;
CCGFaceIterator *fi = ccgSubSurf_getFaceIterator(ss);
@@ -1605,8 +1612,8 @@ static void ccgDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int)) {
for (; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
- int index = (int) ccgSubSurf_getFaceFaceHandle(ss, f);
+ int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
+ int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(ss, f));
int drawSmooth, mat_nr;
if(faceFlags) {
@@ -1618,7 +1625,7 @@ static void ccgDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int)) {
mat_nr= 0;
}
- if (!setMaterial(mat_nr+1))
+ if (!setMaterial(mat_nr+1, NULL))
continue;
glShadeModel(drawSmooth? GL_SMOOTH: GL_FLAT);
@@ -1663,6 +1670,168 @@ static void ccgDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int)) {
ccgFaceIterator_free(fi);
}
+
+ /* Only used by non-editmesh types */
+static void ccgDM_drawMappedFacesGLSL(DerivedMesh *dm, int (*setMaterial)(int, void *attribs), int (*setDrawOptions)(void *userData, int index), void *userData) {
+ CCGDerivedMesh *ccgdm = (CCGDerivedMesh*) dm;
+ CCGSubSurf *ss = ccgdm->ss;
+ CCGFaceIterator *fi = ccgSubSurf_getFaceIterator(ss);
+ GPUVertexAttribs gattribs;
+ DMVertexAttribs attribs;
+ MTFace *tf = dm->getFaceDataArray(dm, CD_MTFACE);
+ int gridSize = ccgSubSurf_getGridSize(ss);
+ int gridFaces = gridSize - 1;
+ int edgeSize = ccgSubSurf_getEdgeSize(ss);
+ int transp, orig_transp, new_transp;
+ char *faceFlags = DM_get_face_data_layer(dm, CD_FLAGS);
+ int a, b, i, doDraw, numVerts, matnr, new_matnr, totface;
+
+ doDraw = 0;
+ numVerts = 0;
+ matnr = -1;
+ transp = GPU_get_material_blend_mode();
+ orig_transp = transp;
+
+ memset(&attribs, 0, sizeof(attribs));
+
+#define PASSATTRIB(dx, dy, vert) { \
+ if(attribs.totorco) { \
+ index = getFaceIndex(ss, f, S, x+dx, y+dy, edgeSize, gridSize); \
+ glVertexAttrib3fvARB(attribs.orco.glIndex, attribs.orco.array[index]); \
+ } \
+ for(b = 0; b < attribs.tottface; b++) { \
+ MTFace *tf = &attribs.tface[b].array[a]; \
+ glVertexAttrib2fvARB(attribs.tface[b].glIndex, tf->uv[vert]); \
+ } \
+ for(b = 0; b < attribs.totmcol; b++) { \
+ MCol *cp = &attribs.mcol[b].array[a*4 + vert]; \
+ GLubyte col[4]; \
+ col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a; \
+ glVertexAttrib4ubvARB(attribs.mcol[b].glIndex, col); \
+ } \
+ if(attribs.tottang) { \
+ float *tang = attribs.tang.array[a*4 + vert]; \
+ glVertexAttrib3fvARB(attribs.tang.glIndex, tang); \
+ } \
+}
+
+ totface = ccgSubSurf_getNumFaces(ss);
+ for(a = 0, i = 0; i < totface; i++) {
+ CCGFace *f = ccgdm->faceMap[i].face;
+ int S, x, y, drawSmooth;
+ int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(ss, f));
+ int origIndex = ccgDM_getFaceMapIndex(ss, f);
+
+ numVerts = ccgSubSurf_getFaceNumVerts(f);
+
+ if(faceFlags) {
+ drawSmooth = (faceFlags[index*4] & ME_SMOOTH);
+ new_matnr= faceFlags[index*4 + 1] + 1;
+ }
+ else {
+ drawSmooth = 1;
+ new_matnr= 1;
+ }
+
+ if(new_matnr != matnr) {
+ doDraw = setMaterial(matnr = new_matnr, &gattribs);
+ if(doDraw)
+ DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
+ }
+
+ if(!doDraw || (setDrawOptions && !setDrawOptions(userData, origIndex))) {
+ a += gridFaces*gridFaces*numVerts;
+ continue;
+ }
+
+ if(tf) {
+ new_transp = tf[i].transp;
+
+ if(new_transp != transp) {
+ if(new_transp == GPU_BLEND_SOLID && orig_transp != GPU_BLEND_SOLID)
+ GPU_set_material_blend_mode(orig_transp);
+ else
+ GPU_set_material_blend_mode(new_transp);
+ transp = new_transp;
+ }
+ }
+
+ glShadeModel(drawSmooth? GL_SMOOTH: GL_FLAT);
+ for (S=0; S<numVerts; S++) {
+ VertData *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
+ VertData *vda, *vdb;
+
+ if (drawSmooth) {
+ for (y=0; y<gridFaces; y++) {
+ glBegin(GL_QUAD_STRIP);
+ for (x=0; x<gridFaces; x++) {
+ vda = &faceGridData[(y+0)*gridSize + x];
+ vdb = &faceGridData[(y+1)*gridSize + x];
+
+ PASSATTRIB(0, 0, 0);
+ glNormal3fv(vda->no);
+ glVertex3fv(vda->co);
+
+ PASSATTRIB(0, 1, 1);
+ glNormal3fv(vdb->no);
+ glVertex3fv(vdb->co);
+
+ if(x != gridFaces-1)
+ a++;
+ }
+
+ vda = &faceGridData[(y+0)*gridSize + x];
+ vdb = &faceGridData[(y+1)*gridSize + x];
+
+ PASSATTRIB(0, 0, 3);
+ glNormal3fv(vda->no);
+ glVertex3fv(vda->co);
+
+ PASSATTRIB(0, 1, 2);
+ glNormal3fv(vdb->no);
+ glVertex3fv(vdb->co);
+
+ glEnd();
+
+ a++;
+ }
+ } else {
+ glBegin(GL_QUADS);
+ for (y=0; y<gridFaces; y++) {
+ for (x=0; x<gridFaces; x++) {
+ float *aco = faceGridData[(y+0)*gridSize + x].co;
+ float *bco = faceGridData[(y+0)*gridSize + x + 1].co;
+ float *cco = faceGridData[(y+1)*gridSize + x + 1].co;
+ float *dco = faceGridData[(y+1)*gridSize + x].co;
+
+ ccgDM_glNormalFast(aco, bco, cco, dco);
+
+ PASSATTRIB(0, 1, 1);
+ glVertex3fv(dco);
+ PASSATTRIB(1, 1, 2);
+ glVertex3fv(cco);
+ PASSATTRIB(1, 0, 3);
+ glVertex3fv(bco);
+ PASSATTRIB(0, 0, 0);
+ glVertex3fv(aco);
+
+ a++;
+ }
+ }
+ glEnd();
+ }
+ }
+ }
+
+#undef PASSATTRIB
+
+ ccgFaceIterator_free(fi);
+}
+
+static void ccgDM_drawFacesGLSL(DerivedMesh *dm, int (*setMaterial)(int, void *attribs)) {
+ dm->drawMappedFacesGLSL(dm, setMaterial, NULL, NULL);
+}
+
static void ccgDM_drawFacesColored(DerivedMesh *dm, int useTwoSided, unsigned char *col1, unsigned char *col2) {
CCGDerivedMesh *ccgdm = (CCGDerivedMesh*) dm;
CCGSubSurf *ss = ccgdm->ss;
@@ -1686,7 +1855,7 @@ static void ccgDM_drawFacesColored(DerivedMesh *dm, int useTwoSided, unsigned ch
glBegin(GL_QUADS);
for (; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
for (S=0; S<numVerts; S++) {
VertData *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
@@ -1744,9 +1913,9 @@ static void ccgDM_drawFacesTex_common(DerivedMesh *dm,
totface = ccgSubSurf_getNumFaces(ss);
for(i = 0; i < totface; i++) {
CCGFace *f = ccgdm->faceMap[i].face;
- int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
- int drawSmooth, index = ccgDM_getFaceMapIndex(ccgdm, ss, f);
- int origIndex = (int)ccgSubSurf_getFaceFaceHandle(ss, f);
+ int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
+ int drawSmooth, index = ccgDM_getFaceMapIndex(ss, f);
+ int origIndex = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(ss, f));
unsigned char *cp= NULL;
int mat_nr;
@@ -1827,28 +1996,28 @@ static void ccgDM_drawFacesTex_common(DerivedMesh *dm,
glBegin(GL_QUADS);
for (y=0; y<gridFaces; y++) {
for (x=0; x<gridFaces; x++) {
- float *a = faceGridData[(y+0)*gridSize + x].co;
- float *b = faceGridData[(y+0)*gridSize + x + 1].co;
- float *c = faceGridData[(y+1)*gridSize + x + 1].co;
- float *d = faceGridData[(y+1)*gridSize + x].co;
+ float *a_co = faceGridData[(y+0)*gridSize + x].co;
+ float *b_co = faceGridData[(y+0)*gridSize + x + 1].co;
+ float *c_co = faceGridData[(y+1)*gridSize + x + 1].co;
+ float *d_co = faceGridData[(y+1)*gridSize + x].co;
- ccgDM_glNormalFast(a, b, c, d);
+ ccgDM_glNormalFast(a_co, b_co, c_co, d_co);
if(tf) glTexCoord2fv(tf->uv[1]);
if(cp) glColor3ub(cp[7], cp[6], cp[5]);
- glVertex3fv(d);
+ glVertex3fv(d_co);
if(tf) glTexCoord2fv(tf->uv[2]);
if(cp) glColor3ub(cp[11], cp[10], cp[9]);
- glVertex3fv(c);
+ glVertex3fv(c_co);
if(tf) glTexCoord2fv(tf->uv[3]);
if(cp) glColor3ub(cp[15], cp[14], cp[13]);
- glVertex3fv(b);
+ glVertex3fv(b_co);
if(tf) glTexCoord2fv(tf->uv[0]);
if(cp) glColor3ub(cp[3], cp[2], cp[1]);
- glVertex3fv(a);
+ glVertex3fv(a_co);
if(tf) tf++;
if(cp) cp += 16;
@@ -1904,7 +2073,6 @@ static void ccgDM_drawUVEdges(DerivedMesh *dm)
}
static void ccgDM_drawMappedFaces(DerivedMesh *dm, int (*setDrawOptions)(void *userData, int index, int *drawSmooth_r), void *userData, int useColors) {
- GLubyte act_face_stipple[32*32/8] = DM_FACE_STIPPLE;
CCGDerivedMesh *ccgdm = (CCGDerivedMesh*) dm;
CCGSubSurf *ss = ccgdm->ss;
CCGFaceIterator *fi = ccgSubSurf_getFaceIterator(ss);
@@ -1913,11 +2081,11 @@ static void ccgDM_drawMappedFaces(DerivedMesh *dm, int (*setDrawOptions)(void *u
for (i=0; !ccgFaceIterator_isStopped(fi); i++,ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
- int drawSmooth, index = ccgDM_getFaceMapIndex(ccgdm, ss, f);
+ int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
+ int drawSmooth, index = ccgDM_getFaceMapIndex(ss, f);
int origIndex;
- origIndex = (int)ccgSubSurf_getFaceFaceHandle(ss, f);
+ origIndex = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(ss, f));
if(faceFlags) drawSmooth = (faceFlags[origIndex*4] & ME_SMOOTH);
else drawSmooth = 1;
@@ -1929,7 +2097,7 @@ static void ccgDM_drawMappedFaces(DerivedMesh *dm, int (*setDrawOptions)(void *u
if (draw) {
if (draw==2) {
glEnable(GL_POLYGON_STIPPLE);
- glPolygonStipple(act_face_stipple);
+ glPolygonStipple(0); //XXX stipple_quarttone);
}
for (S=0; S<numVerts; S++) {
@@ -1995,7 +2163,7 @@ static void ccgDM_drawMappedEdges(DerivedMesh *dm, int (*setDrawOptions)(void *u
for (; !ccgEdgeIterator_isStopped(ei); ccgEdgeIterator_next(ei)) {
CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
VertData *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
- int index = ccgDM_getEdgeMapIndex(ccgdm, ss, e);
+ int index = ccgDM_getEdgeMapIndex(ss, e);
glBegin(GL_LINE_STRIP);
if (index!=-1 && (!setDrawOptions || setDrawOptions(userData, index))) {
@@ -2025,7 +2193,7 @@ static void ccgDM_drawMappedEdgesInterp(DerivedMesh *dm, int (*setDrawOptions)(v
for (; !ccgEdgeIterator_isStopped(ei); ccgEdgeIterator_next(ei)) {
CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
VertData *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
- int index = ccgDM_getEdgeMapIndex(ccgdm, ss, e);
+ int index = ccgDM_getEdgeMapIndex(ss, e);
glBegin(GL_LINE_STRIP);
if (index!=-1 && (!setDrawOptions || setDrawOptions(userData, index))) {
@@ -2052,7 +2220,7 @@ static void ccgDM_foreachMappedFaceCenter(DerivedMesh *dm, void (*func)(void *us
for (; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- int index = ccgDM_getFaceMapIndex(ccgdm, ss, f);
+ int index = ccgDM_getFaceMapIndex(ss, f);
if (index!=-1) {
/* Face center data normal isn't updated atm. */
@@ -2088,17 +2256,17 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
int index, totvert, totedge, totface;
int i;
int vertNum, edgeNum, faceNum;
- int *vertOrigIndex, *edgeOrigIndex, *faceOrigIndex;
+ int *vertOrigIndex, *faceOrigIndex; /* *edgeOrigIndex - as yet, unused */
int *edgeFlags;
char *faceFlags;
int edgeSize;
int gridSize;
int gridFaces;
int gridSideVerts;
- int gridInternalVerts;
+ /*int gridInternalVerts; - as yet unused */
int gridSideEdges;
int gridInternalEdges;
- MVert *mvert = NULL;
+ /* MVert *mvert = NULL; - as yet unused */
MEdge *medge = NULL;
MFace *mface = NULL;
FaceVertWeight *qweight, *tweight;
@@ -2141,8 +2309,10 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
ccgdm->dm.drawFacesSolid = ccgDM_drawFacesSolid;
ccgdm->dm.drawFacesColored = ccgDM_drawFacesColored;
ccgdm->dm.drawFacesTex = ccgDM_drawFacesTex;
+ ccgdm->dm.drawFacesGLSL = ccgDM_drawFacesGLSL;
ccgdm->dm.drawMappedFaces = ccgDM_drawMappedFaces;
ccgdm->dm.drawMappedFacesTex = ccgDM_drawMappedFacesTex;
+ ccgdm->dm.drawMappedFacesGLSL = ccgDM_drawMappedFacesGLSL;
ccgdm->dm.drawUVEdges = ccgDM_drawUVEdges;
ccgdm->dm.drawMappedEdgesInterp = ccgDM_drawMappedEdgesInterp;
@@ -2160,7 +2330,7 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
for(; !ccgVertIterator_isStopped(vi); ccgVertIterator_next(vi)) {
CCGVert *v = ccgVertIterator_getCurrent(vi);
- ccgdm->vertMap[(int) ccgSubSurf_getVertVertHandle(ss, v)].vert = v;
+ ccgdm->vertMap[GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v))].vert = v;
}
ccgVertIterator_free(vi);
@@ -2170,7 +2340,7 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
for(; !ccgEdgeIterator_isStopped(ei); ccgEdgeIterator_next(ei)) {
CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
- ccgdm->edgeMap[(int) ccgSubSurf_getEdgeEdgeHandle(ss, e)].edge = e;
+ ccgdm->edgeMap[GET_INT_FROM_POINTER(ccgSubSurf_getEdgeEdgeHandle(e))].edge = e;
}
totface = ccgSubSurf_getNumFaces(ss);
@@ -2179,7 +2349,7 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
for(; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
CCGFace *f = ccgFaceIterator_getCurrent(fi);
- ccgdm->faceMap[(int) ccgSubSurf_getFaceFaceHandle(ss, f)].face = f;
+ ccgdm->faceMap[GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(ss, f))].face = f;
}
ccgFaceIterator_free(fi);
@@ -2187,7 +2357,7 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
gridSize = ccgSubSurf_getGridSize(ss);
gridFaces = gridSize - 1;
gridSideVerts = gridSize - 2;
- gridInternalVerts = gridSideVerts * gridSideVerts;
+ /*gridInternalVerts = gridSideVerts * gridSideVerts; - as yet, unused */
gridSideEdges = gridSize - 1;
gridInternalEdges = (gridSideEdges - 1) * gridSideEdges * 2;
@@ -2197,22 +2367,22 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
edgeNum = 0;
faceNum = 0;
- mvert = dm->getVertArray(dm);
+ /* mvert = dm->getVertArray(dm); - as yet unused */
medge = dm->getEdgeArray(dm);
mface = dm->getFaceArray(dm);
vertOrigIndex = DM_get_vert_data_layer(&ccgdm->dm, CD_ORIGINDEX);
- edgeOrigIndex = DM_get_edge_data_layer(&ccgdm->dm, CD_ORIGINDEX);
+ /*edgeOrigIndex = DM_get_edge_data_layer(&ccgdm->dm, CD_ORIGINDEX);*/
faceOrigIndex = DM_get_face_data_layer(&ccgdm->dm, CD_ORIGINDEX);
faceFlags = DM_get_face_data_layer(&ccgdm->dm, CD_FLAGS);
for(index = 0; index < totface; ++index) {
CCGFace *f = ccgdm->faceMap[index].face;
- int numVerts = ccgSubSurf_getFaceNumVerts(ss, f);
+ int numVerts = ccgSubSurf_getFaceNumVerts(f);
int numFinalEdges = numVerts * (gridSideEdges + gridInternalEdges);
- int mapIndex = ccgDM_getFaceMapIndex(ccgdm, ss, f);
- int origIndex = (int)ccgSubSurf_getFaceFaceHandle(ss, f);
+ int mapIndex = ccgDM_getFaceMapIndex(ss, f);
+ int origIndex = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(ss, f));
FaceVertWeight *weight = (numVerts == 4) ? qweight : tweight;
int S, x, y;
int vertIdx[4];
@@ -2227,7 +2397,7 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
for(S = 0; S < numVerts; S++) {
CCGVert *v = ccgSubSurf_getFaceVert(ss, f, S);
- vertIdx[S] = (int)ccgSubSurf_getVertVertHandle(ss, v);
+ vertIdx[S] = GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v));
}
DM_interp_vert_data(dm, &ccgdm->dm, vertIdx, weight[0][0],
@@ -2330,16 +2500,16 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
for(index = 0; index < totedge; ++index) {
CCGEdge *e = ccgdm->edgeMap[index].edge;
int numFinalEdges = edgeSize - 1;
- int mapIndex = ccgDM_getEdgeMapIndex(ccgdm, ss, e);
+ int mapIndex = ccgDM_getEdgeMapIndex(ss, e);
int x;
int vertIdx[2];
- int edgeIdx = (int)ccgSubSurf_getEdgeEdgeHandle(ss, e);
+ int edgeIdx = GET_INT_FROM_POINTER(ccgSubSurf_getEdgeEdgeHandle(e));
CCGVert *v;
- v = ccgSubSurf_getEdgeVert0(ss, e);
- vertIdx[0] = (int)ccgSubSurf_getVertVertHandle(ss, v);
- v = ccgSubSurf_getEdgeVert1(ss, e);
- vertIdx[1] = (int)ccgSubSurf_getVertVertHandle(ss, v);
+ v = ccgSubSurf_getEdgeVert0(e);
+ vertIdx[0] = GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v));
+ v = ccgSubSurf_getEdgeVert1(e);
+ vertIdx[1] = GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v));
ccgdm->edgeMap[index].startVert = vertNum;
ccgdm->edgeMap[index].startEdge = edgeNum;
@@ -2370,10 +2540,10 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
for(index = 0; index < totvert; ++index) {
CCGVert *v = ccgdm->vertMap[index].vert;
- int mapIndex = ccgDM_getVertMapIndex(ccgdm, ccgdm->ss, v);
+ int mapIndex = ccgDM_getVertMapIndex(ccgdm->ss, v);
int vertIdx;
- vertIdx = (int)ccgSubSurf_getVertVertHandle(ss, v);
+ vertIdx = GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v));
ccgdm->vertMap[index].startVert = vertNum;
@@ -2417,7 +2587,14 @@ struct DerivedMesh *subsurf_make_derived_from_derived(
useSubsurfUv, dm);
} else if(useRenderParams) {
/* Do not use cache in render mode. */
- CCGSubSurf *ss = _getSubSurf(NULL, smd->renderLevels, 0, 1, useSimple);
+ CCGSubSurf *ss;
+ int levels;
+
+ levels= get_render_subsurf_level(&G.scene->r, smd->renderLevels);
+ if(levels == 0)
+ return dm;
+
+ ss = _getSubSurf(NULL, levels, 0, 1, useSimple);
ss_sync_from_derivedmesh(ss, dm, vertCos, useSimple);
@@ -2499,9 +2676,9 @@ void subsurf_calculate_limit_positions(Mesh *me, float (*positions_r)[3])
vi = ccgSubSurf_getVertIterator(ss);
for (; !ccgVertIterator_isStopped(vi); ccgVertIterator_next(vi)) {
CCGVert *v = ccgVertIterator_getCurrent(vi);
- int idx = (int) ccgSubSurf_getVertVertHandle(ss, v);
- int N = ccgSubSurf_getVertNumEdges(ss, v);
- int numFaces = ccgSubSurf_getVertNumFaces(ss, v);
+ int idx = GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v));
+ int N = ccgSubSurf_getVertNumEdges(v);
+ int numFaces = ccgSubSurf_getVertNumFaces(v);
float *co;
int i;
@@ -2509,12 +2686,12 @@ void subsurf_calculate_limit_positions(Mesh *me, float (*positions_r)[3])
face_sum[0]= face_sum[1]= face_sum[2]= 0.0;
for (i=0; i<N; i++) {
- CCGEdge *e = ccgSubSurf_getVertEdge(ss, v, i);
+ CCGEdge *e = ccgSubSurf_getVertEdge(v, i);
VecAddf(edge_sum, edge_sum, ccgSubSurf_getEdgeData(ss, e, 1));
}
for (i=0; i<numFaces; i++) {
- CCGFace *f = ccgSubSurf_getVertFace(ss, v, i);
- VecAddf(face_sum, face_sum, ccgSubSurf_getFaceCenterData(ss, f));
+ CCGFace *f = ccgSubSurf_getVertFace(v, i);
+ VecAddf(face_sum, face_sum, ccgSubSurf_getFaceCenterData(f));
}
/* ad-hoc correction for boundary vertices, to at least avoid them
diff --git a/source/blender/blenkernel/intern/suggestions.c b/source/blender/blenkernel/intern/suggestions.c
new file mode 100644
index 00000000000..6530909336c
--- /dev/null
+++ b/source/blender/blenkernel/intern/suggestions.c
@@ -0,0 +1,254 @@
+/**
+ * $Id: $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2008, Blender Foundation
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Ian Thompson.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+
+#include "MEM_guardedalloc.h"
+#include "BLI_blenlib.h"
+#include "DNA_text_types.h"
+#include "BKE_text.h"
+#include "BKE_suggestions.h"
+
+/**********************/
+/* Static definitions */
+/**********************/
+
+static Text *activeToolText = NULL;
+static SuggList suggestions = {NULL, NULL, NULL, NULL, NULL};
+static char *documentation = NULL;
+//static int doc_lines = 0;
+
+static int txttl_cmp(const char *first, const char *second, int len) {
+ int cmp, i;
+ for (cmp=0, i=0; i<len; i++) {
+ if ( (cmp= toupper(first[i])-toupper(second[i])) ) {
+ break;
+ }
+ }
+ return cmp;
+}
+
+static void txttl_free_suggest() {
+ SuggItem *item, *prev;
+ for (item = suggestions.last; item; item=prev) {
+ prev = item->prev;
+ MEM_freeN(item);
+ }
+ suggestions.first = suggestions.last = NULL;
+ suggestions.firstmatch = suggestions.lastmatch = NULL;
+ suggestions.selected = NULL;
+ suggestions.top = 0;
+}
+
+static void txttl_free_docs() {
+ if (documentation) {
+ MEM_freeN(documentation);
+ documentation = NULL;
+ }
+}
+
+/**************************/
+/* General tool functions */
+/**************************/
+
+void free_texttools() {
+ txttl_free_suggest();
+ txttl_free_docs();
+}
+
+void texttool_text_set_active(Text *text) {
+ if (activeToolText == text) return;
+ texttool_text_clear();
+ activeToolText = text;
+}
+
+void texttool_text_clear() {
+ free_texttools();
+ activeToolText = NULL;
+}
+
+short texttool_text_is_active(Text *text) {
+ return activeToolText==text ? 1 : 0;
+}
+
+/***************************/
+/* Suggestion list methods */
+/***************************/
+
+void texttool_suggest_add(const char *name, char type) {
+ SuggItem *newitem, *item;
+ int len, cmp;
+
+ newitem = MEM_mallocN(sizeof(SuggItem) + strlen(name) + 1, "SuggestionItem");
+ if (!newitem) {
+ printf("Failed to allocate memory for suggestion.\n");
+ return;
+ }
+
+ newitem->name = (char *) (newitem + 1);
+ len = strlen(name);
+ strncpy(newitem->name, name, len);
+ newitem->name[len] = '\0';
+ newitem->type = type;
+ newitem->prev = newitem->next = NULL;
+
+ /* Perform simple linear search for ordered storage */
+ if (!suggestions.first || !suggestions.last) {
+ suggestions.first = suggestions.last = newitem;
+ } else {
+ cmp = -1;
+ for (item=suggestions.last; item; item=item->prev) {
+ cmp = txttl_cmp(name, item->name, len);
+
+ /* Newitem comes after this item, insert here */
+ if (cmp >= 0) {
+ newitem->prev = item;
+ if (item->next)
+ item->next->prev = newitem;
+ newitem->next = item->next;
+ item->next = newitem;
+
+ /* At last item, set last pointer here */
+ if (item == suggestions.last)
+ suggestions.last = newitem;
+ break;
+ }
+ }
+ /* Reached beginning of list, insert before first */
+ if (cmp < 0) {
+ newitem->next = suggestions.first;
+ suggestions.first->prev = newitem;
+ suggestions.first = newitem;
+ }
+ }
+ suggestions.firstmatch = suggestions.lastmatch = suggestions.selected = NULL;
+ suggestions.top= 0;
+}
+
+void texttool_suggest_prefix(const char *prefix) {
+ SuggItem *match, *first, *last;
+ int cmp, len = strlen(prefix), top = 0;
+
+ if (!suggestions.first) return;
+ if (len==0) {
+ suggestions.selected = suggestions.firstmatch = suggestions.first;
+ suggestions.lastmatch = suggestions.last;
+ return;
+ }
+
+ first = last = NULL;
+ for (match=suggestions.first; match; match=match->next) {
+ cmp = txttl_cmp(prefix, match->name, len);
+ if (cmp==0) {
+ if (!first) {
+ first = match;
+ suggestions.top = top;
+ }
+ } else if (cmp<0) {
+ if (!last) {
+ last = match->prev;
+ break;
+ }
+ }
+ top++;
+ }
+ if (first) {
+ if (!last) last = suggestions.last;
+ suggestions.firstmatch = first;
+ suggestions.lastmatch = last;
+ suggestions.selected = first;
+ } else {
+ suggestions.firstmatch = NULL;
+ suggestions.lastmatch = NULL;
+ suggestions.selected = NULL;
+ suggestions.top = 0;
+ }
+}
+
+void texttool_suggest_clear() {
+ txttl_free_suggest();
+}
+
+SuggItem *texttool_suggest_first() {
+ return suggestions.firstmatch;
+}
+
+SuggItem *texttool_suggest_last() {
+ return suggestions.lastmatch;
+}
+
+void texttool_suggest_select(SuggItem *sel) {
+ suggestions.selected = sel;
+}
+
+SuggItem *texttool_suggest_selected() {
+ return suggestions.selected;
+}
+
+int *texttool_suggest_top() {
+ return &suggestions.top;
+}
+
+/*************************/
+/* Documentation methods */
+/*************************/
+
+void texttool_docs_show(const char *docs) {
+ int len;
+
+ if (!docs) return;
+
+ len = strlen(docs);
+
+ if (documentation) {
+ MEM_freeN(documentation);
+ documentation = NULL;
+ }
+
+ /* Ensure documentation ends with a '\n' */
+ if (docs[len-1] != '\n') {
+ documentation = MEM_mallocN(len+2, "Documentation");
+ strncpy(documentation, docs, len);
+ documentation[len++] = '\n';
+ } else {
+ documentation = MEM_mallocN(len+1, "Documentation");
+ strncpy(documentation, docs, len);
+ }
+ documentation[len] = '\0';
+}
+
+char *texttool_docs_get() {
+ return documentation;
+}
+
+void texttool_docs_clear() {
+ txttl_free_docs();
+}
diff --git a/source/blender/blenkernel/intern/text.c b/source/blender/blenkernel/intern/text.c
index 0dbaa9d3843..d1d252ab210 100644
--- a/source/blender/blenkernel/intern/text.c
+++ b/source/blender/blenkernel/intern/text.c
@@ -30,6 +30,8 @@
*/
#include <string.h> /* strstr */
+#include <sys/types.h>
+#include <sys/stat.h>
#include "MEM_guardedalloc.h"
@@ -44,7 +46,9 @@
#include "BKE_global.h"
#include "BKE_main.h"
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h"
+#endif
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -80,12 +84,19 @@ The st->top determines at what line the top of the text is displayed.
If the user moves the cursor the st containing that cursor should
be popped ... other st's retain their own top location.
-*/ /***************/
-
+Markers
+--
+The mrk->flags define the behaviour and relationships between markers. The
+upper two bytes are used to hold a group ID, the lower two are normal flags. If
+TMARK_EDITALL is set the group ID defines which other markers should be edited.
-/****************/ /*
- Undo
+The mrk->clr field is used to visually group markers where the flags may not
+match. A template system, for example, may allow editing of repeating tokens
+(in one group) but include other marked positions (in another group) all in the
+same template with the same colour.
+Undo
+--
Undo/Redo works by storing
events in a queue, and a pointer
to the current position in the
@@ -144,10 +155,13 @@ void free_text(Text *text)
}
BLI_freelistN(&text->lines);
+ BLI_freelistN(&text->markers);
if(text->name) MEM_freeN(text->name);
MEM_freeN(text->undo_buf);
+#ifndef DISABLE_PYTHON
if (text->compiled) BPY_free_compiled_text(text);
+#endif
}
Text *add_empty_text(char *name)
@@ -168,10 +182,11 @@ Text *add_empty_text(char *name)
ta->flags= TXT_ISDIRTY | TXT_ISTMP | TXT_ISMEM;
ta->lines.first= ta->lines.last= NULL;
+ ta->markers.first= ta->markers.last= NULL;
tmp= (TextLine*) MEM_mallocN(sizeof(TextLine), "textline");
tmp->line= (char*) MEM_mallocN(1, "textline_string");
- tmp->format= (char*) MEM_mallocN(2, "Syntax_format");
+ tmp->format= NULL;
tmp->line[0]=0;
tmp->len= 0;
@@ -208,18 +223,18 @@ static void cleanup_textline(TextLine * tl)
int reopen_text(Text *text)
{
FILE *fp;
- int i, llen, len;
+ int i, llen, len, res;
unsigned char *buffer;
TextLine *tmp;
- char sdir[FILE_MAXDIR];
char sfile[FILE_MAXFILE];
char str[FILE_MAXDIR+FILE_MAXFILE];
+ struct stat st;
if (!text || !text->name) return 0;
BLI_strncpy(str, text->name, FILE_MAXDIR+FILE_MAXFILE);
- BLI_convertstringcode(str, G.sce, G.scene->r.cfra);
- BLI_split_dirfile(str, sdir, sfile);
+ BLI_convertstringcode(str, G.sce);
+ BLI_split_dirfile_basic(str, NULL, sfile);
fp= fopen(str, "r");
if(fp==NULL) return 0;
@@ -242,7 +257,7 @@ int reopen_text(Text *text)
text->undo_len= TXT_INIT_UNDO;
text->undo_buf= MEM_mallocN(text->undo_len, "undo buf");
- text->flags= TXT_ISDIRTY | TXT_ISTMP;
+ text->flags= TXT_ISTMP;
fseek(fp, 0L, SEEK_END);
len= ftell(fp);
@@ -256,6 +271,9 @@ int reopen_text(Text *text)
len = fread(buffer, 1, len, fp);
fclose(fp);
+
+ res= stat(str, &st);
+ text->mtime= st.st_mtime;
text->nlines=0;
i=0;
@@ -264,7 +282,7 @@ int reopen_text(Text *text)
if (buffer[i]=='\n') {
tmp= (TextLine*) MEM_mallocN(sizeof(TextLine), "textline");
tmp->line= (char*) MEM_mallocN(llen+1, "textline_string");
- tmp->format= (char*) MEM_mallocN(llen+2, "Syntax_format");
+ tmp->format= NULL;
if(llen) memcpy(tmp->line, &buffer[i-llen], llen);
tmp->line[llen]=0;
@@ -284,7 +302,7 @@ int reopen_text(Text *text)
if (llen!=0 || text->nlines==0) {
tmp= (TextLine*) MEM_mallocN(sizeof(TextLine), "textline");
tmp->line= (char*) MEM_mallocN(llen+1, "textline_string");
- tmp->format= (char*) MEM_mallocN(llen+2, "Syntax_format");
+ tmp->format= NULL;
if(llen) memcpy(tmp->line, &buffer[i-llen], llen);
@@ -307,18 +325,18 @@ int reopen_text(Text *text)
Text *add_text(char *file)
{
FILE *fp;
- int i, llen, len;
+ int i, llen, len, res;
unsigned char *buffer;
TextLine *tmp;
Text *ta;
- char sdir[FILE_MAXDIR];
char sfile[FILE_MAXFILE];
char str[FILE_MAXDIR+FILE_MAXFILE];
+ struct stat st;
BLI_strncpy(str, file, FILE_MAXDIR+FILE_MAXFILE);
if (G.scene) /* can be NULL (bg mode) */
- BLI_convertstringcode(str, G.sce, G.scene->r.cfra);
- BLI_split_dirfile(str, sdir, sfile);
+ BLI_convertstringcode(str, G.sce);
+ BLI_split_dirfile_basic(str, NULL, sfile);
fp= fopen(str, "r");
if(fp==NULL) return NULL;
@@ -327,6 +345,7 @@ Text *add_text(char *file)
ta->id.us= 1;
ta->lines.first= ta->lines.last= NULL;
+ ta->markers.first= ta->markers.last= NULL;
ta->curl= ta->sell= NULL;
/* ta->flags= TXT_ISTMP | TXT_ISEXT; */
@@ -349,6 +368,9 @@ Text *add_text(char *file)
len = fread(buffer, 1, len, fp);
fclose(fp);
+
+ res= stat(str, &st);
+ ta->mtime= st.st_mtime;
ta->nlines=0;
i=0;
@@ -357,7 +379,7 @@ Text *add_text(char *file)
if (buffer[i]=='\n') {
tmp= (TextLine*) MEM_mallocN(sizeof(TextLine), "textline");
tmp->line= (char*) MEM_mallocN(llen+1, "textline_string");
- tmp->format= (char*) MEM_mallocN(llen+2, "Syntax_format");
+ tmp->format= NULL;
if(llen) memcpy(tmp->line, &buffer[i-llen], llen);
tmp->line[llen]=0;
@@ -377,7 +399,7 @@ Text *add_text(char *file)
if (llen!=0 || ta->nlines==0) {
tmp= (TextLine*) MEM_mallocN(sizeof(TextLine), "textline");
tmp->line= (char*) MEM_mallocN(llen+1, "textline_string");
- tmp->format= (char*) MEM_mallocN(llen+2, "Syntax_format");
+ tmp->format= NULL;
if(llen) memcpy(tmp->line, &buffer[i-llen], llen);
@@ -411,6 +433,7 @@ Text *copy_text(Text *ta)
tan->flags = ta->flags | TXT_ISDIRTY | TXT_ISTMP;
tan->lines.first= tan->lines.last= NULL;
+ tan->markers.first= tan->markers.last= NULL;
tan->curl= tan->sell= NULL;
tan->nlines= ta->nlines;
@@ -420,7 +443,7 @@ Text *copy_text(Text *ta)
while (line) {
tmp= (TextLine*) MEM_mallocN(sizeof(TextLine), "textline");
tmp->line= MEM_mallocN(line->len+1, "textline_string");
- tmp->format= MEM_mallocN(line->len+2, "Syntax_format");
+ tmp->format= NULL;
strcpy(tmp->line, line->line);
@@ -441,14 +464,14 @@ Text *copy_text(Text *ta)
/* Editing utility functions */
/*****************************/
-static void make_new_line (TextLine *line, char *newline, char *newformat)
+static void make_new_line (TextLine *line, char *newline)
{
if (line->line) MEM_freeN(line->line);
if (line->format) MEM_freeN(line->format);
line->line= newline;
line->len= strlen(newline);
- line->format= newformat;
+ line->format= NULL;
}
static TextLine *txt_new_line(char *str)
@@ -459,7 +482,7 @@ static TextLine *txt_new_line(char *str)
tmp= (TextLine *) MEM_mallocN(sizeof(TextLine), "textline");
tmp->line= MEM_mallocN(strlen(str)+1, "textline_string");
- tmp->format= MEM_mallocN(strlen(str)+2, "Syntax_format");
+ tmp->format= NULL;
strcpy(tmp->line, str);
@@ -477,7 +500,7 @@ static TextLine *txt_new_linen(char *str, int n)
tmp= (TextLine *) MEM_mallocN(sizeof(TextLine), "textline");
tmp->line= MEM_mallocN(n+1, "textline_string");
- tmp->format= MEM_mallocN(n+2, "Syntax_format");
+ tmp->format= NULL;
BLI_strncpy(tmp->line, str, n+1);
@@ -551,7 +574,23 @@ int txt_get_span (TextLine *from, TextLine *to)
static void txt_make_dirty (Text *text)
{
text->flags |= TXT_ISDIRTY;
+#ifndef DISABLE_PYTHON
if (text->compiled) BPY_free_compiled_text(text);
+#endif
+}
+
+/* 0:whitespace, 1:punct, 2:alphanumeric */
+static short txt_char_type (char ch)
+{
+ if (ch <= ' ') return 0; /* 32 */
+ if (ch <= '/') return 1; /* 47 */
+ if (ch <= '9') return 2; /* 57 */
+ if (ch <= '@') return 1; /* 64 */
+ if (ch <= 'Z') return 2; /* 90 */
+ if (ch == '_') return 2; /* 95, dont delimit '_' */
+ if (ch <= '`') return 1; /* 96 */
+ if (ch <= 'z') return 2; /* 122 */
+ return 1;
}
/****************************/
@@ -607,8 +646,7 @@ void txt_move_up(Text *text, short sel)
if(!undoing) txt_undo_add_op(text, sel?UNDO_SUP:UNDO_CUP);
}
} else {
- *charp= 0;
- if(!undoing) txt_undo_add_op(text, sel?UNDO_SUP:UNDO_CUP);
+ txt_move_bol(text, sel);
}
if(!sel) txt_pop_sel(text);
@@ -633,8 +671,7 @@ void txt_move_down(Text *text, short sel)
} else
if(!undoing) txt_undo_add_op(text, sel?UNDO_SDOWN:UNDO_CDOWN);
} else {
- *charp= (*linep)->len;
- if(!undoing) txt_undo_add_op(text, sel?UNDO_SDOWN:UNDO_CDOWN);
+ txt_move_eol(text, sel);
}
if(!sel) txt_pop_sel(text);
@@ -690,6 +727,68 @@ void txt_move_right(Text *text, short sel)
if(!sel) txt_pop_sel(text);
}
+void txt_jump_left(Text *text, short sel)
+{
+ TextLine **linep, *oldl;
+ int *charp, oldc, count, i;
+ unsigned char oldu;
+
+ if (!text) return;
+ if(sel) txt_curs_sel(text, &linep, &charp);
+ else { txt_pop_first(text); txt_curs_cur(text, &linep, &charp); }
+ if (!*linep) return;
+
+ oldl= *linep;
+ oldc= *charp;
+ oldu= undoing;
+ undoing= 1; /* Don't push individual moves to undo stack */
+
+ count= 0;
+ for (i=0; i<3; i++) {
+ if (count < 2) {
+ while (*charp>0 && txt_char_type((*linep)->line[*charp-1])==i) {
+ txt_move_left(text, sel);
+ count++;
+ }
+ }
+ }
+ if (count==0) txt_move_left(text, sel);
+
+ undoing= oldu;
+ if(!undoing) txt_undo_add_toop(text, sel?UNDO_STO:UNDO_CTO, txt_get_span(text->lines.first, oldl), oldc, txt_get_span(text->lines.first, *linep), (unsigned short)*charp);
+}
+
+void txt_jump_right(Text *text, short sel)
+{
+ TextLine **linep, *oldl;
+ int *charp, oldc, count, i;
+ unsigned char oldu;
+
+ if (!text) return;
+ if(sel) txt_curs_sel(text, &linep, &charp);
+ else { txt_pop_last(text); txt_curs_cur(text, &linep, &charp); }
+ if (!*linep) return;
+
+ oldl= *linep;
+ oldc= *charp;
+ oldu= undoing;
+ undoing= 1; /* Don't push individual moves to undo stack */
+
+ count= 0;
+ for (i=0; i<3; i++) {
+ if (count < 2) {
+ while (*charp<(*linep)->len && txt_char_type((*linep)->line[*charp])==i) {
+ txt_move_right(text, sel);
+ count++;
+ }
+ }
+ }
+ if (count==0) txt_move_right(text, sel);
+
+ undoing= oldu;
+ if(!undoing) txt_undo_add_toop(text, sel?UNDO_STO:UNDO_CTO, txt_get_span(text->lines.first, oldl), oldc, txt_get_span(text->lines.first, *linep), (unsigned short)*charp);
+}
+
void txt_move_bol (Text *text, short sel)
{
TextLine **linep;
@@ -762,6 +861,11 @@ void txt_move_eof (Text *text, short sel)
void txt_move_toline (Text *text, unsigned int line, short sel)
{
+ txt_move_to(text, line, 0, sel);
+}
+
+void txt_move_to (Text *text, unsigned int line, unsigned int ch, short sel)
+{
TextLine **linep, *oldl;
int *charp, oldc;
unsigned int i;
@@ -778,10 +882,12 @@ void txt_move_toline (Text *text, unsigned int line, short sel)
if ((*linep)->next) *linep= (*linep)->next;
else break;
}
- *charp= 0;
+ if (ch>(*linep)->len)
+ ch= (*linep)->len;
+ *charp= ch;
if(!sel) txt_pop_sel(text);
- if(!undoing) txt_undo_add_toop(text, sel?UNDO_STO:UNDO_CTO, txt_get_span(text->lines.first, oldl), oldc, txt_get_span(text->lines.first, *linep), (unsigned short)*charp);
+ if(!undoing) txt_undo_add_toop(text, sel?UNDO_STO:UNDO_CTO, txt_get_span(text->lines.first, oldl), oldc, txt_get_span(text->lines.first, *linep), (unsigned short)*charp);
}
/****************************/
@@ -866,7 +972,9 @@ int txt_has_sel(Text *text)
static void txt_delete_sel (Text *text)
{
TextLine *tmpl;
- char *buf, *format;
+ TextMarker *mrk;
+ char *buf;
+ int move, lineno;
if (!text) return;
if (!text->curl) return;
@@ -883,13 +991,33 @@ static void txt_delete_sel (Text *text)
}
buf= MEM_mallocN(text->curc+(text->sell->len - text->selc)+1, "textline_string");
- format= MEM_mallocN(text->curc+(text->sell->len - text->selc)+2, "Syntax_format");
+ if (text->curl != text->sell) {
+ txt_clear_marker_region(text, text->curl, text->curc, text->curl->len, 0, 0);
+ move= txt_get_span(text->curl, text->sell);
+ } else {
+ mrk= txt_find_marker_region(text, text->curl, text->curc, text->selc, 0, 0);
+ if (mrk && (mrk->start > text->curc || mrk->end < text->selc))
+ txt_clear_marker_region(text, text->curl, text->curc, text->selc, 0, 0);
+ move= 0;
+ }
+
+ mrk= txt_find_marker_region(text, text->sell, text->selc-1, text->sell->len, 0, 0);
+ if (mrk) {
+ lineno= mrk->lineno;
+ do {
+ mrk->lineno -= move;
+ if (mrk->start > text->curc) mrk->start -= text->selc - text->curc;
+ mrk->end -= text->selc - text->curc;
+ mrk= mrk->next;
+ } while (mrk && mrk->lineno==lineno);
+ }
+
strncpy(buf, text->curl->line, text->curc);
strcpy(buf+text->curc, text->sell->line + text->selc);
buf[text->curc+(text->sell->len - text->selc)]=0;
- make_new_line(text->curl, buf, format);
+ make_new_line(text->curl, buf);
tmpl= text->sell;
while (tmpl != text->curl) {
@@ -943,7 +1071,8 @@ char *txt_to_buf (Text *text)
if (!text) return NULL;
if (!text->curl) return NULL;
if (!text->sell) return NULL;
-
+ if (!text->lines.first) return NULL;
+
linef= text->lines.first;
charf= 0;
@@ -995,22 +1124,31 @@ char *txt_to_buf (Text *text)
return buf;
}
-int txt_find_string(Text *text, char *findstr)
+int txt_find_string(Text *text, char *findstr, int wrap)
{
TextLine *tl, *startl;
char *s= NULL;
+ int oldcl, oldsl, oldcc, oldsc;
if (!text || !text->curl || !text->sell) return 0;
txt_order_cursors(text);
+ oldcl= txt_get_span(text->lines.first, text->curl);
+ oldsl= txt_get_span(text->lines.first, text->sell);
tl= startl= text->sell;
+ oldcc= text->curc;
+ oldsc= text->selc;
s= strstr(&tl->line[text->selc], findstr);
while (!s) {
tl= tl->next;
- if (!tl)
- tl= text->lines.first;
+ if (!tl) {
+ if (wrap)
+ tl= text->lines.first;
+ else
+ break;
+ }
s= strstr(tl->line, findstr);
if (tl==startl)
@@ -1018,10 +1156,10 @@ int txt_find_string(Text *text, char *findstr)
}
if (s) {
- text->curl= text->sell= tl;
- text->curc= (int) (s-tl->line);
- text->selc= text->curc + strlen(findstr);
-
+ int newl= txt_get_span(text->lines.first, tl);
+ int newc= (int)(s-tl->line);
+ txt_move_to(text, newl, newc, 0);
+ txt_move_to(text, newl, newc + strlen(findstr), 1);
return 1;
} else
return 0;
@@ -1029,7 +1167,8 @@ int txt_find_string(Text *text, char *findstr)
void txt_cut_sel (Text *text)
{
- txt_copy_sel(text);
+ if (!G.background) /* Python uses txt_cut_sel, which it should not, working around for now */
+ ; //XXX txt_copy_clipboard(text);
txt_delete_sel(text);
txt_make_dirty(text);
@@ -1620,7 +1759,6 @@ void txt_do_undo(Text *text)
case UNDO_SWAP:
txt_curs_swap(text);
- txt_do_undo(text); /* swaps should appear transparent */
break;
case UNDO_DBLOCK:
@@ -1735,6 +1873,19 @@ void txt_do_undo(Text *text)
break;
}
+
+ /* next undo step may need evaluating */
+ if (text->undo_pos>=0) {
+ switch (text->undo_buf[text->undo_pos]) {
+ case UNDO_STO:
+ txt_do_undo(text);
+ txt_do_redo(text); /* selections need restoring */
+ break;
+ case UNDO_SWAP:
+ txt_do_undo(text); /* swaps should appear transparent */
+ break;
+ }
+ }
undoing= 0;
}
@@ -1809,7 +1960,7 @@ void txt_do_redo(Text *text)
case UNDO_SWAP:
txt_curs_swap(text);
- txt_do_undo(text); /* swaps should appear transparent a*/
+ txt_do_redo(text); /* swaps should appear transparent a*/
break;
case UNDO_CTO:
@@ -1946,22 +2097,37 @@ void txt_do_redo(Text *text)
void txt_split_curline (Text *text)
{
TextLine *ins;
- char *left, *right, *fleft, *fright;
+ TextMarker *mrk;
+ char *left, *right;
+ int lineno= -1;
if (!text) return;
if (!text->curl) return;
- txt_delete_sel(text);
+ txt_delete_sel(text);
+
+ /* Move markers */
+
+ lineno= txt_get_span(text->lines.first, text->curl);
+ mrk= text->markers.first;
+ while (mrk) {
+ if (mrk->lineno==lineno && mrk->start>text->curc) {
+ mrk->lineno++;
+ mrk->start -= text->curc;
+ mrk->end -= text->curc;
+ } else if (mrk->lineno > lineno) {
+ mrk->lineno++;
+ }
+ mrk= mrk->next;
+ }
/* Make the two half strings */
left= MEM_mallocN(text->curc+1, "textline_string");
- fleft= MEM_mallocN(text->curc+2, "Syntax_format");
if (text->curc) memcpy(left, text->curl->line, text->curc);
left[text->curc]=0;
right= MEM_mallocN(text->curl->len - text->curc+1, "textline_string");
- fright= MEM_mallocN(text->curl->len - text->curc+2, "Syntax_format");
if (text->curl->len - text->curc) memcpy(right, text->curl->line+text->curc, text->curl->len-text->curc);
right[text->curl->len - text->curc]=0;
@@ -1972,11 +2138,11 @@ void txt_split_curline (Text *text)
ins= MEM_mallocN(sizeof(TextLine), "textline");
ins->line= left;
- ins->format= fleft;
+ ins->format= NULL;
ins->len= text->curc;
text->curl->line= right;
- text->curl->format= fright;
+ text->curl->format= NULL;
text->curl->len= text->curl->len - text->curc;
BLI_insertlinkbefore(&text->lines, text->curl, ins);
@@ -1992,9 +2158,23 @@ void txt_split_curline (Text *text)
static void txt_delete_line (Text *text, TextLine *line)
{
+ TextMarker *mrk=NULL, *nxt;
+ int lineno= -1;
+
if (!text) return;
if (!text->curl) return;
+ lineno= txt_get_span(text->lines.first, line);
+ mrk= text->markers.first;
+ while (mrk) {
+ nxt= mrk->next;
+ if (mrk->lineno==lineno)
+ BLI_freelinkN(&text->markers, mrk);
+ else if (mrk->lineno > lineno)
+ mrk->lineno--;
+ mrk= nxt;
+ }
+
BLI_remlink (&text->lines, line);
if (line->line) MEM_freeN(line->line);
@@ -2008,21 +2188,35 @@ static void txt_delete_line (Text *text, TextLine *line)
static void txt_combine_lines (Text *text, TextLine *linea, TextLine *lineb)
{
- char *tmp, *format;
+ char *tmp;
+ TextMarker *mrk= NULL;
+ int lineno=-1;
if (!text) return;
if(!linea || !lineb) return;
+
+ mrk= txt_find_marker_region(text, lineb, 0, lineb->len, 0, 0);
+ if (mrk) {
+ lineno= mrk->lineno;
+ do {
+ mrk->lineno--;
+ mrk->start += linea->len;
+ mrk->end += linea->len;
+ mrk= mrk->next;
+ } while (mrk && mrk->lineno==lineno);
+ }
+ if (lineno==-1) lineno= txt_get_span(text->lines.first, lineb);
+ if (!mrk) mrk= text->markers.first;
tmp= MEM_mallocN(linea->len+lineb->len+1, "textline_string");
- format= MEM_mallocN(linea->len+lineb->len+1, "Syntax_format");
strcpy(tmp, linea->line);
strcat(tmp, lineb->line);
- make_new_line(linea, tmp, format);
+ make_new_line(linea, tmp);
- txt_delete_line(text, lineb);
+ txt_delete_line(text, lineb);
txt_make_dirty(text);
txt_clean_text(text);
@@ -2036,7 +2230,9 @@ void txt_delete_char (Text *text)
if (!text->curl) return;
if (txt_has_sel(text)) { /* deleting a selection */
- txt_delete_sel(text);
+ txt_delete_sel(text);
+ txt_make_dirty(text);
+ return;
}
else if (text->curc== text->curl->len) { /* Appending two lines */
if (text->curl->next) {
@@ -2045,6 +2241,24 @@ void txt_delete_char (Text *text)
}
} else { /* Just deleting a char */
int i= text->curc;
+
+ TextMarker *mrk= txt_find_marker_region(text, text->curl, i-1, text->curl->len, 0, 0);
+ if (mrk) {
+ int lineno= mrk->lineno;
+ if (mrk->end==i) {
+ if ((mrk->flags & TMARK_TEMP) && !(mrk->flags & TMARK_EDITALL)) {
+ txt_clear_markers(text, mrk->group, TMARK_TEMP);
+ } else {
+ BLI_freelinkN(&text->markers, mrk);
+ }
+ return;
+ }
+ do {
+ if (mrk->start>i) mrk->start--;
+ mrk->end--;
+ mrk= mrk->next;
+ } while (mrk && mrk->lineno==lineno);
+ }
c= text->curl->line[i];
while(i< text->curl->len) {
@@ -2062,6 +2276,12 @@ void txt_delete_char (Text *text)
if(!undoing) txt_undo_add_charop(text, UNDO_DEL, c);
}
+void txt_delete_word (Text *text)
+{
+ txt_jump_right(text, 1);
+ txt_delete_sel(text);
+}
+
void txt_backspace_char (Text *text)
{
char c='\n';
@@ -2070,29 +2290,49 @@ void txt_backspace_char (Text *text)
if (!text->curl) return;
if (txt_has_sel(text)) { /* deleting a selection */
- txt_delete_sel(text);
+ txt_delete_sel(text);
+ txt_make_dirty(text);
+ return;
}
else if (text->curc==0) { /* Appending two lines */
- if (text->curl->prev) {
- text->curl= text->curl->prev;
- text->curc= text->curl->len;
-
- txt_combine_lines(text, text->curl, text->curl->next);
- txt_pop_sel(text);
- }
- }
- else { /* Just backspacing a char */
- int i= text->curc-1;
+ if (!text->curl->prev) return;
- c= text->curl->line[i];
- while(i< text->curl->len) {
- text->curl->line[i]= text->curl->line[i+1];
- i++;
- }
- text->curl->len--;
- text->curc--;
+ text->curl= text->curl->prev;
+ text->curc= text->curl->len;
- txt_pop_sel(text);
+ txt_combine_lines(text, text->curl, text->curl->next);
+ txt_pop_sel(text);
+ }
+ else { /* Just backspacing a char */
+ int i= text->curc-1;
+
+ TextMarker *mrk= txt_find_marker_region(text, text->curl, i, text->curl->len, 0, 0);
+ if (mrk) {
+ int lineno= mrk->lineno;
+ if (mrk->start==i+1) {
+ if ((mrk->flags & TMARK_TEMP) && !(mrk->flags & TMARK_EDITALL)) {
+ txt_clear_markers(text, mrk->group, TMARK_TEMP);
+ } else {
+ BLI_freelinkN(&text->markers, mrk);
+ }
+ return;
+ }
+ do {
+ if (mrk->start>i) mrk->start--;
+ mrk->end--;
+ mrk= mrk->next;
+ } while (mrk && mrk->lineno==lineno);
+ }
+
+ c= text->curl->line[i];
+ while(i< text->curl->len) {
+ text->curl->line[i]= text->curl->line[i+1];
+ i++;
+ }
+ text->curl->len--;
+ text->curc--;
+
+ txt_pop_sel(text);
}
txt_make_dirty(text);
@@ -2101,10 +2341,17 @@ void txt_backspace_char (Text *text)
if(!undoing) txt_undo_add_charop(text, UNDO_BS, c);
}
+void txt_backspace_word (Text *text)
+{
+ txt_jump_left(text, 1);
+ txt_delete_sel(text);
+}
+
int txt_add_char (Text *text, char add)
{
- int len;
- char *tmp, *format;
+ int len, lineno;
+ char *tmp;
+ TextMarker *mrk;
if (!text) return 0;
if (!text->curl) return 0;
@@ -2116,8 +2363,17 @@ int txt_add_char (Text *text, char add)
txt_delete_sel(text);
+ mrk= txt_find_marker_region(text, text->curl, text->curc-1, text->curl->len, 0, 0);
+ if (mrk) {
+ lineno= mrk->lineno;
+ do {
+ if (mrk->start>text->curc) mrk->start++;
+ mrk->end++;
+ mrk= mrk->next;
+ } while (mrk && mrk->lineno==lineno);
+ }
+
tmp= MEM_mallocN(text->curl->len+2, "textline_string");
- format= MEM_mallocN(text->curl->len+4, "Syntax_format");
if(text->curc) memcpy(tmp, text->curl->line, text->curc);
tmp[text->curc]= add;
@@ -2125,7 +2381,7 @@ int txt_add_char (Text *text, char add)
len= text->curl->len - text->curc;
if(len>0) memcpy(tmp+text->curc+1, text->curl->line+text->curc, len);
tmp[text->curl->len+1]=0;
- make_new_line(text->curl, tmp, format);
+ make_new_line(text->curl, tmp);
text->curc++;
@@ -2138,10 +2394,42 @@ int txt_add_char (Text *text, char add)
return 1;
}
+int txt_replace_char (Text *text, char add)
+{
+ char del;
+
+ if (!text) return 0;
+ if (!text->curl) return 0;
+
+ /* If text is selected or we're at the end of the line just use txt_add_char */
+ if (text->curc==text->curl->len || txt_has_sel(text) || add=='\n') {
+ TextMarker *mrk;
+ int i= txt_add_char(text, add);
+ mrk= txt_find_marker(text, text->curl, text->curc, 0, 0);
+ if (mrk && mrk->end==text->curc) mrk->end--;
+ return i;
+ }
+
+ del= text->curl->line[text->curc];
+ text->curl->line[text->curc]= (unsigned char) add;
+ text->curc++;
+ txt_pop_sel(text);
+
+ txt_make_dirty(text);
+ txt_clean_text(text);
+
+ /* Should probably create a new op for this */
+ if(!undoing) {
+ txt_undo_add_charop(text, UNDO_DEL, del);
+ txt_undo_add_charop(text, UNDO_INSERT, add);
+ }
+ return 1;
+}
+
void indent(Text *text)
{
int len, num;
- char *tmp, *format;
+ char *tmp;
char add = '\t';
if (!text) return;
@@ -2152,7 +2440,6 @@ void indent(Text *text)
while (TRUE)
{
tmp= MEM_mallocN(text->curl->len+2, "textline_string");
- format= MEM_mallocN(text->curl->len+3, "Syntax_format");
text->curc = 0;
if(text->curc) memcpy(tmp, text->curl->line, text->curc);
@@ -2162,7 +2449,7 @@ void indent(Text *text)
if(len>0) memcpy(tmp+text->curc+1, text->curl->line+text->curc, len);
tmp[text->curl->len+1]=0;
- make_new_line(text->curl, tmp, format);
+ make_new_line(text->curl, tmp);
text->curc++;
@@ -2243,7 +2530,7 @@ void unindent(Text *text)
void comment(Text *text)
{
int len, num;
- char *tmp, *format;
+ char *tmp;
char add = '#';
if (!text) return;
@@ -2254,7 +2541,6 @@ void comment(Text *text)
while (TRUE)
{
tmp= MEM_mallocN(text->curl->len+2, "textline_string");
- format = MEM_mallocN(text->curl->len+3, "Syntax_format");
text->curc = 0;
if(text->curc) memcpy(tmp, text->curl->line, text->curc);
@@ -2264,7 +2550,7 @@ void comment(Text *text)
if(len>0) memcpy(tmp+text->curc+1, text->curl->line+text->curc, len);
tmp[text->curl->len+1]=0;
- make_new_line(text->curl, tmp, format);
+ make_new_line(text->curl, tmp);
text->curc++;
@@ -2348,7 +2634,7 @@ int setcurr_tab (Text *text)
int test = 0;
char *word = ":";
char *comm = "#";
- char back_words[3][7] = {"return", "break", "pass"};
+ char back_words[4][7] = {"return", "break", "pass", "yield"};
if (!text) return 0;
if (!text->curl) return 0;
@@ -2365,16 +2651,25 @@ int setcurr_tab (Text *text)
if(strstr(text->curl->line, word))
{
//if we find a : then add a tab but not if it is in a comment
- if(strcspn(text->curl->line, word) < strcspn(text->curl->line, comm))
+ int a, indent = 0;
+ for(a=0; text->curl->line[a] != '\0'; a++)
{
+ if (text->curl->line[a]=='#') {
+ break;
+ } else if (text->curl->line[a]==':') {
+ indent = 1;
+ } else if (text->curl->line[a]==']') {
+ indent = 0;
+ }
+ }
+ if (indent) {
i++;
-
}
}
- while(test < 3)
+ for(test=0; test < 4; test++)
{
- //if there are these 3 key words then remove a tab because we are done with the block
+ //if there are these 4 key words then remove a tab because we are done with the block
if(strstr(text->curl->line, back_words[test]) && i > 0)
{
if(strcspn(text->curl->line, back_words[test]) < strcspn(text->curl->line, comm))
@@ -2382,8 +2677,145 @@ int setcurr_tab (Text *text)
i--;
}
}
- test++;
}
return i;
}
+/*********************************/
+/* Text marker utility functions */
+/*********************************/
+
+/* Creates and adds a marker to the list maintaining sorted order */
+void txt_add_marker(Text *text, TextLine *line, int start, int end, char color[4], int group, int flags) {
+ TextMarker *tmp, *marker;
+
+ marker= MEM_mallocN(sizeof(TextMarker), "text_marker");
+
+ marker->lineno= txt_get_span(text->lines.first, line);
+ marker->start= MIN2(start, end);
+ marker->end= MAX2(start, end);
+ marker->group= group;
+ marker->flags= flags;
+
+ marker->color[0]= color[0];
+ marker->color[1]= color[1];
+ marker->color[2]= color[2];
+ marker->color[3]= color[3];
+
+ for (tmp=text->markers.last; tmp; tmp=tmp->prev)
+ if (tmp->lineno < marker->lineno || (tmp->lineno==marker->lineno && tmp->start < marker->start))
+ break;
+
+ if (tmp) BLI_insertlinkafter(&text->markers, tmp, marker);
+ else BLI_addhead(&text->markers, marker);
+}
+
+/* Returns the first matching marker on the specified line between two points.
+ If the group or flags fields are non-zero the returned flag must be in the
+ specified group and have at least the specified flags set. */
+TextMarker *txt_find_marker_region(Text *text, TextLine *line, int start, int end, int group, int flags) {
+ TextMarker *marker, *next;
+ int lineno= txt_get_span(text->lines.first, line);
+
+ for (marker=text->markers.first; marker; marker=next) {
+ next= marker->next;
+
+ if (group && marker->group != group) continue;
+ else if ((marker->flags & flags) != flags) continue;
+ else if (marker->lineno < lineno) continue;
+ else if (marker->lineno > lineno) break;
+
+ if ((marker->start==marker->end && start<=marker->start && marker->start<=end) ||
+ (marker->start<end && marker->end>start))
+ return marker;
+ }
+ return NULL;
+}
+
+/* Clears all markers on the specified line between two points. If the group or
+ flags fields are non-zero the returned flag must be in the specified group
+ and have at least the specified flags set. */
+short txt_clear_marker_region(Text *text, TextLine *line, int start, int end, int group, int flags) {
+ TextMarker *marker, *next;
+ int lineno= txt_get_span(text->lines.first, line);
+ short cleared= 0;
+
+ for (marker=text->markers.first; marker; marker=next) {
+ next= marker->next;
+
+ if (group && marker->group != group) continue;
+ else if ((marker->flags & flags) != flags) continue;
+ else if (marker->lineno < lineno) continue;
+ else if (marker->lineno > lineno) break;
+
+ if ((marker->start==marker->end && start<=marker->start && marker->start<=end) ||
+ (marker->start<end && marker->end>start)) {
+ BLI_freelinkN(&text->markers, marker);
+ cleared= 1;
+ }
+ }
+ return cleared;
+}
+
+/* Clears all markers in the specified group (if given) with at least the
+ specified flags set. Useful for clearing temporary markers (group=0,
+ flags=TMARK_TEMP) */
+short txt_clear_markers(Text *text, int group, int flags) {
+ TextMarker *marker, *next;
+ short cleared= 0;
+
+ for (marker=text->markers.first; marker; marker=next) {
+ next= marker->next;
+
+ if ((!group || marker->group==group) &&
+ (marker->flags & flags) == flags) {
+ BLI_freelinkN(&text->markers, marker);
+ cleared= 1;
+ }
+ }
+ return cleared;
+}
+
+/* Finds the marker at the specified line and cursor position with at least the
+ specified flags set in the given group (if non-zero). */
+TextMarker *txt_find_marker(Text *text, TextLine *line, int curs, int group, int flags) {
+ TextMarker *marker;
+ int lineno= txt_get_span(text->lines.first, line);
+
+ for (marker=text->markers.first; marker; marker=marker->next) {
+ if (group && marker->group != group) continue;
+ else if ((marker->flags & flags) != flags) continue;
+ else if (marker->lineno < lineno) continue;
+ else if (marker->lineno > lineno) break;
+
+ if (marker->start <= curs && curs <= marker->end)
+ return marker;
+ }
+ return NULL;
+}
+
+/* Finds the previous marker in the same group. If no other is found, the same
+ marker will be returned */
+TextMarker *txt_prev_marker(Text *text, TextMarker *marker) {
+ TextMarker *tmp= marker;
+ while (tmp) {
+ if (tmp->prev) tmp= tmp->prev;
+ else tmp= text->markers.last;
+ if (tmp->group == marker->group)
+ return tmp;
+ }
+ return NULL; /* Only if marker==NULL */
+}
+
+/* Finds the next marker in the same group. If no other is found, the same
+ marker will be returned */
+TextMarker *txt_next_marker(Text *text, TextMarker *marker) {
+ TextMarker *tmp= marker;
+ while (tmp) {
+ if (tmp->next) tmp= tmp->next;
+ else tmp= text->markers.first;
+ if (tmp->group == marker->group)
+ return tmp;
+ }
+ return NULL; /* Only if marker==NULL */
+}
diff --git a/source/blender/blenkernel/intern/texture.c b/source/blender/blenkernel/intern/texture.c
index 859cf663e6d..372c51b0da5 100644
--- a/source/blender/blenkernel/intern/texture.c
+++ b/source/blender/blenkernel/intern/texture.c
@@ -52,6 +52,9 @@
#include "DNA_image_types.h"
#include "DNA_world_types.h"
#include "DNA_brush_types.h"
+#include "DNA_node_types.h"
+#include "DNA_color_types.h"
+#include "DNA_scene_types.h"
#include "IMB_imbuf_types.h"
#include "IMB_imbuf.h"
@@ -71,6 +74,7 @@
#include "BKE_icons.h"
#include "BKE_ipo.h"
#include "BKE_brush.h"
+#include "BKE_node.h"
/* ------------------------------------------------------------------------- */
@@ -103,6 +107,7 @@ void open_plugin_tex(PluginTex *pit)
pit->result= 0;
pit->cfra= 0;
pit->version= 0;
+ pit->instance_init= 0;
/* clear the error list */
PIL_dynlib_get_error_as_string(NULL);
@@ -122,7 +127,7 @@ void open_plugin_tex(PluginTex *pit)
if (version != 0) {
pit->version= version();
- if (pit->version>=2 && pit->version<=5) {
+ if( pit->version >= 2 && pit->version <=6) {
int (*info_func)(PluginInfo *);
PluginInfo *info= (PluginInfo*) MEM_mallocN(sizeof(PluginInfo), "plugin_info");
@@ -342,6 +347,15 @@ int do_colorband(ColorBand *coba, float in, float out[4])
else
fac= 0.0f;
+ if (coba->ipotype==4) {
+ /* constant */
+ out[0]= cbd2->r;
+ out[1]= cbd2->g;
+ out[2]= cbd2->b;
+ out[3]= cbd2->a;
+ return 1;
+ }
+
if(coba->ipotype>=2) {
/* ipo from right to left: 3 2 1 0 */
@@ -385,6 +399,17 @@ int do_colorband(ColorBand *coba, float in, float out[4])
return 1; /* OK */
}
+void colorband_table_RGBA(ColorBand *coba, float **array, int *size)
+{
+ int a;
+
+ *size = CM_TABLE+1;
+ *array = MEM_callocN(sizeof(float)*(*size)*4, "ColorBand");
+
+ for(a=0; a<*size; a++)
+ do_colorband(coba, (float)a/(float)CM_TABLE, &(*array)[a*4]);
+}
+
/* ******************* TEX ************************ */
void free_texture(Tex *tex)
@@ -540,6 +565,8 @@ Tex *copy_texture(Tex *tex)
if(texn->type==TEX_IMAGE) id_us_plus((ID *)texn->ima);
else texn->ima= 0;
+ id_us_plus((ID *)texn->ipo);
+
if(texn->plugin) {
texn->plugin= MEM_dupallocN(texn->plugin);
open_plugin_tex(texn->plugin);
@@ -724,9 +751,10 @@ Tex *give_current_texture(Object *ob, int act)
Lamp *la = 0;
MTex *mtex = 0;
Tex *tex = 0;
+ bNode *node;
if(ob==0) return 0;
- if(ob->totcol==0) return 0;
+ if(ob->totcol==0 && !(ob->type==OB_LAMP)) return 0;
if(ob->type==OB_LAMP) {
la=(Lamp *)ob->data;
@@ -734,7 +762,6 @@ Tex *give_current_texture(Object *ob, int act)
mtex= la->mtex[(int)(la->texact)];
if(mtex) tex= mtex->tex;
}
- else tex= 0;
} else {
if(act>ob->totcol) act= ob->totcol;
else if(act==0) act= 1;
@@ -747,18 +774,42 @@ Tex *give_current_texture(Object *ob, int act)
if(matarar && *matarar) ma= (*matarar)[act-1];
else ma= 0;
-
+ }
+
+ if(ma && ma->use_nodes && ma->nodetree) {
+ node= nodeGetActiveID(ma->nodetree, ID_TE);
+
+ if(node) {
+ tex= (Tex *)node->id;
+ ma= NULL;
+ }
+ else {
+ node= nodeGetActiveID(ma->nodetree, ID_MA);
+ if(node)
+ ma= (Material*)node->id;
+ }
}
if(ma) {
mtex= ma->mtex[(int)(ma->texact)];
if(mtex) tex= mtex->tex;
}
- else tex= 0;
}
return tex;
}
+Tex *give_current_world_texture(void)
+{
+ MTex *mtex = 0;
+ Tex *tex = 0;
+
+ if(!(G.scene->world)) return 0;
+
+ mtex= G.scene->world->mtex[(int)(G.scene->world->texact)];
+ if(mtex) tex= mtex->tex;
+
+ return tex;
+}
/* ------------------------------------------------------------------------- */
@@ -816,3 +867,19 @@ void BKE_free_envmap(EnvMap *env)
}
/* ------------------------------------------------------------------------- */
+int BKE_texture_dependsOnTime(const struct Tex *texture)
+{
+ if(texture->plugin) {
+ // assume all plugins depend on time
+ return 1;
+ } else if( texture->ima &&
+ ELEM(texture->ima->source, IMA_SRC_SEQUENCE, IMA_SRC_MOVIE)) {
+ return 1;
+ } else if(texture->ipo) {
+ // assume any ipo means the texture is animated
+ return 1;
+ }
+ return 0;
+}
+
+/* ------------------------------------------------------------------------- */
diff --git a/source/blender/blenkernel/intern/world.c b/source/blender/blenkernel/intern/world.c
index 44c35252359..bef372e39f1 100644
--- a/source/blender/blenkernel/intern/world.c
+++ b/source/blender/blenkernel/intern/world.c
@@ -53,7 +53,9 @@
#include "BKE_main.h"
#include "BKE_icons.h"
+#ifndef DISABLE_PYTHON
#include "BPY_extern.h"
+#endif
#ifdef HAVE_CONFIG_H
#include <config.h>
@@ -63,9 +65,10 @@ void free_world(World *wrld)
{
MTex *mtex;
int a;
-
+
+#ifndef DISABLE_PYTHON
BPY_free_scriptlink(&wrld->scriptlink);
-
+#endif
for(a=0; a<MAX_MTEX; a++) {
mtex= wrld->mtex[a];
if(mtex && mtex->tex) mtex->tex->id.us--;
@@ -94,12 +97,12 @@ World *add_world(char *name)
wrld->exp= 0.0f;
wrld->exposure=wrld->range= 1.0f;
- wrld->aodist= 5.0;
+ wrld->aodist= 5.0f;
wrld->aosamp= 5;
- wrld->aoenergy= 1.0;
- wrld->aobias= 0.05;
+ wrld->aoenergy= 1.0f;
+ wrld->aobias= 0.05f;
wrld->ao_samp_method = WO_AOSAMP_HAMMERSLEY;
-
+ wrld->ao_approx_error= 0.25f;
wrld->physicsEngine= WOPHY_BULLET;//WOPHY_SUMO; Bullet by default
wrld->preview = NULL;
@@ -123,9 +126,9 @@ World *copy_world(World *wrld)
}
if (wrld->preview) wrldn->preview = BKE_previewimg_copy(wrld->preview);
-
+#ifndef DISABLE_PYTHON
BPY_copy_scriptlink(&wrld->scriptlink);
-
+#endif
id_us_plus((ID *)wrldn->ipo);
return wrldn;
diff --git a/source/blender/blenkernel/intern/writeavi.c b/source/blender/blenkernel/intern/writeavi.c
index b70bdc2c07e..e63588e6d7f 100644
--- a/source/blender/blenkernel/intern/writeavi.c
+++ b/source/blender/blenkernel/intern/writeavi.c
@@ -116,7 +116,7 @@ void makeavistring (RenderData *rd, char *string)
if (string==0) return;
strcpy(string, rd->pic);
- BLI_convertstringcode(string, G.sce, rd->cfra);
+ BLI_convertstringcode(string, G.sce);
BLI_make_existing_file(string);
diff --git a/source/blender/blenkernel/intern/writeffmpeg.c b/source/blender/blenkernel/intern/writeffmpeg.c
index e5d8d560a1b..7008f254871 100644
--- a/source/blender/blenkernel/intern/writeffmpeg.c
+++ b/source/blender/blenkernel/intern/writeffmpeg.c
@@ -33,6 +33,7 @@
#include <ffmpeg/avcodec.h>
#include <ffmpeg/rational.h>
#include <ffmpeg/swscale.h>
+#include <ffmpeg/opt.h>
#if LIBAVFORMAT_VERSION_INT < (49 << 16)
#define FFMPEG_OLD_FRAME_RATE 1
@@ -41,6 +42,12 @@
#define FFMPEG_CODEC_TIME_BASE 1
#endif
+#if LIBAVFORMAT_VERSION_INT >= (52 << 16)
+#define OUTFILE_PB (outfile->pb)
+#else
+#define OUTFILE_PB (&outfile->pb)
+#endif
+
#if defined(WIN32) && (!(defined snprintf))
#define snprintf _snprintf
#endif
@@ -51,6 +58,7 @@
#include "BLI_blenlib.h"
#include "BKE_global.h"
+#include "BKE_idprop.h"
#include "IMB_imbuf_types.h"
#include "IMB_imbuf.h"
@@ -210,6 +218,18 @@ static const char** get_file_extensions(int format)
static const char * rv[] = { ".avi", NULL };
return rv;
}
+ case FFMPEG_FLV: {
+ static const char * rv[] = { ".flv", NULL };
+ return rv;
+ }
+ case FFMPEG_MKV: {
+ static const char * rv[] = { ".mkv", NULL };
+ return rv;
+ }
+ case FFMPEG_OGG: {
+ static const char * rv[] = { ".ogg", ".ogv", NULL };
+ return rv;
+ }
default:
return NULL;
}
@@ -231,14 +251,18 @@ static void write_video_frame(AVFrame* frame)
AVPacket packet;
av_init_packet(&packet);
+ if (c->coded_frame->pts != AV_NOPTS_VALUE) {
#ifdef FFMPEG_CODEC_TIME_BASE
- packet.pts = av_rescale_q(c->coded_frame->pts,
- c->time_base,
- video_stream->time_base);
+ packet.pts = av_rescale_q(c->coded_frame->pts,
+ c->time_base,
+ video_stream->time_base);
#else
- packet.pts = c->coded_frame->pts;
+ packet.pts = c->coded_frame->pts;
#endif
- fprintf(stderr, "Video Frame PTS: %lld\n", packet.pts);
+ fprintf(stderr, "Video Frame PTS: %lld\n", packet.pts);
+ } else {
+ fprintf(stderr, "Video Frame PTS: not set\n");
+ }
if (c->coded_frame->key_frame)
packet.flags |= PKT_FLAG_KEY;
packet.stream_index = video_stream->index;
@@ -323,6 +347,75 @@ static AVFrame* generate_video_frame(uint8_t* pixels)
return current_frame;
}
+static void set_ffmpeg_property_option(AVCodecContext* c, IDProperty * prop)
+{
+ char name[128];
+ char * param;
+ const AVOption * rv = NULL;
+
+ fprintf(stderr, "FFMPEG expert option: %s: ", prop->name);
+
+ strncpy(name, prop->name, 128);
+
+ param = strchr(name, ':');
+
+ if (param) {
+ *param++ = 0;
+ }
+
+ switch(prop->type) {
+ case IDP_STRING:
+ fprintf(stderr, "%s.\n", IDP_String(prop));
+ rv = av_set_string(c, prop->name, IDP_String(prop));
+ break;
+ case IDP_FLOAT:
+ fprintf(stderr, "%g.\n", IDP_Float(prop));
+ rv = av_set_double(c, prop->name, IDP_Float(prop));
+ break;
+ case IDP_INT:
+ fprintf(stderr, "%d.\n", IDP_Int(prop));
+
+ if (param) {
+ if (IDP_Int(prop)) {
+ rv = av_set_string(c, name, param);
+ } else {
+ return;
+ }
+ } else {
+ rv = av_set_int(c, prop->name, IDP_Int(prop));
+ }
+ break;
+ }
+
+ if (!rv) {
+ fprintf(stderr, "ffmpeg-option not supported: %s! Skipping.\n",
+ prop->name);
+ }
+}
+
+static void set_ffmpeg_properties(AVCodecContext* c, const char * prop_name)
+{
+ IDProperty * prop;
+ void * iter;
+ IDProperty * curr;
+
+ if (!G.scene->r.ffcodecdata.properties) {
+ return;
+ }
+
+ prop = IDP_GetPropertyFromGroup(
+ G.scene->r.ffcodecdata.properties, (char*) prop_name);
+ if (!prop) {
+ return;
+ }
+
+ iter = IDP_GetGroupIterator(prop);
+
+ while ((curr = IDP_GroupIterNext(iter)) != NULL) {
+ set_ffmpeg_property_option(c, curr);
+ }
+}
+
/* prepare a video stream for the output file */
static AVStream* alloc_video_stream(int codec_id, AVFormatContext* of,
@@ -409,13 +502,18 @@ static AVStream* alloc_video_stream(int codec_id, AVFormatContext* of,
}
/* Determine whether we are encoding interlaced material or not */
- if (G.scene->r.mode & (1 << 6)) {
+ if (G.scene->r.mode & R_FIELDS) {
fprintf(stderr, "Encoding interlaced video\n");
c->flags |= CODEC_FLAG_INTERLACED_DCT;
c->flags |= CODEC_FLAG_INTERLACED_ME;
- }
- c->sample_aspect_ratio.num = G.scene->r.xasp;
- c->sample_aspect_ratio.den = G.scene->r.yasp;
+ }
+
+ /* xasp & yasp got float lately... */
+
+ c->sample_aspect_ratio = av_d2q(
+ ((double) G.scene->r.xasp / (double) G.scene->r.yasp), 255);
+
+ set_ffmpeg_properties(c, "video");
if (avcodec_open(c, codec) < 0) {
//
@@ -461,6 +559,9 @@ static AVStream* alloc_audio_stream(int codec_id, AVFormatContext* of)
//XXX error("Couldn't find a valid audio codec");
return NULL;
}
+
+ set_ffmpeg_properties(c, "audio");
+
if (avcodec_open(c, codec) < 0) {
//XXX error("Couldn't initialize audio codec");
return NULL;
@@ -573,6 +674,8 @@ void start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty)
switch(ffmpeg_type) {
case FFMPEG_AVI:
case FFMPEG_MOV:
+ case FFMPEG_OGG:
+ case FFMPEG_MKV:
fmt->video_codec = ffmpeg_codec;
break;
case FFMPEG_DV:
@@ -590,6 +693,9 @@ void start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty)
case FFMPEG_XVID:
fmt->video_codec = CODEC_ID_XVID;
break;
+ case FFMPEG_FLV:
+ fmt->video_codec = CODEC_ID_FLV1;
+ break;
case FFMPEG_MPEG4:
default:
fmt->video_codec = CODEC_ID_MPEG4;
@@ -615,6 +721,9 @@ void start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty)
return;
}
}
+
+ fmt->audio_codec = ffmpeg_audio_codec;
+
if (ffmpeg_type == FFMPEG_DV) {
fmt->audio_codec = CODEC_ID_PCM_S16LE;
if (ffmpeg_multiplex_audio
@@ -684,7 +793,8 @@ void makeffmpegstring(char* string) {
if (!string || !exts) return;
strcpy(string, G.scene->r.pic);
- BLI_convertstringcode(string, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(string, G.sce);
+ BLI_convertstringframe(string, G.scene->r.cfra);
BLI_make_existing_file(string);
@@ -756,7 +866,7 @@ void append_ffmpeg(int frame, int *pixels, int rectx, int recty)
write_video_frame(generate_video_frame((unsigned char*) pixels));
if (ffmpeg_autosplit) {
- if (url_ftell(&outfile->pb) > FFMPEG_AUTOSPLIT_SIZE) {
+ if (url_ftell(OUTFILE_PB) > FFMPEG_AUTOSPLIT_SIZE) {
end_ffmpeg();
ffmpeg_autosplit_count++;
start_ffmpeg_impl(ffmpeg_renderdata,
@@ -772,7 +882,7 @@ void end_ffmpeg(void)
fprintf(stderr, "Closing ffmpeg...\n");
- if (audio_stream) {
+ if (audio_stream && video_stream) {
write_audio_frames();
}
@@ -803,7 +913,7 @@ void end_ffmpeg(void)
}
if (outfile && outfile->oformat) {
if (!(outfile->oformat->flags & AVFMT_NOFILE)) {
- url_fclose(&outfile->pb);
+ url_fclose(OUTFILE_PB);
}
}
if (outfile) {
diff --git a/source/blender/blenkernel/intern/writeframeserver.c b/source/blender/blenkernel/intern/writeframeserver.c
index c48bea70dc9..64bf5f85d23 100644
--- a/source/blender/blenkernel/intern/writeframeserver.c
+++ b/source/blender/blenkernel/intern/writeframeserver.c
@@ -249,7 +249,7 @@ static int handle_request(char * req)
return -1;
}
-int frameserver_loop()
+int frameserver_loop(void)
{
fd_set readfds;
struct timeval tv;
diff --git a/source/blender/blenlib/BLI_arithb.h b/source/blender/blenlib/BLI_arithb.h
index 6697a7b2ba5..186681fad7d 100644
--- a/source/blender/blenlib/BLI_arithb.h
+++ b/source/blender/blenlib/BLI_arithb.h
@@ -50,10 +50,14 @@ extern "C" {
#ifndef M_SQRT1_2
#define M_SQRT1_2 0.70710678118654752440
#endif
+#ifndef M_1_PI
+#define M_1_PI 0.318309886183790671538
+#endif
#ifdef WIN32
#ifndef FREE_WINDOWS
#define isnan(n) _isnan(n)
+ #define finite _finite
#endif
#endif
@@ -87,6 +91,7 @@ float saasin(float fac);
float sasqrt(float fac);
int FloatCompare(float *v1, float *v2, float limit);
+int FloatCompare4(float *v1, float *v2, float limit);
float FloatLerpf(float target, float origin, float fac);
float CalcNormFloat(float *v1, float *v2, float *v3, float *n);
@@ -95,7 +100,7 @@ float CalcNormFloat4(float *v1, float *v2, float *v3, float *v4, float *n);
void CalcNormLong(int *v1, int *v2, int *v3, float *n);
/* CalcNormShort: is ook uitprodukt - (translates as 'is also out/cross product') */
void CalcNormShort(short *v1, short *v2, short *v3, float *n);
-
+float power_of_2(float val);
/**
* @section Euler conversion routines
@@ -160,6 +165,7 @@ void Mat3Inv(float m1[][3], float m2[][3]);
void Mat3CpyMat4(float m1[][3],float m2[][4]);
void Mat4CpyMat3(float m1[][4], float m2[][3]);
+void Mat3BlendMat3(float out[][3], float dst[][3], float src[][3], float srcweight);
void Mat4BlendMat4(float out[][4], float dst[][4], float src[][4], float srcweight);
float Det2x2(float a,float b,float c, float d);
@@ -239,6 +245,7 @@ void VecMulf(float *v1, float f);
int VecLenCompare(float *v1, float *v2, float limit);
int VecCompare(float *v1, float *v2, float limit);
int VecEqual(float *v1, float *v2);
+int VecIsNull(float *v);
void printvecf(char *str,float v[3]);
void printvec4f(char *str, float v[4]);
@@ -256,15 +263,23 @@ void Vec2Mulf(float *v1, float f);
void Vec2Addf(float *v, float *v1, float *v2);
void Vec2Subf(float *v, float *v1, float *v2);
void Vec2Copyf(float *v1, float *v2);
+void Vec2Lerpf(float *target, float *a, float *b, float t);
-float *vectoquat(float *vec, short axis, short upflag);
+void AxisAngleToQuat(float *q, float *axis, float angle);
+void RotationBetweenVectorsToQuat(float *q, float v1[3], float v2[3]);
+void vectoquat(float *vec, short axis, short upflag, float *q);
float VecAngle2(float *v1, float *v2);
float VecAngle3(float *v1, float *v2, float *v3);
float NormalizedVecAngle2(float *v1, float *v2);
+float VecAngle3_2D(float *v1, float *v2, float *v3);
+float NormalizedVecAngle2_2D(float *v1, float *v2);
+
void euler_rot(float *beul, float ang, char axis);
+void NormalShortToFloat(float *out, short *in);
+void NormalFloatToShort(short *out, float *in);
float DistVL2Dfl(float *v1, float *v2, float *v3);
float PdistVL2Dfl(float *v1, float *v2, float *v3);
@@ -309,6 +324,10 @@ void i_window(
float mat[][4]
);
+#define BLI_CS_SMPTE 0
+#define BLI_CS_REC709 1
+#define BLI_CS_CIE 2
+
void hsv_to_rgb(float h, float s, float v, float *r, float *g, float *b);
void hex_to_rgb(char *hexcol, float *r, float *g, float *b);
void rgb_to_yuv(float r, float g, float b, float *ly, float *lu, float *lv);
@@ -316,6 +335,9 @@ void yuv_to_rgb(float y, float u, float v, float *lr, float *lg, float *lb);
void ycc_to_rgb(float y, float cb, float cr, float *lr, float *lg, float *lb);
void rgb_to_ycc(float r, float g, float b, float *ly, float *lcb, float *lcr);
void rgb_to_hsv(float r, float g, float b, float *lh, float *ls, float *lv);
+void xyz_to_rgb(float x, float y, float z, float *r, float *g, float *b, int colorspace);
+int constrain_rgb(float *r, float *g, float *b);
+void gamma_correct_rgb(float *r, float *g, float *b);
unsigned int hsv_to_cpack(float h, float s, float v);
unsigned int rgb_to_cpack(float r, float g, float b);
void cpack_to_rgb(unsigned int col, float *r, float *g, float *b);
@@ -367,7 +389,9 @@ void LocQuatSizeToMat4(float mat[][4], float loc[3], float quat[4], float size[3
void tubemap(float x, float y, float z, float *u, float *v);
void spheremap(float x, float y, float z, float *u, float *v);
+int LineIntersectLine(float v1[3], float v2[3], float v3[3], float v4[3], float i1[3], float i2[3]);
int LineIntersectsTriangle(float p1[3], float p2[3], float v0[3], float v1[3], float v2[3], float *lambda, float *uv);
+int RayIntersectsTriangle(float p1[3], float d[3], float v0[3], float v1[3], float v2[3], float *lambda, float *uv);
int SweepingSphereIntersectsTriangleUV(float p1[3], float p2[3], float radius, float v0[3], float v1[3], float v2[3], float *lambda, float *ipoint);
int AxialLineIntersectsTriangle(int axis, float co1[3], float co2[3], float v0[3], float v1[3], float v2[3], float *lambda);
int AabbIntersectAabb(float min1[3], float max1[3], float min2[3], float max2[3]);
@@ -395,6 +419,16 @@ void DQuatNormalize(DualQuat *dq, float totweight);
void DQuatMulVecfl(DualQuat *dq, float *co, float mat[][3]);
void DQuatCpyDQuat(DualQuat *dq1, DualQuat *dq2);
+/* Tangent stuff */
+typedef struct VertexTangent {
+ float tang[3], uv[2];
+ struct VertexTangent *next;
+} VertexTangent;
+
+void sum_or_add_vertex_tangent(void *arena, VertexTangent **vtang, float *tang, float *uv);
+float *find_vertex_tangent(VertexTangent *vtang, float *uv);
+void tangent_from_uv(float *uv1, float *uv2, float *uv3, float *co1, float *co2, float *co3, float *n, float *tang);
+
#ifdef __cplusplus
}
#endif
diff --git a/source/blender/blenlib/BLI_blenlib.h b/source/blender/blenlib/BLI_blenlib.h
index efeab705913..f65aaa72a75 100644
--- a/source/blender/blenlib/BLI_blenlib.h
+++ b/source/blender/blenlib/BLI_blenlib.h
@@ -67,14 +67,14 @@
#include "DNA_listBase.h"
#include <stdlib.h>
-
extern ListBase fillfacebase;
extern ListBase fillvertbase;
/**
* @attention Defined in scanfill.c
*/
extern ListBase filledgebase;
-extern int totblock;
+
+extern char btempdir[]; /* creator.c temp dir used instead of U.tempdir, set with BLI_where_is_temp( btempdir, 1 ); */
struct chardesc;
struct direntry;
@@ -94,7 +94,8 @@ char *BLI_gethome(void);
void BLI_make_file_string(const char *relabase, char *string, const char *dir, const char *file);
void BLI_make_exist(char *dir);
void BLI_make_existing_file(char *name);
-void BLI_split_dirfile(const char *string, char *dir, char *file);
+void BLI_split_dirfile(char *string, char *dir, char *file);
+void BLI_split_dirfile_basic(const char *string, char *dir, char *file);
void BLI_join_dirfile(char *string, const char *dir, const char *file);
int BLI_testextensie(const char *str, const char *ext);
void addlisttolist(ListBase *list1, ListBase *list2);
@@ -104,6 +105,7 @@ int BLI_findindex(struct ListBase *listbase, void *vlink);
void BLI_freelistN(struct ListBase *listbase);
void BLI_addtail(struct ListBase *listbase, void *vlink);
void BLI_remlink(struct ListBase *listbase, void *vlink);
+void BLI_uniquename(struct ListBase *list, void *vlink, char defname[], short name_offs, short len);
void BLI_newname(char * name, int add);
int BLI_stringdec(char *string, char *kop, char *start, unsigned short *numlen);
void BLI_stringenc(char *string, char *kop, char *start, unsigned short numlen, int pic);
@@ -135,7 +137,11 @@ void BLI_dlist_reinit(struct DynamicList *dlist);
* converts it to a regular full path.
* Also removes garbage from directory paths, like /../ or double slashes etc
*/
-void BLI_cleanup_dir(const char *relabase, char *dir);
+void BLI_cleanup_file(const char *relabase, char *dir);
+void BLI_cleanup_dir(const char *relabase, char *dir); /* same as above but adds a trailing slash */
+
+/* go back one directory */
+int BLI_parent_dir(char *path);
/**
* Blender's path code replacement function.
@@ -149,7 +155,9 @@ void BLI_cleanup_dir(const char *relabase, char *dir);
* @a framenum The framenumber to replace the frame code with.
* @retval Returns true if the path was relative (started with "//").
*/
-int BLI_convertstringcode(char *path, const char *basepath, int framenum);
+int BLI_convertstringcode(char *path, const char *basepath);
+int BLI_convertstringframe(char *path, int frame);
+int BLI_convertstringcwd(char *path);
void BLI_makestringcode(const char *relfile, char *file);
@@ -222,7 +230,7 @@ int BLI_strcaseeq(char *a, char *b);
/* in util.c */
#ifdef WITH_ICONV
-void BLI_string_to_utf8(char *original, char *utf_8, char *code);
+void BLI_string_to_utf8(char *original, char *utf_8, const char *code);
#endif
/**
@@ -253,7 +261,19 @@ void BLI_free_file_lines(struct LinkNode *lines);
* @param fullname The full path and full name of the executable
* @param name The name of the executable (usually argv[0]) to be checked
*/
-void BLI_where_am_i(char *fullname, char *name);
+void BLI_where_am_i(char *fullname, const char *name);
+
+char *get_install_dir(void);
+ /**
+ * Gets the temp directory when blender first runs.
+ * If the default path is not found, use try $TEMP
+ *
+ * Also make sure the temp dir has a trailing slash
+ *
+ * @param fullname The full path to the temp directory
+ */
+void BLI_where_is_temp(char *fullname, int usertemp);
+
/**
* determines the full path to the application bundle on OS X
@@ -270,6 +290,7 @@ int BLI_getInstallationDir(char *str);
/* BLI_storage.h */
int BLI_filesize(int file);
+int BLI_filepathsize(const char *path);
double BLI_diskfree(char *dir);
char *BLI_getwdN(char *dir);
void BLI_hide_dot_files(int set);
@@ -283,7 +304,6 @@ int BLI_exist(char *name);
/* BLI_fileops.h */
void BLI_recurdir_fileops(char *dirname);
int BLI_link(char *file, char *to);
-int BLI_backup(char *file, char *from, char *to);
int BLI_is_writable(char *filename);
/**
@@ -295,8 +315,10 @@ int BLI_rename(char *from, char *to);
int BLI_gzip(char *from, char *to);
int BLI_delete(char *file, int dir, int recursive);
int BLI_move(char *file, char *to);
-int BLI_touch(char *file);
-char *BLI_last_slash(char *string);
+int BLI_touch(const char *file);
+char *BLI_last_slash(const char *string);
+void BLI_add_slash(char *string);
+void BLI_del_slash(char *string);
/* BLI_rct.c */
/**
@@ -397,7 +419,7 @@ void *BLI_pointer_from_int(int val);
* @param member The name of a member field of @a strct
* @retval The offset in bytes of @a member within @a strct
*/
-#define BLI_STRUCT_OFFSET(strct, member) ((int) &((strct*) 0)->member)
+#define BLI_STRUCT_OFFSET(strct, member) ((int)(intptr_t) &((strct*) 0)->member)
#ifdef __cplusplus
}
diff --git a/source/blender/blenlib/BLI_bpath.h b/source/blender/blenlib/BLI_bpath.h
index 9426064f59f..874c8c7828c 100644
--- a/source/blender/blenlib/BLI_bpath.h
+++ b/source/blender/blenlib/BLI_bpath.h
@@ -29,6 +29,13 @@
/* Based on ghash, difference is ghash is not a fixed size,
* so for BPath we dont need to malloc */
+struct BPathIteratorSeqData {
+ int totseq;
+ int seq;
+ struct Sequence **seqar; /* Sequence */
+ struct Scene *scene; /* Current scene */
+};
+
struct BPathIterator {
char* path;
char* lib;
@@ -36,21 +43,30 @@ struct BPathIterator {
void* data;
int len;
int type;
+
+ void (*setpath_callback)(struct BPathIterator *, char *);
+ void (*getpath_callback)(struct BPathIterator *, char *);
+
+ /* only for seq data */
+ struct BPathIteratorSeqData seqdata;
};
-void BLI_bpathIterator_init (struct BPathIterator *bpi);
-char* BLI_bpathIterator_getPath (struct BPathIterator *bpi);
-char* BLI_bpathIterator_getLib (struct BPathIterator *bpi);
-char* BLI_bpathIterator_getName (struct BPathIterator *bpi);
-int BLI_bpathIterator_getType (struct BPathIterator *bpi);
-int BLI_bpathIterator_getPathMaxLen(struct BPathIterator *bpi);
-void BLI_bpathIterator_step (struct BPathIterator *bpi);
-int BLI_bpathIterator_isDone (struct BPathIterator *bpi);
-void BLI_bpathIterator_copyPathExpanded( struct BPathIterator *bpi, char *path_expanded);
+void BLI_bpathIterator_init (struct BPathIterator *bpi);
+void BLI_bpathIterator_free (struct BPathIterator *bpi);
+char* BLI_bpathIterator_getLib (struct BPathIterator *bpi);
+char* BLI_bpathIterator_getName (struct BPathIterator *bpi);
+int BLI_bpathIterator_getType (struct BPathIterator *bpi);
+int BLI_bpathIterator_getPathMaxLen (struct BPathIterator *bpi);
+void BLI_bpathIterator_step (struct BPathIterator *bpi);
+int BLI_bpathIterator_isDone (struct BPathIterator *bpi);
+void BLI_bpathIterator_getPath (struct BPathIterator *bpi, char *path);
+void BLI_bpathIterator_getPathExpanded (struct BPathIterator *bpi, char *path_expanded);
+void BLI_bpathIterator_setPath (struct BPathIterator *bpi, char *path);
/* high level funcs */
/* creates a text file with missing files if there are any */
-struct Text * checkMissingFiles(void);
-void makeFilesRelative(int *tot, int *changed, int *failed, int *linked);
+void checkMissingFiles(char *txtname );
+void makeFilesRelative(char *txtname, int *tot, int *changed, int *failed, int *linked);
+void makeFilesAbsolute(char *txtname, int *tot, int *changed, int *failed, int *linked);
void findMissingFiles(char *str);
diff --git a/source/blender/blenlib/BLI_edgehash.h b/source/blender/blenlib/BLI_edgehash.h
index f3aa69d77ff..abbd17c3635 100644
--- a/source/blender/blenlib/BLI_edgehash.h
+++ b/source/blender/blenlib/BLI_edgehash.h
@@ -86,6 +86,9 @@ void BLI_edgehashIterator_getKey (EdgeHashIterator *ehi, int *v0_r, int *v1
/* Retrieve the value from an iterator. */
void* BLI_edgehashIterator_getValue (EdgeHashIterator *ehi);
+ /* Set the value for an iterator. */
+void BLI_edgehashIterator_setValue (EdgeHashIterator *ehi, void *val);
+
/* Steps the iterator to the next index. */
void BLI_edgehashIterator_step (EdgeHashIterator *ehi);
diff --git a/source/blender/blenlib/BLI_editVert.h b/source/blender/blenlib/BLI_editVert.h
index ae7697c7c7e..447f6a2a485 100644
--- a/source/blender/blenlib/BLI_editVert.h
+++ b/source/blender/blenlib/BLI_editVert.h
@@ -38,6 +38,8 @@
#include "DNA_customdata_types.h"
#include "DNA_mesh_types.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
struct DerivedMesh;
struct RetopoPaintData;
@@ -53,7 +55,7 @@ typedef struct EditVert
struct EditEdge *e;
struct EditFace *f;
void *p;
- long l;
+ intptr_t l;
float fp;
} tmp;
float no[3]; /*vertex normal */
@@ -64,6 +66,7 @@ typedef struct EditVert
h for hidden. if (!eve->h) {...
f1 and f2 can be used for temp data, clear them first*/
unsigned char f, h, f1, f2;
+ float bweight;
short fast; /* only 0 or 1, for editmesh_fastmalloc, do not store temp data here! */
int hash;
int keyindex; /* original index #, for restoring key information */
@@ -94,12 +97,13 @@ typedef struct EditEdge
struct EditEdge *e;
struct EditFace *f;
void *p;
- long l;
+ intptr_t l;
float fp;
} tmp;
short f1, f2; /* short, f1 is (ab)used in subdiv */
unsigned char f, h, dir, seam, sharp;
float crease;
+ float bweight;
short fast; /* only 0 or 1, for editmesh_fastmalloc */
short fgoni; /* index for fgon, for search */
HashEdge hash;
@@ -120,7 +124,7 @@ typedef struct EditFace
struct EditEdge *e;
struct EditFace *f;
void *p;
- long l;
+ intptr_t l;
float fp;
} tmp;
float n[3], cent[3];
diff --git a/source/blender/blenlib/BLI_ghash.h b/source/blender/blenlib/BLI_ghash.h
index aec77f5f385..c77e82f0a2b 100644
--- a/source/blender/blenlib/BLI_ghash.h
+++ b/source/blender/blenlib/BLI_ghash.h
@@ -34,7 +34,12 @@
struct GHash;
typedef struct GHash GHash;
-typedef struct GHashIterator GHashIterator;
+
+typedef struct GHashIterator {
+ GHash *gh;
+ int curBucket;
+ struct Entry *curEntry;
+} GHashIterator;
typedef unsigned int (*GHashHashFP) (void *key);
typedef int (*GHashCmpFP) (void *a, void *b);
@@ -63,6 +68,15 @@ int BLI_ghash_size (GHash *gh);
*/
GHashIterator* BLI_ghashIterator_new (GHash *gh);
/**
+ * Init an already allocated GHashIterator. The hash table must not
+ * be mutated while the iterator is in use, and the iterator will
+ * step exactly BLI_ghash_size(gh) times before becoming done.
+ *
+ * @param ghi The GHashIterator to initialize.
+ * @param gh The GHash to iterate over.
+ */
+void BLI_ghashIterator_init(GHashIterator *ghi, GHash *gh);
+ /**
* Free a GHashIterator.
*
* @param ghi The iterator to free.
diff --git a/source/blender/blenlib/BLI_graph.h b/source/blender/blenlib/BLI_graph.h
new file mode 100644
index 00000000000..160c2e04cf5
--- /dev/null
+++ b/source/blender/blenlib/BLI_graph.h
@@ -0,0 +1,125 @@
+#ifndef BLI_GRAPH_H_
+#define BLI_GRAPH_H_
+
+#include "DNA_listBase.h"
+
+struct BGraph;
+struct BNode;
+struct BArc;
+
+struct RadialArc;
+
+typedef void (*FreeArc)(struct BArc*);
+typedef void (*FreeNode)(struct BNode*);
+typedef void (*RadialSymmetry)(struct BNode* root_node, struct RadialArc* ring, int total);
+typedef void (*AxialSymmetry)(struct BNode* root_node, struct BNode* node1, struct BNode* node2, struct BArc* arc1, struct BArc* arc2);
+
+/* IF YOU MODIFY THOSE TYPES, YOU NEED TO UPDATE ALL THOSE THAT "INHERIT" FROM THEM
+ *
+ * RigGraph, ReebGraph
+ *
+ * */
+
+typedef struct BGraph {
+ ListBase arcs;
+ ListBase nodes;
+
+ float length;
+
+ /* function pointer to deal with custom fonctionnality */
+ FreeArc free_arc;
+ FreeNode free_node;
+ RadialSymmetry radial_symmetry;
+ AxialSymmetry axial_symmetry;
+} BGraph;
+
+typedef struct BNode {
+ void *next, *prev;
+ float p[3];
+ int flag;
+
+ int degree;
+ struct BArc **arcs;
+
+ int subgraph_index;
+
+ int symmetry_level;
+ int symmetry_flag;
+ float symmetry_axis[3];
+} BNode;
+
+typedef struct BArc {
+ void *next, *prev;
+ struct BNode *head, *tail;
+ int flag;
+
+ float length;
+
+ int symmetry_level;
+ int symmetry_group;
+ int symmetry_flag;
+} BArc;
+
+/* Helper structure for radial symmetry */
+typedef struct RadialArc
+{
+ struct BArc *arc;
+ float n[3]; /* normalized vector joining the nodes of the arc */
+} RadialArc;
+
+BNode *BLI_otherNode(BArc *arc, BNode *node);
+
+void BLI_freeNode(BGraph *graph, BNode *node);
+void BLI_removeNode(BGraph *graph, BNode *node);
+
+void BLI_removeArc(BGraph *graph, BArc *arc);
+
+void BLI_flagNodes(BGraph *graph, int flag);
+void BLI_flagArcs(BGraph *graph, int flag);
+
+int BLI_hasAdjacencyList(BGraph *rg);
+void BLI_buildAdjacencyList(BGraph *rg);
+void BLI_rebuildAdjacencyList(BGraph* rg);
+void BLI_rebuildAdjacencyListForNode(BGraph* rg, BNode *node);
+void BLI_freeAdjacencyList(BGraph *rg);
+
+int BLI_FlagSubgraphs(BGraph *graph);
+void BLI_ReflagSubgraph(BGraph *graph, int old_subgraph, int new_subgraph);
+
+#define SHAPE_RADIX 10 /* each shape level is encoded this base */
+
+int BLI_subtreeShape(BGraph *graph, BNode *node, BArc *rootArc, int include_root);
+float BLI_subtreeLength(BNode *node);
+void BLI_calcGraphLength(BGraph *graph);
+
+void BLI_replaceNode(BGraph *graph, BNode *node_src, BNode *node_replaced);
+void BLI_replaceNodeInArc(BGraph *graph, BArc *arc, BNode *node_src, BNode *node_replaced);
+void BLI_removeDoubleNodes(BGraph *graph, float limit);
+BNode * BLI_FindNodeByPosition(BGraph *graph, float *p, float limit);
+
+BArc * BLI_findConnectedArc(BGraph *graph, BArc *arc, BNode *v);
+
+int BLI_isGraphCyclic(BGraph *graph);
+
+/*------------ Symmetry handling ------------*/
+void BLI_markdownSymmetry(BGraph *graph, BNode *root_node, float limit);
+
+void BLI_mirrorAlongAxis(float v[3], float center[3], float axis[3]);
+
+/* BNode symmetry flags */
+#define SYM_TOPOLOGICAL 1
+#define SYM_PHYSICAL 2
+
+/* the following two are exclusive */
+#define SYM_AXIAL 4
+#define SYM_RADIAL 8
+
+/* BArc symmetry flags
+ *
+ * axial symetry sides */
+#define SYM_SIDE_POSITIVE 1
+#define SYM_SIDE_NEGATIVE 2
+/* Anything higher is the order in radial symmetry */
+#define SYM_SIDE_RADIAL 3
+
+#endif /*BLI_GRAPH_H_*/
diff --git a/source/blender/blenlib/BLI_kdopbvh.h b/source/blender/blenlib/BLI_kdopbvh.h
new file mode 100644
index 00000000000..e3591a84e98
--- /dev/null
+++ b/source/blender/blenlib/BLI_kdopbvh.h
@@ -0,0 +1,97 @@
+/**
+ *
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2006 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Daniel Genrich, Andre Pinto
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+
+#ifndef BLI_KDOPBVH_H
+#define BLI_KDOPBVH_H
+
+#include <float.h>
+
+struct BVHTree;
+typedef struct BVHTree BVHTree;
+
+typedef struct BVHTreeOverlap {
+ int indexA;
+ int indexB;
+} BVHTreeOverlap;
+
+typedef struct BVHTreeNearest
+{
+ int index; /* the index of the nearest found (untouched if none is found within a dist radius from the given coordinates) */
+ float co[3]; /* nearest coordinates (untouched it none is found within a dist radius from the given coordinates) */
+ float no[3]; /* normal at nearest coordinates (untouched it none is found within a dist radius from the given coordinates) */
+ float dist; /* squared distance to search arround */
+} BVHTreeNearest;
+
+typedef struct BVHTreeRay
+{
+ float origin[3]; /* ray origin */
+ float direction[3]; /* ray direction */
+ float radius; /* radius around ray */
+} BVHTreeRay;
+
+typedef struct BVHTreeRayHit
+{
+ int index; /* index of the tree node (untouched if no hit is found) */
+ float co[3]; /* coordinates of the hit point */
+ float no[3]; /* normal on hit point */
+ float dist; /* distance to the hit point */
+} BVHTreeRayHit;
+
+/* callback must update nearest in case it finds a nearest result */
+typedef void (*BVHTree_NearestPointCallback) (void *userdata, int index, const float *co, BVHTreeNearest *nearest);
+
+/* callback must update hit in case it finds a nearest successful hit */
+typedef void (*BVHTree_RayCastCallback) (void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit);
+
+
+BVHTree *BLI_bvhtree_new(int maxsize, float epsilon, char tree_type, char axis);
+void BLI_bvhtree_free(BVHTree *tree);
+
+/* construct: first insert points, then call balance */
+int BLI_bvhtree_insert(BVHTree *tree, int index, float *co, int numpoints);
+void BLI_bvhtree_balance(BVHTree *tree);
+
+/* update: first update points/nodes, then call update_tree to refit the bounding volumes */
+int BLI_bvhtree_update_node(BVHTree *tree, int index, float *co, float *co_moving, int numpoints);
+void BLI_bvhtree_update_tree(BVHTree *tree);
+
+/* collision/overlap: check two trees if they overlap, alloc's *overlap with length of the int return value */
+BVHTreeOverlap *BLI_bvhtree_overlap(BVHTree *tree1, BVHTree *tree2, int *result);
+
+float BLI_bvhtree_getepsilon(BVHTree *tree);
+
+/* find nearest node to the given coordinates (if nearest is given it will only search nodes where square distance is smaller than nearest->dist) */
+int BLI_bvhtree_find_nearest(BVHTree *tree, const float *co, BVHTreeNearest *nearest, BVHTree_NearestPointCallback callback, void *userdata);
+
+int BLI_bvhtree_ray_cast(BVHTree *tree, const float *co, const float *dir, float radius, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata);
+
+#endif // BLI_KDOPBVH_H
+
diff --git a/source/blender/blenlib/BLI_mempool.h b/source/blender/blenlib/BLI_mempool.h
new file mode 100644
index 00000000000..8b31459dd38
--- /dev/null
+++ b/source/blender/blenlib/BLI_mempool.h
@@ -0,0 +1,44 @@
+/**
+ * Simple fast memory allocator
+ *
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2008 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Geoffrey Bantle.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef BLI_MEMPOOL_H
+#define BLI_MEMPOOL_H
+
+struct BLI_mempool;
+typedef struct BLI_mempool BLI_mempool;
+
+BLI_mempool *BLI_mempool_create(int esize, int tote, int pchunk);
+void *BLI_mempool_alloc(BLI_mempool *pool);
+void *BLI_mempool_calloc(BLI_mempool *pool);
+void BLI_mempool_free(BLI_mempool *pool, void *addr);
+void BLI_mempool_destroy(BLI_mempool *pool);
+
+
+#endif
diff --git a/source/blender/blenlib/BLI_rand.h b/source/blender/blenlib/BLI_rand.h
index 0e534783c17..266aa347aff 100644
--- a/source/blender/blenlib/BLI_rand.h
+++ b/source/blender/blenlib/BLI_rand.h
@@ -44,6 +44,7 @@ struct RNG* rng_new (unsigned int seed);
void rng_free (struct RNG* rng);
void rng_seed (struct RNG* rng, unsigned int seed);
+void rng_srandom(struct RNG *rng, unsigned int seed);
int rng_getInt (struct RNG* rng);
double rng_getDouble (struct RNG* rng);
float rng_getFloat (struct RNG* rng);
diff --git a/source/blender/blenlib/BLI_threads.h b/source/blender/blenlib/BLI_threads.h
index 60ecce3f9d8..5a7e84c42fb 100644
--- a/source/blender/blenlib/BLI_threads.h
+++ b/source/blender/blenlib/BLI_threads.h
@@ -39,16 +39,41 @@
#define BLENDER_MAX_THREADS 8
struct ListBase;
-
void BLI_init_threads (struct ListBase *threadbase, void *(*do_thread)(void *), int tot);
int BLI_available_threads(struct ListBase *threadbase);
int BLI_available_thread_index(struct ListBase *threadbase);
void BLI_insert_thread (struct ListBase *threadbase, void *callerdata);
void BLI_remove_thread (struct ListBase *threadbase, void *callerdata);
+void BLI_remove_thread_index(struct ListBase *threadbase, int index);
+void BLI_remove_threads(struct ListBase *threadbase);
void BLI_end_threads (struct ListBase *threadbase);
void BLI_lock_thread (int type);
void BLI_unlock_thread (int type);
+int BLI_system_thread_count( void ); /* gets the number of threads the system can make use of */
+
+/* ThreadedWorker is a simple tool for dispatching work to a limited number of threads in a transparent
+ * fashion from the caller's perspective
+ * */
+
+struct ThreadedWorker;
+
+/* Create a new worker supporting tot parallel threads.
+ * When new work in inserted and all threads are busy, sleep(sleep_time) before checking again
+ */
+struct ThreadedWorker *BLI_create_worker(void *(*do_thread)(void *), int tot, int sleep_time);
+
+/* join all working threads */
+void BLI_end_worker(struct ThreadedWorker *worker);
+
+/* also ends all working threads */
+void BLI_destroy_worker(struct ThreadedWorker *worker);
+
+/* Spawns a new work thread if possible, sleeps until one is available otherwise
+ * NOTE: inserting work is NOT thread safe, so make sure it is only done from one thread */
+void BLI_insert_work(struct ThreadedWorker *worker, void *param);
+
+
#endif
diff --git a/source/blender/blenlib/BLI_winstuff.h b/source/blender/blenlib/BLI_winstuff.h
index 54d70626dd5..3bb63506c95 100644
--- a/source/blender/blenlib/BLI_winstuff.h
+++ b/source/blender/blenlib/BLI_winstuff.h
@@ -61,6 +61,10 @@
// These definitions are also in arithb for simplicity
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
@@ -73,6 +77,9 @@
#ifndef M_SQRT1_2
#define M_SQRT1_2 0.70710678118654752440
#endif
+#ifndef M_1_PI
+#define M_1_PI 0.318309886183790671538
+#endif
#define MAXPATHLEN MAX_PATH
@@ -110,7 +117,12 @@ void RegisterBlendExtension(char * str);
DIR *opendir (const char *path);
struct dirent *readdir(DIR *dp);
int closedir (DIR *dp);
-void get_default_root(char* root);
+void get_default_root(char *root);
+int check_file_chars(char *filename);
+
+#ifdef __cplusplus
+}
+#endif
#endif /* __WINSTUFF_H__ */
diff --git a/source/blender/blenlib/CMakeLists.txt b/source/blender/blenlib/CMakeLists.txt
index d5e34d7d4de..4eb01a50f39 100644
--- a/source/blender/blenlib/CMakeLists.txt
+++ b/source/blender/blenlib/CMakeLists.txt
@@ -33,6 +33,13 @@ SET(INC
${ZLIB_INC}
)
+IF(CMAKE_SYSTEM_NAME MATCHES "Linux")
+SET(INC
+ ${INC}
+ ${BINRELOC_INC}
+)
+ENDIF(CMAKE_SYSTEM_NAME MATCHES "Linux")
+
IF(WITH_VERSE)
ADD_DEFINITIONS(-DWITH_VERSE)
SET(INC ${INC} ${VERSE_INC})
diff --git a/source/blender/blenlib/SConscript b/source/blender/blenlib/SConscript
index 9d81ac05472..01a9a1eab0e 100644
--- a/source/blender/blenlib/SConscript
+++ b/source/blender/blenlib/SConscript
@@ -7,20 +7,23 @@ cflags=''
incs = '. ../makesdna ../blenkernel #/intern/guardedalloc ../editors/include'
incs += ' ' + env['BF_FREETYPE_INC']
incs += ' ' + env['BF_ZLIB_INC']
-incs += ' ' + env['BF_SDL_INC']
defs = ''
-if env['WITH_BF_INTERNATIONAL'] == 1:
- defs = 'WITH_FREETYPE2'
+if env['WITH_BF_SDL']:
+ incs += ' ' + env['BF_SDL_INC']
+
+if env['WITH_BF_INTERNATIONAL']:
+ defs = 'WITH_FREETYPE2'
if env['WITH_BF_VERSE']:
defs += ' WITH_VERSE'
incs += ' ' + env['BF_VERSE_INCLUDE']
if env['OURPLATFORM'] == 'linux2':
- cflags='-pthread'
+ cflags='-pthread'
+ incs += ' ../../../extern/binreloc/include'
if env['OURPLATFORM'] in ('win32-vc', 'win32-mingw'):
- incs += ' ' + env['BF_PTHREADS_INC']
+ incs += ' ' + env['BF_PTHREADS_INC']
-env.BlenderLib ( 'bf_blenlib', sources, Split(incs), Split(defs), libtype=['core','player'], priority = [100,195], compileflags =cflags )
+env.BlenderLib ( 'bf_blenlib', sources, Split(incs), Split(defs), libtype=['core', 'intern', 'player'], priority = [85,150,195], compileflags =cflags )
diff --git a/source/blender/blenlib/intern/BLI_ghash.c b/source/blender/blenlib/intern/BLI_ghash.c
index 227cb8f5e9a..1967b8a88e2 100644
--- a/source/blender/blenlib/intern/BLI_ghash.c
+++ b/source/blender/blenlib/intern/BLI_ghash.c
@@ -34,6 +34,8 @@
#include "MEM_guardedalloc.h"
#include "BLI_ghash.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
@@ -198,12 +200,6 @@ void BLI_ghash_free(GHash *gh, GHashKeyFreeFP keyfreefp, GHashValFreeFP valfreef
/***/
-struct GHashIterator {
- GHash *gh;
- int curBucket;
- Entry *curEntry;
-};
-
GHashIterator *BLI_ghashIterator_new(GHash *gh) {
GHashIterator *ghi= malloc(sizeof(*ghi));
ghi->gh= gh;
@@ -217,6 +213,17 @@ GHashIterator *BLI_ghashIterator_new(GHash *gh) {
}
return ghi;
}
+void BLI_ghashIterator_init(GHashIterator *ghi, GHash *gh) {
+ ghi->gh= gh;
+ ghi->curEntry= NULL;
+ ghi->curBucket= -1;
+ while (!ghi->curEntry) {
+ ghi->curBucket++;
+ if (ghi->curBucket==ghi->gh->nbuckets)
+ break;
+ ghi->curEntry= ghi->gh->buckets[ghi->curBucket];
+ }
+}
void BLI_ghashIterator_free(GHashIterator *ghi) {
free(ghi);
}
@@ -256,11 +263,7 @@ int BLI_ghashutil_ptrcmp(void *a, void *b) {
}
unsigned int BLI_ghashutil_inthash(void *ptr) {
-#if defined(_WIN64)
- unsigned __int64 key = (unsigned __int64)ptr;
-#else
- unsigned long key = (unsigned long)ptr;
-#endif
+ uintptr_t key = (uintptr_t)ptr;
key += ~(key << 16);
key ^= (key >> 5);
diff --git a/source/blender/blenlib/intern/BLI_kdopbvh.c b/source/blender/blenlib/intern/BLI_kdopbvh.c
new file mode 100644
index 00000000000..30472beb3e6
--- /dev/null
+++ b/source/blender/blenlib/intern/BLI_kdopbvh.c
@@ -0,0 +1,1526 @@
+/**
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2006 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Daniel Genrich, Andre Pinto
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "math.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "BKE_utildefines.h"
+
+#include "BLI_kdopbvh.h"
+#include "BLI_arithb.h"
+
+#ifdef _OPENMP
+#include <omp.h>
+#endif
+
+
+
+#define MAX_TREETYPE 32
+#define DEFAULT_FIND_NEAREST_HEAP_SIZE 1024
+
+typedef struct BVHNode
+{
+ struct BVHNode **children;
+ struct BVHNode *parent; // some user defined traversed need that
+ float *bv; // Bounding volume of all nodes, max 13 axis
+ int index; // face, edge, vertex index
+ char totnode; // how many nodes are used, used for speedup
+ char main_axis; // Axis used to split this node
+} BVHNode;
+
+struct BVHTree
+{
+ BVHNode **nodes;
+ BVHNode *nodearray; /* pre-alloc branch nodes */
+ BVHNode **nodechild; // pre-alloc childs for nodes
+ float *nodebv; // pre-alloc bounding-volumes for nodes
+ float epsilon; /* epslion is used for inflation of the k-dop */
+ int totleaf; // leafs
+ int totbranch;
+ char tree_type; // type of tree (4 => quadtree)
+ char axis; // kdop type (6 => OBB, 7 => AABB, ...)
+ char start_axis, stop_axis; // KDOP_AXES array indices according to axis
+};
+
+typedef struct BVHOverlapData
+{
+ BVHTree *tree1, *tree2;
+ BVHTreeOverlap *overlap;
+ int i, max_overlap; /* i is number of overlaps */
+ int start_axis, stop_axis;
+} BVHOverlapData;
+
+typedef struct BVHNearestData
+{
+ BVHTree *tree;
+ const float *co;
+ BVHTree_NearestPointCallback callback;
+ void *userdata;
+ float proj[13]; //coordinates projection over axis
+ BVHTreeNearest nearest;
+
+} BVHNearestData;
+
+typedef struct BVHRayCastData
+{
+ BVHTree *tree;
+
+ BVHTree_RayCastCallback callback;
+ void *userdata;
+
+
+ BVHTreeRay ray;
+ float ray_dot_axis[13];
+
+ BVHTreeRayHit hit;
+} BVHRayCastData;
+////////////////////////////////////////m
+
+
+////////////////////////////////////////////////////////////////////////
+// Bounding Volume Hierarchy Definition
+//
+// Notes: From OBB until 26-DOP --> all bounding volumes possible, just choose type below
+// Notes: You have to choose the type at compile time ITM
+// Notes: You can choose the tree type --> binary, quad, octree, choose below
+////////////////////////////////////////////////////////////////////////
+
+static float KDOP_AXES[13][3] =
+{ {1.0, 0, 0}, {0, 1.0, 0}, {0, 0, 1.0}, {1.0, 1.0, 1.0}, {1.0, -1.0, 1.0}, {1.0, 1.0, -1.0},
+{1.0, -1.0, -1.0}, {1.0, 1.0, 0}, {1.0, 0, 1.0}, {0, 1.0, 1.0}, {1.0, -1.0, 0}, {1.0, 0, -1.0},
+{0, 1.0, -1.0}
+};
+
+/*
+ * Generic push and pop heap
+ */
+#define PUSH_HEAP_BODY(HEAP_TYPE,PRIORITY,heap,heap_size) \
+{ \
+ HEAP_TYPE element = heap[heap_size-1]; \
+ int child = heap_size-1; \
+ while(child != 0) \
+ { \
+ int parent = (child-1) / 2; \
+ if(PRIORITY(element, heap[parent])) \
+ { \
+ heap[child] = heap[parent]; \
+ child = parent; \
+ } \
+ else break; \
+ } \
+ heap[child] = element; \
+}
+
+#define POP_HEAP_BODY(HEAP_TYPE, PRIORITY,heap,heap_size) \
+{ \
+ HEAP_TYPE element = heap[heap_size-1]; \
+ int parent = 0; \
+ while(parent < (heap_size-1)/2 ) \
+ { \
+ int child2 = (parent+1)*2; \
+ if(PRIORITY(heap[child2-1], heap[child2])) \
+ --child2; \
+ \
+ if(PRIORITY(element, heap[child2])) \
+ break; \
+ \
+ heap[parent] = heap[child2]; \
+ parent = child2; \
+ } \
+ heap[parent] = element; \
+}
+
+int ADJUST_MEMORY(void *local_memblock, void **memblock, int new_size, int *max_size, int size_per_item)
+{
+ int new_max_size = *max_size * 2;
+ void *new_memblock = NULL;
+
+ if(new_size <= *max_size)
+ return TRUE;
+
+ if(*memblock == local_memblock)
+ {
+ new_memblock = malloc( size_per_item * new_max_size );
+ memcpy( new_memblock, *memblock, size_per_item * *max_size );
+ }
+ else
+ new_memblock = realloc(*memblock, size_per_item * new_max_size );
+
+ if(new_memblock)
+ {
+ *memblock = new_memblock;
+ *max_size = new_max_size;
+ return TRUE;
+ }
+ else
+ return FALSE;
+}
+
+
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+// Introsort
+// with permission deriven from the following Java code:
+// http://ralphunden.net/content/tutorials/a-guide-to-introsort/
+// and he derived it from the SUN STL
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+static int size_threshold = 16;
+/*
+* Common methods for all algorithms
+*/
+static int floor_lg(int a)
+{
+ return (int)(floor(log(a)/log(2)));
+}
+
+/*
+* Insertion sort algorithm
+*/
+static void bvh_insertionsort(BVHNode **a, int lo, int hi, int axis)
+{
+ int i,j;
+ BVHNode *t;
+ for (i=lo; i < hi; i++)
+ {
+ j=i;
+ t = a[i];
+ while((j!=lo) && (t->bv[axis] < (a[j-1])->bv[axis]))
+ {
+ a[j] = a[j-1];
+ j--;
+ }
+ a[j] = t;
+ }
+}
+
+static int bvh_partition(BVHNode **a, int lo, int hi, BVHNode * x, int axis)
+{
+ int i=lo, j=hi;
+ while (1)
+ {
+ while ((a[i])->bv[axis] < x->bv[axis]) i++;
+ j--;
+ while (x->bv[axis] < (a[j])->bv[axis]) j--;
+ if(!(i < j))
+ return i;
+ SWAP( BVHNode* , a[i], a[j]);
+ i++;
+ }
+}
+
+/*
+* Heapsort algorithm
+*/
+static void bvh_downheap(BVHNode **a, int i, int n, int lo, int axis)
+{
+ BVHNode * d = a[lo+i-1];
+ int child;
+ while (i<=n/2)
+ {
+ child = 2*i;
+ if ((child < n) && ((a[lo+child-1])->bv[axis] < (a[lo+child])->bv[axis]))
+ {
+ child++;
+ }
+ if (!(d->bv[axis] < (a[lo+child-1])->bv[axis])) break;
+ a[lo+i-1] = a[lo+child-1];
+ i = child;
+ }
+ a[lo+i-1] = d;
+}
+
+static void bvh_heapsort(BVHNode **a, int lo, int hi, int axis)
+{
+ int n = hi-lo, i;
+ for (i=n/2; i>=1; i=i-1)
+ {
+ bvh_downheap(a, i,n,lo, axis);
+ }
+ for (i=n; i>1; i=i-1)
+ {
+ SWAP(BVHNode*, a[lo],a[lo+i-1]);
+ bvh_downheap(a, 1,i-1,lo, axis);
+ }
+}
+
+static BVHNode *bvh_medianof3(BVHNode **a, int lo, int mid, int hi, int axis) // returns Sortable
+{
+ if ((a[mid])->bv[axis] < (a[lo])->bv[axis])
+ {
+ if ((a[hi])->bv[axis] < (a[mid])->bv[axis])
+ return a[mid];
+ else
+ {
+ if ((a[hi])->bv[axis] < (a[lo])->bv[axis])
+ return a[hi];
+ else
+ return a[lo];
+ }
+ }
+ else
+ {
+ if ((a[hi])->bv[axis] < (a[mid])->bv[axis])
+ {
+ if ((a[hi])->bv[axis] < (a[lo])->bv[axis])
+ return a[lo];
+ else
+ return a[hi];
+ }
+ else
+ return a[mid];
+ }
+}
+/*
+* Quicksort algorithm modified for Introsort
+*/
+static void bvh_introsort_loop (BVHNode **a, int lo, int hi, int depth_limit, int axis)
+{
+ int p;
+
+ while (hi-lo > size_threshold)
+ {
+ if (depth_limit == 0)
+ {
+ bvh_heapsort(a, lo, hi, axis);
+ return;
+ }
+ depth_limit=depth_limit-1;
+ p=bvh_partition(a, lo, hi, bvh_medianof3(a, lo, lo+((hi-lo)/2)+1, hi-1, axis), axis);
+ bvh_introsort_loop(a, p, hi, depth_limit, axis);
+ hi=p;
+ }
+}
+
+static void sort(BVHNode **a0, int begin, int end, int axis)
+{
+ if (begin < end)
+ {
+ BVHNode **a=a0;
+ bvh_introsort_loop(a, begin, end, 2*floor_lg(end-begin), axis);
+ bvh_insertionsort(a, begin, end, axis);
+ }
+}
+void sort_along_axis(BVHTree *tree, int start, int end, int axis)
+{
+ sort(tree->nodes, start, end, axis);
+}
+
+//after a call to this function you can expect one of:
+// every node to left of a[n] are smaller or equal to it
+// every node to the right of a[n] are greater or equal to it
+int partition_nth_element(BVHNode **a, int _begin, int _end, int n, int axis){
+ int begin = _begin, end = _end, cut;
+ while(end-begin > 3)
+ {
+ cut = bvh_partition(a, begin, end, bvh_medianof3(a, begin, (begin+end)/2, end-1, axis), axis );
+ if(cut <= n)
+ begin = cut;
+ else
+ end = cut;
+ }
+ bvh_insertionsort(a, begin, end, axis);
+
+ return n;
+}
+
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+
+/*
+ * BVHTree bounding volumes functions
+ */
+static void create_kdop_hull(BVHTree *tree, BVHNode *node, float *co, int numpoints, int moving)
+{
+ float newminmax;
+ float *bv = node->bv;
+ int i, k;
+
+ // don't init boudings for the moving case
+ if(!moving)
+ {
+ for (i = tree->start_axis; i < tree->stop_axis; i++)
+ {
+ bv[2*i] = FLT_MAX;
+ bv[2*i + 1] = -FLT_MAX;
+ }
+ }
+
+ for(k = 0; k < numpoints; k++)
+ {
+ // for all Axes.
+ for (i = tree->start_axis; i < tree->stop_axis; i++)
+ {
+ newminmax = INPR(&co[k * 3], KDOP_AXES[i]);
+ if (newminmax < bv[2 * i])
+ bv[2 * i] = newminmax;
+ if (newminmax > bv[(2 * i) + 1])
+ bv[(2 * i) + 1] = newminmax;
+ }
+ }
+}
+
+// depends on the fact that the BVH's for each face is already build
+static void refit_kdop_hull(BVHTree *tree, BVHNode *node, int start, int end)
+{
+ float newmin,newmax;
+ int i, j;
+ float *bv = node->bv;
+
+
+ for (i = tree->start_axis; i < tree->stop_axis; i++)
+ {
+ bv[2*i] = FLT_MAX;
+ bv[2*i + 1] = -FLT_MAX;
+ }
+
+ for (j = start; j < end; j++)
+ {
+// for all Axes.
+ for (i = tree->start_axis; i < tree->stop_axis; i++)
+ {
+ newmin = tree->nodes[j]->bv[(2 * i)];
+ if ((newmin < bv[(2 * i)]))
+ bv[(2 * i)] = newmin;
+
+ newmax = tree->nodes[j]->bv[(2 * i) + 1];
+ if ((newmax > bv[(2 * i) + 1]))
+ bv[(2 * i) + 1] = newmax;
+ }
+ }
+
+}
+
+// only supports x,y,z axis in the moment
+// but we should use a plain and simple function here for speed sake
+static char get_largest_axis(float *bv)
+{
+ float middle_point[3];
+
+ middle_point[0] = (bv[1]) - (bv[0]); // x axis
+ middle_point[1] = (bv[3]) - (bv[2]); // y axis
+ middle_point[2] = (bv[5]) - (bv[4]); // z axis
+ if (middle_point[0] > middle_point[1])
+ {
+ if (middle_point[0] > middle_point[2])
+ return 1; // max x axis
+ else
+ return 5; // max z axis
+ }
+ else
+ {
+ if (middle_point[1] > middle_point[2])
+ return 3; // max y axis
+ else
+ return 5; // max z axis
+ }
+}
+
+// bottom-up update of bvh node BV
+// join the children on the parent BV
+static void node_join(BVHTree *tree, BVHNode *node)
+{
+ int i, j;
+
+ for (i = tree->start_axis; i < tree->stop_axis; i++)
+ {
+ node->bv[2*i] = FLT_MAX;
+ node->bv[2*i + 1] = -FLT_MAX;
+ }
+
+ for (i = 0; i < tree->tree_type; i++)
+ {
+ if (node->children[i])
+ {
+ for (j = tree->start_axis; j < tree->stop_axis; j++)
+ {
+ // update minimum
+ if (node->children[i]->bv[(2 * j)] < node->bv[(2 * j)])
+ node->bv[(2 * j)] = node->children[i]->bv[(2 * j)];
+
+ // update maximum
+ if (node->children[i]->bv[(2 * j) + 1] > node->bv[(2 * j) + 1])
+ node->bv[(2 * j) + 1] = node->children[i]->bv[(2 * j) + 1];
+ }
+ }
+ else
+ break;
+ }
+}
+
+/*
+ * Debug and information functions
+ */
+static void bvhtree_print_tree(BVHTree *tree, BVHNode *node, int depth)
+{
+ int i;
+ for(i=0; i<depth; i++) printf(" ");
+ printf(" - %d (%ld): ", node->index, node - tree->nodearray);
+ for(i=2*tree->start_axis; i<2*tree->stop_axis; i++)
+ printf("%.3f ", node->bv[i]);
+ printf("\n");
+
+ for(i=0; i<tree->tree_type; i++)
+ if(node->children[i])
+ bvhtree_print_tree(tree, node->children[i], depth+1);
+}
+
+static void bvhtree_info(BVHTree *tree)
+{
+ printf("BVHTree info\n");
+ printf("tree_type = %d, axis = %d, epsilon = %f\n", tree->tree_type, tree->axis, tree->epsilon);
+ printf("nodes = %d, branches = %d, leafs = %d\n", tree->totbranch + tree->totleaf, tree->totbranch, tree->totleaf);
+ printf("Memory per node = %ldbytes\n", sizeof(BVHNode) + sizeof(BVHNode*)*tree->tree_type + sizeof(float)*tree->axis);
+ printf("BV memory = %dbytes\n", MEM_allocN_len(tree->nodebv));
+
+ printf("Total memory = %ldbytes\n", sizeof(BVHTree)
+ + MEM_allocN_len(tree->nodes)
+ + MEM_allocN_len(tree->nodearray)
+ + MEM_allocN_len(tree->nodechild)
+ + MEM_allocN_len(tree->nodebv)
+ );
+
+// bvhtree_print_tree(tree, tree->nodes[tree->totleaf], 0);
+}
+
+#if 0
+
+
+static void verify_tree(BVHTree *tree)
+{
+ int i, j, check = 0;
+
+ // check the pointer list
+ for(i = 0; i < tree->totleaf; i++)
+ {
+ if(tree->nodes[i]->parent == NULL)
+ printf("Leaf has no parent: %d\n", i);
+ else
+ {
+ for(j = 0; j < tree->tree_type; j++)
+ {
+ if(tree->nodes[i]->parent->children[j] == tree->nodes[i])
+ check = 1;
+ }
+ if(!check)
+ {
+ printf("Parent child relationship doesn't match: %d\n", i);
+ }
+ check = 0;
+ }
+ }
+
+ // check the leaf list
+ for(i = 0; i < tree->totleaf; i++)
+ {
+ if(tree->nodearray[i].parent == NULL)
+ printf("Leaf has no parent: %d\n", i);
+ else
+ {
+ for(j = 0; j < tree->tree_type; j++)
+ {
+ if(tree->nodearray[i].parent->children[j] == &tree->nodearray[i])
+ check = 1;
+ }
+ if(!check)
+ {
+ printf("Parent child relationship doesn't match: %d\n", i);
+ }
+ check = 0;
+ }
+ }
+
+ printf("branches: %d, leafs: %d, total: %d\n", tree->totbranch, tree->totleaf, tree->totbranch + tree->totleaf);
+}
+#endif
+
+//Helper data and structures to build a min-leaf generalized implicit tree
+//This code can be easily reduced (basicly this is only method to calculate pow(k, n) in O(1).. and stuff like that)
+typedef struct BVHBuildHelper
+{
+ int tree_type; //
+ int totleafs; //
+
+ int leafs_per_child [32]; //Min number of leafs that are archievable from a node at depth N
+ int branches_on_level[32]; //Number of nodes at depth N (tree_type^N)
+
+ int remain_leafs; //Number of leafs that are placed on the level that is not 100% filled
+
+} BVHBuildHelper;
+
+static void build_implicit_tree_helper(BVHTree *tree, BVHBuildHelper *data)
+{
+ int depth = 0;
+ int remain;
+ int nnodes;
+
+ data->totleafs = tree->totleaf;
+ data->tree_type= tree->tree_type;
+
+ //Calculate the smallest tree_type^n such that tree_type^n >= num_leafs
+ for(
+ data->leafs_per_child[0] = 1;
+ data->leafs_per_child[0] < data->totleafs;
+ data->leafs_per_child[0] *= data->tree_type
+ );
+
+ data->branches_on_level[0] = 1;
+
+ //We could stop the loop first (but I am lazy to find out when)
+ for(depth = 1; depth < 32; depth++)
+ {
+ data->branches_on_level[depth] = data->branches_on_level[depth-1] * data->tree_type;
+ data->leafs_per_child [depth] = data->leafs_per_child [depth-1] / data->tree_type;
+ }
+
+ remain = data->totleafs - data->leafs_per_child[1];
+ nnodes = (remain + data->tree_type - 2) / (data->tree_type - 1);
+ data->remain_leafs = remain + nnodes;
+}
+
+// return the min index of all the leafs archivable with the given branch
+static int implicit_leafs_index(BVHBuildHelper *data, int depth, int child_index)
+{
+ int min_leaf_index = child_index * data->leafs_per_child[depth-1];
+ if(min_leaf_index <= data->remain_leafs)
+ return min_leaf_index;
+ else if(data->leafs_per_child[depth])
+ return data->totleafs - (data->branches_on_level[depth-1] - child_index) * data->leafs_per_child[depth];
+ else
+ return data->remain_leafs;
+}
+
+/**
+ * Generalized implicit tree build
+ *
+ * An implicit tree is a tree where its structure is implied, thus there is no need to store child pointers or indexs.
+ * Its possible to find the position of the child or the parent with simple maths (multiplication and adittion). This type
+ * of tree is for example used on heaps.. where node N has its childs at indexs N*2 and N*2+1.
+ *
+ * Altought in this case the tree type is general.. and not know until runtime.
+ * tree_type stands for the maximum number of childs that a tree node can have.
+ * All tree types >= 2 are supported.
+ *
+ * Advantages of the used trees include:
+ * - No need to store child/parent relations (they are implicit);
+ * - Any node child always has an index greater than the parent;
+ * - Brother nodes are sequencial in memory;
+ *
+ *
+ * Some math relations derived for general implicit trees:
+ *
+ * K = tree_type, ( 2 <= K )
+ * ROOT = 1
+ * N child of node A = A * K + (2 - K) + N, (0 <= N < K)
+ *
+ * Util methods:
+ * TODO...
+ * (looping elements, knowing if its a leaf or not.. etc...)
+ */
+
+// This functions returns the number of branches needed to have the requested number of leafs.
+static int implicit_needed_branches(int tree_type, int leafs)
+{
+ return MAX2(1, (leafs + tree_type - 3) / (tree_type-1) );
+}
+
+/*
+ * This function handles the problem of "sorting" the leafs (along the split_axis).
+ *
+ * It arranges the elements in the given partitions such that:
+ * - any element in partition N is less or equal to any element in partition N+1.
+ * - if all elements are diferent all partition will get the same subset of elements
+ * as if the array was sorted.
+ *
+ * partition P is described as the elements in the range ( nth[P] , nth[P+1] ]
+ *
+ * TODO: This can be optimized a bit by doing a specialized nth_element instead of K nth_elements
+ */
+static void split_leafs(BVHNode **leafs_array, int *nth, int partitions, int split_axis)
+{
+ int i;
+ for(i=0; i < partitions-1; i++)
+ {
+ if(nth[i] >= nth[partitions])
+ break;
+
+ partition_nth_element(leafs_array, nth[i], nth[partitions], nth[i+1], split_axis);
+ }
+}
+
+/*
+ * This functions builds an optimal implicit tree from the given leafs.
+ * Where optimal stands for:
+ * - The resulting tree will have the smallest number of branches;
+ * - At most only one branch will have NULL childs;
+ * - All leafs will be stored at level N or N+1.
+ *
+ * This function creates an implicit tree on branches_array, the leafs are given on the leafs_array.
+ *
+ * The tree is built per depth levels. First branchs at depth 1.. then branches at depth 2.. etc..
+ * The reason is that we can build level N+1 from level N witouth any data dependencies.. thus it allows
+ * to use multithread building.
+ *
+ * To archieve this is necessary to find how much leafs are accessible from a certain branch, BVHBuildHelper
+ * implicit_needed_branches and implicit_leafs_index are auxiliar functions to solve that "optimal-split".
+ */
+static void non_recursive_bvh_div_nodes(BVHTree *tree, BVHNode *branches_array, BVHNode **leafs_array, int num_leafs)
+{
+ int i;
+
+ const int tree_type = tree->tree_type;
+ const int tree_offset = 2 - tree->tree_type; //this value is 0 (on binary trees) and negative on the others
+ const int num_branches= implicit_needed_branches(tree_type, num_leafs);
+
+ BVHBuildHelper data;
+ int depth;
+
+ // set parent from root node to NULL
+ BVHNode *tmp = branches_array+0;
+ tmp->parent = NULL;
+
+ //Most of bvhtree code relies on 1-leaf trees having at least one branch
+ //We handle that special case here
+ if(num_leafs == 1)
+ {
+ BVHNode *root = branches_array+0;
+ refit_kdop_hull(tree, root, 0, num_leafs);
+ root->main_axis = get_largest_axis(root->bv) / 2;
+ root->totnode = 1;
+ root->children[0] = leafs_array[0];
+ root->children[0]->parent = root;
+ return;
+ }
+
+ branches_array--; //Implicit trees use 1-based indexs
+
+ build_implicit_tree_helper(tree, &data);
+
+ //Loop tree levels (log N) loops
+ for(i=1, depth = 1; i <= num_branches; i = i*tree_type + tree_offset, depth++)
+ {
+ const int first_of_next_level = i*tree_type + tree_offset;
+ const int end_j = MIN2(first_of_next_level, num_branches + 1); //index of last branch on this level
+ int j;
+
+ //Loop all branches on this level
+#pragma omp parallel for private(j) schedule(static)
+ for(j = i; j < end_j; j++)
+ {
+ int k;
+ const int parent_level_index= j-i;
+ BVHNode* parent = branches_array + j;
+ int nth_positions[ MAX_TREETYPE + 1];
+ char split_axis;
+
+ int parent_leafs_begin = implicit_leafs_index(&data, depth, parent_level_index);
+ int parent_leafs_end = implicit_leafs_index(&data, depth, parent_level_index+1);
+
+ //This calculates the bounding box of this branch
+ //and chooses the largest axis as the axis to divide leafs
+ refit_kdop_hull(tree, parent, parent_leafs_begin, parent_leafs_end);
+ split_axis = get_largest_axis(parent->bv);
+
+ //Save split axis (this can be used on raytracing to speedup the query time)
+ parent->main_axis = split_axis / 2;
+
+ //Split the childs along the split_axis, note: its not needed to sort the whole leafs array
+ //Only to assure that the elements are partioned on a way that each child takes the elements
+ //it would take in case the whole array was sorted.
+ //Split_leafs takes care of that "sort" problem.
+ nth_positions[ 0] = parent_leafs_begin;
+ nth_positions[tree_type] = parent_leafs_end;
+ for(k = 1; k < tree_type; k++)
+ {
+ int child_index = j * tree_type + tree_offset + k;
+ int child_level_index = child_index - first_of_next_level; //child level index
+ nth_positions[k] = implicit_leafs_index(&data, depth+1, child_level_index);
+ }
+
+ split_leafs(leafs_array, nth_positions, tree_type, split_axis);
+
+
+ //Setup children and totnode counters
+ //Not really needed but currently most of BVH code relies on having an explicit children structure
+ for(k = 0; k < tree_type; k++)
+ {
+ int child_index = j * tree_type + tree_offset + k;
+ int child_level_index = child_index - first_of_next_level; //child level index
+
+ int child_leafs_begin = implicit_leafs_index(&data, depth+1, child_level_index);
+ int child_leafs_end = implicit_leafs_index(&data, depth+1, child_level_index+1);
+
+ if(child_leafs_end - child_leafs_begin > 1)
+ {
+ parent->children[k] = branches_array + child_index;
+ parent->children[k]->parent = parent;
+ }
+ else if(child_leafs_end - child_leafs_begin == 1)
+ {
+ parent->children[k] = leafs_array[ child_leafs_begin ];
+ parent->children[k]->parent = parent;
+ }
+ else
+ break;
+
+ parent->totnode = k+1;
+ }
+ }
+ }
+}
+
+
+/*
+ * BLI_bvhtree api
+ */
+BVHTree *BLI_bvhtree_new(int maxsize, float epsilon, char tree_type, char axis)
+{
+ BVHTree *tree;
+ int numnodes, i;
+
+ // theres not support for trees below binary-trees :P
+ if(tree_type < 2)
+ return NULL;
+
+ if(tree_type > MAX_TREETYPE)
+ return NULL;
+
+ tree = (BVHTree *)MEM_callocN(sizeof(BVHTree), "BVHTree");
+
+ //tree epsilon must be >= FLT_EPSILON
+ //so that tangent rays can still hit a bounding volume..
+ //this bug would show up when casting a ray aligned with a kdop-axis and with an edge of 2 faces
+ epsilon = MAX2(FLT_EPSILON, epsilon);
+
+ if(tree)
+ {
+ tree->epsilon = epsilon;
+ tree->tree_type = tree_type;
+ tree->axis = axis;
+
+ if(axis == 26)
+ {
+ tree->start_axis = 0;
+ tree->stop_axis = 13;
+ }
+ else if(axis == 18)
+ {
+ tree->start_axis = 7;
+ tree->stop_axis = 13;
+ }
+ else if(axis == 14)
+ {
+ tree->start_axis = 0;
+ tree->stop_axis = 7;
+ }
+ else if(axis == 8) // AABB
+ {
+ tree->start_axis = 0;
+ tree->stop_axis = 4;
+ }
+ else if(axis == 6) // OBB
+ {
+ tree->start_axis = 0;
+ tree->stop_axis = 3;
+ }
+ else
+ {
+ MEM_freeN(tree);
+ return NULL;
+ }
+
+
+ //Allocate arrays
+ numnodes = maxsize + implicit_needed_branches(tree_type, maxsize) + tree_type;
+
+ tree->nodes = (BVHNode **)MEM_callocN(sizeof(BVHNode *)*numnodes, "BVHNodes");
+
+ if(!tree->nodes)
+ {
+ MEM_freeN(tree);
+ return NULL;
+ }
+
+ tree->nodebv = (float*)MEM_callocN(sizeof(float)* axis * numnodes, "BVHNodeBV");
+ if(!tree->nodebv)
+ {
+ MEM_freeN(tree->nodes);
+ MEM_freeN(tree);
+ }
+
+ tree->nodechild = (BVHNode**)MEM_callocN(sizeof(BVHNode*) * tree_type * numnodes, "BVHNodeBV");
+ if(!tree->nodechild)
+ {
+ MEM_freeN(tree->nodebv);
+ MEM_freeN(tree->nodes);
+ MEM_freeN(tree);
+ }
+
+ tree->nodearray = (BVHNode *)MEM_callocN(sizeof(BVHNode)* numnodes, "BVHNodeArray");
+
+ if(!tree->nodearray)
+ {
+ MEM_freeN(tree->nodechild);
+ MEM_freeN(tree->nodebv);
+ MEM_freeN(tree->nodes);
+ MEM_freeN(tree);
+ return NULL;
+ }
+
+ //link the dynamic bv and child links
+ for(i=0; i< numnodes; i++)
+ {
+ tree->nodearray[i].bv = tree->nodebv + i * axis;
+ tree->nodearray[i].children = tree->nodechild + i * tree_type;
+ }
+
+ }
+
+ return tree;
+}
+
+void BLI_bvhtree_free(BVHTree *tree)
+{
+ if(tree)
+ {
+ MEM_freeN(tree->nodes);
+ MEM_freeN(tree->nodearray);
+ MEM_freeN(tree->nodebv);
+ MEM_freeN(tree->nodechild);
+ MEM_freeN(tree);
+ }
+}
+
+void BLI_bvhtree_balance(BVHTree *tree)
+{
+ int i;
+
+ BVHNode* branches_array = tree->nodearray + tree->totleaf;
+ BVHNode** leafs_array = tree->nodes;
+
+ //This function should only be called once (some big bug goes here if its being called more than once per tree)
+ assert(tree->totbranch == 0);
+
+ //Build the implicit tree
+ non_recursive_bvh_div_nodes(tree, branches_array, leafs_array, tree->totleaf);
+
+ //current code expects the branches to be linked to the nodes array
+ //we perform that linkage here
+ tree->totbranch = implicit_needed_branches(tree->tree_type, tree->totleaf);
+ for(i = 0; i < tree->totbranch; i++)
+ tree->nodes[tree->totleaf + i] = branches_array + i;
+
+ //bvhtree_info(tree);
+}
+
+int BLI_bvhtree_insert(BVHTree *tree, int index, float *co, int numpoints)
+{
+ int i;
+ BVHNode *node = NULL;
+
+ // insert should only possible as long as tree->totbranch is 0
+ if(tree->totbranch > 0)
+ return 0;
+
+ if(tree->totleaf+1 >= MEM_allocN_len(tree->nodes)/sizeof(*(tree->nodes)))
+ return 0;
+
+ // TODO check if have enough nodes in array
+
+ node = tree->nodes[tree->totleaf] = &(tree->nodearray[tree->totleaf]);
+ tree->totleaf++;
+
+ create_kdop_hull(tree, node, co, numpoints, 0);
+ node->index= index;
+
+ // inflate the bv with some epsilon
+ for (i = tree->start_axis; i < tree->stop_axis; i++)
+ {
+ node->bv[(2 * i)] -= tree->epsilon; // minimum
+ node->bv[(2 * i) + 1] += tree->epsilon; // maximum
+ }
+
+ return 1;
+}
+
+
+// call before BLI_bvhtree_update_tree()
+int BLI_bvhtree_update_node(BVHTree *tree, int index, float *co, float *co_moving, int numpoints)
+{
+ int i;
+ BVHNode *node= NULL;
+
+ // check if index exists
+ if(index > tree->totleaf)
+ return 0;
+
+ node = tree->nodearray + index;
+
+ create_kdop_hull(tree, node, co, numpoints, 0);
+
+ if(co_moving)
+ create_kdop_hull(tree, node, co_moving, numpoints, 1);
+
+ // inflate the bv with some epsilon
+ for (i = tree->start_axis; i < tree->stop_axis; i++)
+ {
+ node->bv[(2 * i)] -= tree->epsilon; // minimum
+ node->bv[(2 * i) + 1] += tree->epsilon; // maximum
+ }
+
+ return 1;
+}
+
+// call BLI_bvhtree_update_node() first for every node/point/triangle
+void BLI_bvhtree_update_tree(BVHTree *tree)
+{
+ //Update bottom=>top
+ //TRICKY: the way we build the tree all the childs have an index greater than the parent
+ //This allows us todo a bottom up update by starting on the biger numbered branch
+
+ BVHNode** root = tree->nodes + tree->totleaf;
+ BVHNode** index = tree->nodes + tree->totleaf + tree->totbranch-1;
+
+ for (; index >= root; index--)
+ node_join(tree, *index);
+}
+
+float BLI_bvhtree_getepsilon(BVHTree *tree)
+{
+ return tree->epsilon;
+}
+
+
+/*
+ * BLI_bvhtree_overlap
+ */
+// overlap - is it possbile for 2 bv's to collide ?
+static int tree_overlap(BVHNode *node1, BVHNode *node2, int start_axis, int stop_axis)
+{
+ float *bv1 = node1->bv;
+ float *bv2 = node2->bv;
+
+ float *bv1_end = bv1 + (stop_axis<<1);
+
+ bv1 += start_axis<<1;
+ bv2 += start_axis<<1;
+
+ // test all axis if min + max overlap
+ for (; bv1 != bv1_end; bv1+=2, bv2+=2)
+ {
+ if ((*(bv1) > *(bv2 + 1)) || (*(bv2) > *(bv1 + 1)))
+ return 0;
+ }
+
+ return 1;
+}
+
+static void traverse(BVHOverlapData *data, BVHNode *node1, BVHNode *node2)
+{
+ int j;
+
+ if(tree_overlap(node1, node2, data->start_axis, data->stop_axis))
+ {
+ // check if node1 is a leaf
+ if(!node1->totnode)
+ {
+ // check if node2 is a leaf
+ if(!node2->totnode)
+ {
+
+ if(node1 == node2)
+ {
+ return;
+ }
+
+ if(data->i >= data->max_overlap)
+ {
+ // try to make alloc'ed memory bigger
+ data->overlap = realloc(data->overlap, sizeof(BVHTreeOverlap)*data->max_overlap*2);
+
+ if(!data->overlap)
+ {
+ printf("Out of Memory in traverse\n");
+ return;
+ }
+ data->max_overlap *= 2;
+ }
+
+ // both leafs, insert overlap!
+ data->overlap[data->i].indexA = node1->index;
+ data->overlap[data->i].indexB = node2->index;
+
+ data->i++;
+ }
+ else
+ {
+ for(j = 0; j < data->tree2->tree_type; j++)
+ {
+ if(node2->children[j])
+ traverse(data, node1, node2->children[j]);
+ }
+ }
+ }
+ else
+ {
+
+ for(j = 0; j < data->tree2->tree_type; j++)
+ {
+ if(node1->children[j])
+ traverse(data, node1->children[j], node2);
+ }
+ }
+ }
+ return;
+}
+
+BVHTreeOverlap *BLI_bvhtree_overlap(BVHTree *tree1, BVHTree *tree2, int *result)
+{
+ int j, total = 0;
+ BVHTreeOverlap *overlap = NULL, *to = NULL;
+ BVHOverlapData **data;
+
+ // check for compatibility of both trees (can't compare 14-DOP with 18-DOP)
+ if((tree1->axis != tree2->axis) && (tree1->axis == 14 || tree2->axis == 14) && (tree1->axis == 18 || tree2->axis == 18))
+ return 0;
+
+ // fast check root nodes for collision before doing big splitting + traversal
+ if(!tree_overlap(tree1->nodes[tree1->totleaf], tree2->nodes[tree2->totleaf], MIN2(tree1->start_axis, tree2->start_axis), MIN2(tree1->stop_axis, tree2->stop_axis)))
+ return 0;
+
+ data = MEM_callocN(sizeof(BVHOverlapData *)* tree1->tree_type, "BVHOverlapData_star");
+
+ for(j = 0; j < tree1->tree_type; j++)
+ {
+ data[j] = (BVHOverlapData *)MEM_callocN(sizeof(BVHOverlapData), "BVHOverlapData");
+
+ // init BVHOverlapData
+ data[j]->overlap = (BVHTreeOverlap *)malloc(sizeof(BVHTreeOverlap)*MAX2(tree1->totleaf, tree2->totleaf));
+ data[j]->tree1 = tree1;
+ data[j]->tree2 = tree2;
+ data[j]->max_overlap = MAX2(tree1->totleaf, tree2->totleaf);
+ data[j]->i = 0;
+ data[j]->start_axis = MIN2(tree1->start_axis, tree2->start_axis);
+ data[j]->stop_axis = MIN2(tree1->stop_axis, tree2->stop_axis );
+ }
+
+#pragma omp parallel for private(j) schedule(static)
+ for(j = 0; j < MIN2(tree1->tree_type, tree1->nodes[tree1->totleaf]->totnode); j++)
+ {
+ traverse(data[j], tree1->nodes[tree1->totleaf]->children[j], tree2->nodes[tree2->totleaf]);
+ }
+
+ for(j = 0; j < tree1->tree_type; j++)
+ total += data[j]->i;
+
+ to = overlap = (BVHTreeOverlap *)MEM_callocN(sizeof(BVHTreeOverlap)*total, "BVHTreeOverlap");
+
+ for(j = 0; j < tree1->tree_type; j++)
+ {
+ memcpy(to, data[j]->overlap, data[j]->i*sizeof(BVHTreeOverlap));
+ to+=data[j]->i;
+ }
+
+ for(j = 0; j < tree1->tree_type; j++)
+ {
+ free(data[j]->overlap);
+ MEM_freeN(data[j]);
+ }
+ MEM_freeN(data);
+
+ (*result) = total;
+ return overlap;
+}
+
+
+/*
+ * Nearest neighbour - BLI_bvhtree_find_nearest
+ */
+static float squared_dist(const float *a, const float *b)
+{
+ float tmp[3];
+ VECSUB(tmp, a, b);
+ return INPR(tmp, tmp);
+}
+
+//Determines the nearest point of the given node BV. Returns the squared distance to that point.
+static float calc_nearest_point(BVHNearestData *data, BVHNode *node, float *nearest)
+{
+ int i;
+ const float *bv = node->bv;
+
+ //nearest on AABB hull
+ for(i=0; i != 3; i++, bv += 2)
+ {
+ if(bv[0] > data->proj[i])
+ nearest[i] = bv[0];
+ else if(bv[1] < data->proj[i])
+ nearest[i] = bv[1];
+ else
+ nearest[i] = data->proj[i];
+ }
+
+/*
+ //nearest on a general hull
+ VECCOPY(nearest, data->co);
+ for(i = data->tree->start_axis; i != data->tree->stop_axis; i++, bv+=2)
+ {
+ float proj = INPR( nearest, KDOP_AXES[i]);
+ float dl = bv[0] - proj;
+ float du = bv[1] - proj;
+
+ if(dl > 0)
+ {
+ VECADDFAC(nearest, nearest, KDOP_AXES[i], dl);
+ }
+ else if(du < 0)
+ {
+ VECADDFAC(nearest, nearest, KDOP_AXES[i], du);
+ }
+ }
+*/
+ return squared_dist(data->co, nearest);
+}
+
+
+typedef struct NodeDistance
+{
+ BVHNode *node;
+ float dist;
+
+} NodeDistance;
+
+#define NodeDistance_priority(a,b) ( (a).dist < (b).dist )
+
+// TODO: use a priority queue to reduce the number of nodes looked on
+static void dfs_find_nearest_dfs(BVHNearestData *data, BVHNode *node)
+{
+ if(node->totnode == 0)
+ {
+ if(data->callback)
+ data->callback(data->userdata , node->index, data->co, &data->nearest);
+ else
+ {
+ data->nearest.index = node->index;
+ data->nearest.dist = calc_nearest_point(data, node, data->nearest.co);
+ }
+ }
+ else
+ {
+ //Better heuristic to pick the closest node to dive on
+ int i;
+ float nearest[3];
+
+ if(data->proj[ node->main_axis ] <= node->children[0]->bv[node->main_axis*2+1])
+ {
+
+ for(i=0; i != node->totnode; i++)
+ {
+ if( calc_nearest_point(data, node->children[i], nearest) >= data->nearest.dist) continue;
+ dfs_find_nearest_dfs(data, node->children[i]);
+ }
+ }
+ else
+ {
+ for(i=node->totnode-1; i >= 0 ; i--)
+ {
+ if( calc_nearest_point(data, node->children[i], nearest) >= data->nearest.dist) continue;
+ dfs_find_nearest_dfs(data, node->children[i]);
+ }
+ }
+ }
+}
+
+static void dfs_find_nearest_begin(BVHNearestData *data, BVHNode *node)
+{
+ float nearest[3], sdist;
+ sdist = calc_nearest_point(data, node, nearest);
+ if(sdist >= data->nearest.dist) return;
+ dfs_find_nearest_dfs(data, node);
+}
+
+
+static void NodeDistance_push_heap(NodeDistance *heap, int heap_size)
+PUSH_HEAP_BODY(NodeDistance, NodeDistance_priority, heap, heap_size)
+
+static void NodeDistance_pop_heap(NodeDistance *heap, int heap_size)
+POP_HEAP_BODY(NodeDistance, NodeDistance_priority, heap, heap_size)
+
+//NN function that uses an heap.. this functions leads to an optimal number of min-distance
+//but for normal tri-faces and BV 6-dop.. a simple dfs with local heuristics (as implemented
+//in source/blender/blenkernel/intern/shrinkwrap.c) works faster.
+//
+//It may make sense to use this function if the callback queries are very slow.. or if its impossible
+//to get a nice heuristic
+//
+//this function uses "malloc/free" instead of the MEM_* because it intends to be openmp safe
+static void bfs_find_nearest(BVHNearestData *data, BVHNode *node)
+{
+ int i;
+ NodeDistance default_heap[DEFAULT_FIND_NEAREST_HEAP_SIZE];
+ NodeDistance *heap=default_heap, current;
+ int heap_size = 0, max_heap_size = sizeof(default_heap)/sizeof(default_heap[0]);
+ float nearest[3];
+
+ int callbacks = 0, push_heaps = 0;
+
+ if(node->totnode == 0)
+ {
+ dfs_find_nearest_dfs(data, node);
+ return;
+ }
+
+ current.node = node;
+ current.dist = calc_nearest_point(data, node, nearest);
+
+ while(current.dist < data->nearest.dist)
+ {
+// printf("%f : %f\n", current.dist, data->nearest.dist);
+ for(i=0; i< current.node->totnode; i++)
+ {
+ BVHNode *child = current.node->children[i];
+ if(child->totnode == 0)
+ {
+ callbacks++;
+ dfs_find_nearest_dfs(data, child);
+ }
+ else
+ {
+ //adjust heap size
+ if(heap_size >= max_heap_size
+ && ADJUST_MEMORY(default_heap, (void**)&heap, heap_size+1, &max_heap_size, sizeof(heap[0])) == FALSE)
+ {
+ printf("WARNING: bvh_find_nearest got out of memory\n");
+
+ if(heap != default_heap)
+ free(heap);
+
+ return;
+ }
+
+ heap[heap_size].node = current.node->children[i];
+ heap[heap_size].dist = calc_nearest_point(data, current.node->children[i], nearest);
+
+ if(heap[heap_size].dist >= data->nearest.dist) continue;
+ heap_size++;
+
+ NodeDistance_push_heap(heap, heap_size);
+ // PUSH_HEAP_BODY(NodeDistance, NodeDistance_priority, heap, heap_size);
+ push_heaps++;
+ }
+ }
+
+ if(heap_size == 0) break;
+
+ current = heap[0];
+ NodeDistance_pop_heap(heap, heap_size);
+// POP_HEAP_BODY(NodeDistance, NodeDistance_priority, heap, heap_size);
+ heap_size--;
+ }
+
+// printf("hsize=%d, callbacks=%d, pushs=%d\n", heap_size, callbacks, push_heaps);
+
+ if(heap != default_heap)
+ free(heap);
+}
+
+
+int BLI_bvhtree_find_nearest(BVHTree *tree, const float *co, BVHTreeNearest *nearest, BVHTree_NearestPointCallback callback, void *userdata)
+{
+ int i;
+
+ BVHNearestData data;
+ BVHNode* root = tree->nodes[tree->totleaf];
+
+ //init data to search
+ data.tree = tree;
+ data.co = co;
+
+ data.callback = callback;
+ data.userdata = userdata;
+
+ for(i = data.tree->start_axis; i != data.tree->stop_axis; i++)
+ {
+ data.proj[i] = INPR(data.co, KDOP_AXES[i]);
+ }
+
+ if(nearest)
+ {
+ memcpy( &data.nearest , nearest, sizeof(*nearest) );
+ }
+ else
+ {
+ data.nearest.index = -1;
+ data.nearest.dist = FLT_MAX;
+ }
+
+ //dfs search
+ if(root)
+ dfs_find_nearest_begin(&data, root);
+
+ //copy back results
+ if(nearest)
+ {
+ memcpy(nearest, &data.nearest, sizeof(*nearest));
+ }
+
+ return data.nearest.index;
+}
+
+
+/*
+ * Raycast - BLI_bvhtree_ray_cast
+ *
+ * raycast is done by performing a DFS on the BVHTree and saving the closest hit
+ */
+
+//Determines the distance that the ray must travel to hit the bounding volume of the given node
+static float ray_nearest_hit(BVHRayCastData *data, BVHNode *node)
+{
+ int i;
+ const float *bv = node->bv;
+
+ float low = 0, upper = data->hit.dist;
+
+ for(i=0; i != 3; i++, bv += 2)
+ {
+ if(data->ray_dot_axis[i] == 0.0f)
+ {
+ //axis aligned ray
+ if(data->ray.origin[i] < bv[0] - data->ray.radius
+ || data->ray.origin[i] > bv[1] + data->ray.radius)
+ return FLT_MAX;
+ }
+ else
+ {
+ float ll = (bv[0] - data->ray.radius - data->ray.origin[i]) / data->ray_dot_axis[i];
+ float lu = (bv[1] + data->ray.radius - data->ray.origin[i]) / data->ray_dot_axis[i];
+
+ if(data->ray_dot_axis[i] > 0.0f)
+ {
+ if(ll > low) low = ll;
+ if(lu < upper) upper = lu;
+ }
+ else
+ {
+ if(lu > low) low = lu;
+ if(ll < upper) upper = ll;
+ }
+
+ if(low > upper) return FLT_MAX;
+ }
+ }
+ return low;
+}
+
+static void dfs_raycast(BVHRayCastData *data, BVHNode *node)
+{
+ int i;
+
+ //ray-bv is really fast.. and simple tests revealed its worth to test it
+ //before calling the ray-primitive functions
+ float dist = ray_nearest_hit(data, node);
+ if(dist >= data->hit.dist) return;
+
+ if(node->totnode == 0)
+ {
+ if(data->callback)
+ data->callback(data->userdata, node->index, &data->ray, &data->hit);
+ else
+ {
+ data->hit.index = node->index;
+ data->hit.dist = dist;
+ VECADDFAC(data->hit.co, data->ray.origin, data->ray.direction, dist);
+ }
+ }
+ else
+ {
+ //pick loop direction to dive into the tree (based on ray direction and split axis)
+ if(data->ray_dot_axis[ node->main_axis ] > 0.0f)
+ {
+ for(i=0; i != node->totnode; i++)
+ {
+ dfs_raycast(data, node->children[i]);
+ }
+ }
+ else
+ {
+ for(i=node->totnode-1; i >= 0; i--)
+ {
+ dfs_raycast(data, node->children[i]);
+ }
+ }
+ }
+}
+
+int BLI_bvhtree_ray_cast(BVHTree *tree, const float *co, const float *dir, float radius, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata)
+{
+ int i;
+ BVHRayCastData data;
+ BVHNode * root = tree->nodes[tree->totleaf];
+
+ data.tree = tree;
+
+ data.callback = callback;
+ data.userdata = userdata;
+
+ VECCOPY(data.ray.origin, co);
+ VECCOPY(data.ray.direction, dir);
+ data.ray.radius = radius;
+
+ Normalize(data.ray.direction);
+
+ for(i=0; i<3; i++)
+ {
+ data.ray_dot_axis[i] = INPR( data.ray.direction, KDOP_AXES[i]);
+
+ if(fabs(data.ray_dot_axis[i]) < FLT_EPSILON)
+ data.ray_dot_axis[i] = 0.0;
+ }
+
+
+ if(hit)
+ memcpy( &data.hit, hit, sizeof(*hit) );
+ else
+ {
+ data.hit.index = -1;
+ data.hit.dist = FLT_MAX;
+ }
+
+ if(root)
+ dfs_raycast(&data, root);
+
+
+ if(hit)
+ memcpy( hit, &data.hit, sizeof(*hit) );
+
+ return data.hit.index;
+}
+
diff --git a/source/blender/blenlib/intern/BLI_kdtree.c b/source/blender/blenlib/intern/BLI_kdtree.c
index 03b7561bad5..8e8b2e9f0e9 100644
--- a/source/blender/blenlib/intern/BLI_kdtree.c
+++ b/source/blender/blenlib/intern/BLI_kdtree.c
@@ -163,11 +163,18 @@ int BLI_kdtree_find_nearest(KDTree *tree, float *co, float *nor, KDTreeNearest *
min_node= root;
min_dist= squared_distance(root->co,co,root->nor,nor);
- if(root->left)
- stack[cur++]=root->left;
-
- if(root->right)
- stack[cur++]=root->right;
+ if(co[root->d] < root->co[root->d]) {
+ if(root->right)
+ stack[cur++]=root->right;
+ if(root->left)
+ stack[cur++]=root->left;
+ }
+ else {
+ if(root->left)
+ stack[cur++]=root->left;
+ if(root->right)
+ stack[cur++]=root->right;
+ }
while(cur--){
node=stack[cur];
@@ -263,11 +270,18 @@ int BLI_kdtree_find_n_nearest(KDTree *tree, int n, float *co, float *nor, KDTree
cur_dist= squared_distance(root->co,co,root->nor,nor);
add_nearest(nearest,&found,n,root->index,cur_dist,root->co);
- if(root->left)
- stack[cur++]=root->left;
-
- if(root->right)
- stack[cur++]=root->right;
+ if(co[root->d] < root->co[root->d]) {
+ if(root->right)
+ stack[cur++]=root->right;
+ if(root->left)
+ stack[cur++]=root->left;
+ }
+ else {
+ if(root->left)
+ stack[cur++]=root->left;
+ if(root->right)
+ stack[cur++]=root->right;
+ }
while(cur--){
node=stack[cur];
diff --git a/source/blender/blenlib/intern/BLI_mempool.c b/source/blender/blenlib/intern/BLI_mempool.c
new file mode 100644
index 00000000000..7ac7b8b1791
--- /dev/null
+++ b/source/blender/blenlib/intern/BLI_mempool.c
@@ -0,0 +1,140 @@
+/**
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2008 by Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/*
+ Simple, fast memory allocator for allocating many elements of the same size.
+*/
+
+#include "MEM_guardedalloc.h"
+#include "BLI_blenlib.h"
+#include "DNA_listBase.h"
+#include "BLI_linklist.h"
+#include <string.h>
+
+typedef struct BLI_freenode{
+ struct BLI_freenode *next;
+}BLI_freenode;
+
+typedef struct BLI_mempool_chunk{
+ struct BLI_mempool_chunk *next, *prev;
+ void *data;
+}BLI_mempool_chunk;
+
+typedef struct BLI_mempool{
+ struct ListBase chunks;
+ int esize, csize, pchunk; /*size of elements and chunks in bytes and number of elements per chunk*/
+ struct BLI_freenode *free; /*free element list. Interleaved into chunk datas.*/
+}BLI_mempool;
+
+BLI_mempool *BLI_mempool_create(int esize, int tote, int pchunk)
+{ BLI_mempool *pool = NULL;
+ BLI_freenode *lasttail = NULL, *curnode = NULL;
+ int i,j, maxchunks;
+ char *addr;
+
+ /*allocate the pool structure*/
+ pool = MEM_mallocN(sizeof(BLI_mempool),"memory pool");
+ pool->esize = esize;
+ pool->pchunk = pchunk;
+ pool->csize = esize * pchunk;
+ pool->chunks.first = pool->chunks.last = NULL;
+
+ maxchunks = tote / pchunk;
+
+ /*allocate the actual chunks*/
+ for(i=0; i < maxchunks; i++){
+ BLI_mempool_chunk *mpchunk = MEM_mallocN(sizeof(BLI_mempool_chunk), "BLI_Mempool Chunk");
+ mpchunk->next = mpchunk->prev = NULL;
+ mpchunk->data = MEM_mallocN(pool->csize, "BLI Mempool Chunk Data");
+ BLI_addtail(&(pool->chunks), mpchunk);
+
+ if(i==0) pool->free = mpchunk->data; /*start of the list*/
+ /*loop through the allocated data, building the pointer structures*/
+ for(addr = mpchunk->data, j=0; j < pool->pchunk; j++){
+ curnode = ((BLI_freenode*)addr);
+ addr += pool->esize;
+ curnode->next = (BLI_freenode*)addr;
+ }
+ /*final pointer in the previously allocated chunk is wrong.*/
+ if(lasttail) lasttail->next = mpchunk->data;
+ /*set the end of this chunks memoryy to the new tail for next iteration*/
+ lasttail = curnode;
+ }
+ /*terminate the list*/
+ curnode->next = NULL;
+ return pool;
+}
+void *BLI_mempool_alloc(BLI_mempool *pool){
+ void *retval=NULL;
+ BLI_freenode *curnode=NULL;
+ char *addr=NULL;
+ int j;
+
+ if(!(pool->free)){
+ /*need to allocate a new chunk*/
+ BLI_mempool_chunk *mpchunk = MEM_mallocN(sizeof(BLI_mempool_chunk), "BLI_Mempool Chunk");
+ mpchunk->next = mpchunk->prev = NULL;
+ mpchunk->data = MEM_mallocN(pool->csize, "BLI_Mempool Chunk Data");
+ BLI_addtail(&(pool->chunks), mpchunk);
+
+ pool->free = mpchunk->data; /*start of the list*/
+ for(addr = mpchunk->data, j=0; j < pool->pchunk; j++){
+ curnode = ((BLI_freenode*)addr);
+ addr += pool->esize;
+ curnode->next = (BLI_freenode*)addr;
+ }
+ curnode->next = NULL; /*terminate the list*/
+ }
+
+ retval = pool->free;
+ pool->free = pool->free->next;
+ //memset(retval, 0, pool->esize);
+ return retval;
+}
+
+void *BLI_mempool_calloc(BLI_mempool *pool){
+ void *retval=NULL;
+ retval = BLI_mempool_alloc(pool);
+ memset(retval, 0, pool->esize);
+ return retval;
+}
+
+
+
+void BLI_mempool_free(BLI_mempool *pool, void *addr){ //doesnt protect against double frees, dont be stupid!
+ BLI_freenode *newhead = addr;
+ newhead->next = pool->free;
+ pool->free = newhead;
+}
+void BLI_mempool_destroy(BLI_mempool *pool)
+{
+ BLI_mempool_chunk *mpchunk=NULL;
+ for(mpchunk = pool->chunks.first; mpchunk; mpchunk = mpchunk->next) MEM_freeN(mpchunk->data);
+ BLI_freelistN(&(pool->chunks));
+ MEM_freeN(pool);
+}
diff --git a/source/blender/blenlib/intern/BLI_storage.h b/source/blender/blenlib/intern/BLI_storage.h
index 022a579fb66..3e0dec367da 100644
--- a/source/blender/blenlib/intern/BLI_storage.h
+++ b/source/blender/blenlib/intern/BLI_storage.h
@@ -28,6 +28,13 @@
#ifndef BLI_STORAGE_H
#define BLI_STORAGE_H
+#ifndef __APPLE__
+#ifndef WIN32
+#define _LARGEFILE_SOURCE 1
+#define _FILE_OFFSET_BITS 64
+#endif
+#endif
+
#include "BLI_storage_types.h"
void BLI_adddirstrings(void);
diff --git a/source/blender/blenlib/intern/Makefile b/source/blender/blenlib/intern/Makefile
index 8d6ca9b6dc3..f92fa0a7e25 100644
--- a/source/blender/blenlib/intern/Makefile
+++ b/source/blender/blenlib/intern/Makefile
@@ -56,3 +56,6 @@ endif
ifeq ($(WITH_FREETYPE2), true)
CPPFLAGS += -DWITH_FREETYPE2
endif
+ifeq ($(OS),linux)
+ CPPFLAGS += -I$(OCGDIR)/extern/binreloc/include
+endif
diff --git a/source/blender/blenlib/intern/arithb.c b/source/blender/blenlib/intern/arithb.c
index 735ff2e65f7..0f2226fc872 100644
--- a/source/blender/blenlib/intern/arithb.c
+++ b/source/blender/blenlib/intern/arithb.c
@@ -54,11 +54,13 @@
#include <stdio.h>
#include "BLI_arithb.h"
+#include "BLI_memarena.h"
/* A few small defines. Keep'em local! */
#define SMALL_NUMBER 1.e-8
#define ABS(x) ((x) < 0 ? -(x) : (x))
#define SWAP(type, a, b) { type sw_ap; sw_ap=(a); (a)=(b); (b)=sw_ap; }
+#define CLAMP(a, b, c) if((a)<(b)) (a)=(b); else if((a)>(c)) (a)=(c)
#if defined(WIN32) || defined(__APPLE__)
@@ -757,6 +759,28 @@ void Mat4MulSerie(float answ[][4], float m1[][4],
}
}
+void Mat3BlendMat3(float out[][3], float dst[][3], float src[][3], float srcweight)
+{
+ float squat[4], dquat[4], fquat[4];
+ float ssize[3], dsize[3], fsize[4];
+ float rmat[3][3], smat[3][3];
+
+ Mat3ToQuat(dst, dquat);
+ Mat3ToSize(dst, dsize);
+
+ Mat3ToQuat(src, squat);
+ Mat3ToSize(src, ssize);
+
+ /* do blending */
+ QuatInterpol(fquat, dquat, squat, srcweight);
+ VecLerpf(fsize, dsize, ssize, srcweight);
+
+ /* compose new matrix */
+ QuatToMat3(fquat, rmat);
+ SizeToMat3(fsize, smat);
+ Mat3MulMat3(out, rmat, smat);
+}
+
void Mat4BlendMat4(float out[][4], float dst[][4], float src[][4], float srcweight)
{
float squat[4], dquat[4], fquat[4];
@@ -1002,6 +1026,19 @@ int FloatCompare( float *v1, float *v2, float limit)
return 0;
}
+int FloatCompare4( float *v1, float *v2, float limit)
+{
+
+ if( fabs(v1[0]-v2[0])<limit ) {
+ if( fabs(v1[1]-v2[1])<limit ) {
+ if( fabs(v1[2]-v2[2])<limit ) {
+ if( fabs(v1[3]-v2[3])<limit ) return 1;
+ }
+ }
+ }
+ return 0;
+}
+
float FloatLerpf( float target, float origin, float fac)
{
return (fac*target) + (1.0f-fac)*origin;
@@ -1334,9 +1371,36 @@ void NormalQuat(float *q)
}
}
-float *vectoquat( float *vec, short axis, short upflag)
+void RotationBetweenVectorsToQuat(float *q, float v1[3], float v2[3])
+{
+ float axis[3];
+ float angle;
+
+ Crossf(axis, v1, v2);
+
+ angle = NormalizedVecAngle2(v1, v2);
+
+ AxisAngleToQuat(q, axis, angle);
+}
+
+void AxisAngleToQuat(float *q, float *axis, float angle)
+{
+ float nor[3];
+ float si;
+
+ VecCopyf(nor, axis);
+ Normalize(nor);
+
+ angle /= 2;
+ si = (float)sin(angle);
+ q[0] = (float)cos(angle);
+ q[1] = nor[0] * si;
+ q[2] = nor[1] * si;
+ q[3] = nor[2] * si;
+}
+
+void vectoquat(float *vec, short axis, short upflag, float *q)
{
- static float q1[4];
float q2[4], nor[3], *fp, mat[3][3], angle, si, co, x2, y2, z2, len1;
/* first rotate to axis */
@@ -1348,11 +1412,11 @@ float *vectoquat( float *vec, short axis, short upflag)
x2= -vec[0] ; y2= -vec[1] ; z2= -vec[2];
}
- q1[0]=1.0;
- q1[1]=q1[2]=q1[3]= 0.0;
+ q[0]=1.0;
+ q[1]=q[2]=q[3]= 0.0;
len1= (float)sqrt(x2*x2+y2*y2+z2*z2);
- if(len1 == 0.0) return(q1);
+ if(len1 == 0.0) return;
/* nasty! I need a good routine for this...
* problem is a rotation of an Y axis to the negative Y-axis for example.
@@ -1363,9 +1427,8 @@ float *vectoquat( float *vec, short axis, short upflag)
nor[1]= -z2;
nor[2]= y2;
- if( fabs(y2)+fabs(z2)<0.0001 ) {
+ if(fabs(y2)+fabs(z2)<0.0001)
nor[1]= 1.0;
- }
co= x2;
}
@@ -1374,9 +1437,8 @@ float *vectoquat( float *vec, short axis, short upflag)
nor[1]= 0.0;
nor[2]= -x2;
- if( fabs(x2)+fabs(z2)<0.0001 ) {
+ if(fabs(x2)+fabs(z2)<0.0001)
nor[2]= 1.0;
- }
co= y2;
}
@@ -1385,9 +1447,8 @@ float *vectoquat( float *vec, short axis, short upflag)
nor[1]= x2;
nor[2]= 0.0;
- if( fabs(x2)+fabs(y2)<0.0001 ) {
+ if(fabs(x2)+fabs(y2)<0.0001)
nor[0]= 1.0;
- }
co= z2;
}
@@ -1397,13 +1458,13 @@ float *vectoquat( float *vec, short axis, short upflag)
angle= 0.5f*saacos(co);
si= (float)sin(angle);
- q1[0]= (float)cos(angle);
- q1[1]= nor[0]*si;
- q1[2]= nor[1]*si;
- q1[3]= nor[2]*si;
+ q[0]= (float)cos(angle);
+ q[1]= nor[0]*si;
+ q[2]= nor[1]*si;
+ q[3]= nor[2]*si;
if(axis!=upflag) {
- QuatToMat3(q1, mat);
+ QuatToMat3(q, mat);
fp= mat[2];
if(axis==0) {
@@ -1426,10 +1487,8 @@ float *vectoquat( float *vec, short axis, short upflag)
q2[2]= y2*si;
q2[3]= z2*si;
- QuatMul(q1,q2,q1);
+ QuatMul(q,q2,q);
}
-
- return(q1);
}
void VecUpMat3old( float *vec, float mat[][3], short axis)
@@ -1729,9 +1788,13 @@ void DQuatToMat4(DualQuat *dq, float mat[][4])
void DQuatAddWeighted(DualQuat *dqsum, DualQuat *dq, float weight)
{
+ int flipped= 0;
+
/* make sure we interpolate quats in the right direction */
- if (QuatDot(dq->quat, dqsum->quat) < 0)
- weight = -weight;
+ if (QuatDot(dq->quat, dqsum->quat) < 0) {
+ flipped= 1;
+ weight= -weight;
+ }
/* interpolate rotation and translation */
dqsum->quat[0] += weight*dq->quat[0];
@@ -1748,6 +1811,9 @@ void DQuatAddWeighted(DualQuat *dqsum, DualQuat *dq, float weight)
if (dq->scale_weight) {
float wmat[4][4];
+ if(flipped) /* we don't want negative weights for scaling */
+ weight= -weight;
+
Mat4CpyMat4(wmat, dq->scale);
Mat4MulFloat((float*)wmat, weight);
Mat4AddMat4(dqsum->scale, dqsum->scale, wmat);
@@ -2094,6 +2160,14 @@ void VecLerpf(float *target, float *a, float *b, float t)
target[2]= s*a[2] + t*b[2];
}
+void Vec2Lerpf(float *target, float *a, float *b, float t)
+{
+ float s = 1.0f-t;
+
+ target[0]= s*a[0] + t*b[0];
+ target[1]= s*a[1] + t*b[1];
+}
+
void VecMidf(float *v, float *v1, float *v2)
{
v[0]= 0.5f*(v1[0]+ v2[0]);
@@ -2111,8 +2185,9 @@ void VecMulf(float *v1, float f)
void VecOrthoBasisf(float *v, float *v1, float *v2)
{
- if (v[0] == 0.0f && v[1] == 0.0f)
- {
+ float f = sqrt(v[0]*v[0] + v[1]*v[1]);
+
+ if (f < 1e-35f) {
// degenerate case
v1[0] = 0.0f; v1[1] = 1.0f; v1[2] = 0.0f;
if (v[2] > 0.0f) {
@@ -2122,9 +2197,8 @@ void VecOrthoBasisf(float *v, float *v1, float *v2)
v2[0] = -1.0f; v2[1] = v2[2] = 0.0f;
}
}
- else
- {
- float f = 1.0f/sqrt(v[0]*v[0] + v[1]*v[1]);
+ else {
+ f = 1.0f/f;
v1[0] = v[1]*f;
v1[1] = -v[0]*f;
v1[2] = 0.0f;
@@ -2157,6 +2231,11 @@ int VecEqual(float *v1, float *v2)
return ((v1[0]==v2[0]) && (v1[1]==v2[1]) && (v1[2]==v2[2]));
}
+int VecIsNull(float *v)
+{
+ return (v[0] == 0 && v[1] == 0 && v[2] == 0);
+}
+
void CalcNormShort( short *v1, short *v2, short *v3, float *n) /* is also cross product */
{
float n1[3],n2[3];
@@ -2256,6 +2335,20 @@ double Sqrt3d(double d)
else return exp(log(d)/3);
}
+void NormalShortToFloat(float *out, short *in)
+{
+ out[0] = in[0] / 32767.0;
+ out[1] = in[1] / 32767.0;
+ out[2] = in[2] / 32767.0;
+}
+
+void NormalFloatToShort(short *out, float *in)
+{
+ out[0] = (short)(in[0] * 32767.0);
+ out[1] = (short)(in[1] * 32767.0);
+ out[2] = (short)(in[2] * 32767.0);
+}
+
/* distance v1 to line v2-v3 */
/* using Hesse formula, NO LINE PIECE! */
float DistVL2Dfl( float *v1, float *v2, float *v3) {
@@ -2427,7 +2520,7 @@ short IsectLL2Df(float *v1, float *v2, float *v3, float *v4)
1: intersection
*/
-short IsectLLPt2Df(float x0,float y0,float x1,float y1,
+static short IsectLLPt2Df(float x0,float y0,float x1,float y1,
float x2,float y2,float x3,float y3, float *xi,float *yi)
{
@@ -2477,37 +2570,50 @@ short IsectLLPt2Df(float x0,float y0,float x1,float y1,
} // end Intersect_Lines
#define SIDE_OF_LINE(pa,pb,pp) ((pa[0]-pp[0])*(pb[1]-pp[1]))-((pb[0]-pp[0])*(pa[1]-pp[1]))
-#define ISECT_EPSILON 1e-6
-
/* point in tri */
int IsectPT2Df(float pt[2], float v1[2], float v2[2], float v3[2])
{
- if ((SIDE_OF_LINE(v1,v2,pt)>=-ISECT_EPSILON) &&
- (SIDE_OF_LINE(v2,v3,pt)>=-ISECT_EPSILON) &&
- (SIDE_OF_LINE(v3,v1,pt)>=-ISECT_EPSILON))
- return 1;
- else {
- return 0;
+ if (SIDE_OF_LINE(v1,v2,pt)>=0.0) {
+ if (SIDE_OF_LINE(v2,v3,pt)>=0.0) {
+ if (SIDE_OF_LINE(v3,v1,pt)>=0.0) {
+ return 1;
+ }
+ }
+ } else {
+ if (! (SIDE_OF_LINE(v2,v3,pt)>=0.0) ) {
+ if (! (SIDE_OF_LINE(v3,v1,pt)>=0.0)) {
+ return -1;
+ }
+ }
}
+
+ return 0;
}
/* point in quad - only convex quads */
int IsectPQ2Df(float pt[2], float v1[2], float v2[2], float v3[2], float v4[2])
{
- if ((SIDE_OF_LINE(v1,v2,pt)>=-ISECT_EPSILON) &&
- (SIDE_OF_LINE(v2,v3,pt)>=-ISECT_EPSILON) &&
- (SIDE_OF_LINE(v3,v4,pt)>=-ISECT_EPSILON) &&
- (SIDE_OF_LINE(v4,v1,pt)>=-ISECT_EPSILON))
- return 1;
- else
- return 0;
+ if (SIDE_OF_LINE(v1,v2,pt)>=0.0) {
+ if (SIDE_OF_LINE(v2,v3,pt)>=0.0) {
+ if (SIDE_OF_LINE(v3,v4,pt)>=0.0) {
+ if (SIDE_OF_LINE(v4,v1,pt)>=0.0) {
+ return 1;
+ }
+ }
+ }
+ } else {
+ if (! (SIDE_OF_LINE(v2,v3,pt)>=0.0) ) {
+ if (! (SIDE_OF_LINE(v3,v4,pt)>=0.0)) {
+ if (! (SIDE_OF_LINE(v4,v1,pt)>=0.0)) {
+ return -1;
+ }
+ }
+ }
+ }
+
+ return 0;
}
-
- /* copied from Geometry.c - todo - move to arithb.c or some other generic place we can reuse */
-#define SIDE_OF_LINE(pa,pb,pp) ((pa[0]-pp[0])*(pb[1]-pp[1]))-((pb[0]-pp[0])*(pa[1]-pp[1]))
-#define POINT_IN_TRI(p0,p1,p2,p3) ((SIDE_OF_LINE(p1,p2,p0)>=0) && (SIDE_OF_LINE(p2,p3,p0)>=0) && (SIDE_OF_LINE(p3,p1,p0)>=0))
-
/**
*
* @param min
@@ -2871,6 +2977,22 @@ float VecAngle3(float *v1, float *v2, float *v3)
return NormalizedVecAngle2(vec1, vec2) * 180.0/M_PI;
}
+float VecAngle3_2D(float *v1, float *v2, float *v3)
+{
+ float vec1[2], vec2[2];
+
+ vec1[0] = v2[0]-v1[0];
+ vec1[1] = v2[1]-v1[1];
+
+ vec2[0] = v2[0]-v3[0];
+ vec2[1] = v2[1]-v3[1];
+
+ Normalize2(vec1);
+ Normalize2(vec2);
+
+ return NormalizedVecAngle2_2D(vec1, vec2) * 180.0/M_PI;
+}
+
/* Return the shortest angle in degrees between the 2 vectors */
float VecAngle2(float *v1, float *v2)
{
@@ -2900,6 +3022,21 @@ float NormalizedVecAngle2(float *v1, float *v2)
return 2.0f*saasin(VecLenf(v2, v1)/2.0);
}
+float NormalizedVecAngle2_2D(float *v1, float *v2)
+{
+ /* this is the same as acos(Inpf(v1, v2)), but more accurate */
+ if (Inp2f(v1, v2) < 0.0f) {
+ float vec[2];
+
+ vec[0]= -v2[0];
+ vec[1]= -v2[1];
+
+ return (float)M_PI - 2.0f*saasin(Vec2Lenf(vec, v1)/2.0f);
+ }
+ else
+ return 2.0f*saasin(Vec2Lenf(v2, v1)/2.0);
+}
+
void euler_rot(float *beul, float ang, char axis)
{
float eul[3], mat1[3][3], mat2[3][3], totmat[3][3];
@@ -3351,6 +3488,80 @@ void rgb_to_hsv(float r, float g, float b, float *lh, float *ls, float *lv)
*lv = v;
}
+/*http://brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html */
+
+void xyz_to_rgb(float xc, float yc, float zc, float *r, float *g, float *b, int colorspace)
+{
+ switch (colorspace) {
+ case BLI_CS_SMPTE:
+ *r = (3.50570 * xc) + (-1.73964 * yc) + (-0.544011 * zc);
+ *g = (-1.06906 * xc) + (1.97781 * yc) + (0.0351720 * zc);
+ *b = (0.0563117 * xc) + (-0.196994 * yc) + (1.05005 * zc);
+ break;
+ case BLI_CS_REC709:
+ *r = (3.240476 * xc) + (-1.537150 * yc) + (-0.498535 * zc);
+ *g = (-0.969256 * xc) + (1.875992 * yc) + (0.041556 * zc);
+ *b = (0.055648 * xc) + (-0.204043 * yc) + (1.057311 * zc);
+ break;
+ case BLI_CS_CIE:
+ *r = (2.28783848734076f * xc) + (-0.833367677835217f * yc) + (-0.454470795871421f * zc);
+ *g = (-0.511651380743862f * xc) + (1.42275837632178f * yc) + (0.0888930017552939f * zc);
+ *b = (0.00572040983140966f * xc) + (-0.0159068485104036f * yc) + (1.0101864083734f * zc);
+ break;
+ }
+}
+
+/*If the requested RGB shade contains a negative weight for
+ one of the primaries, it lies outside the colour gamut
+ accessible from the given triple of primaries. Desaturate
+ it by adding white, equal quantities of R, G, and B, enough
+ to make RGB all positive. The function returns 1 if the
+ components were modified, zero otherwise.*/
+int constrain_rgb(float *r, float *g, float *b)
+{
+ float w;
+
+ /* Amount of white needed is w = - min(0, *r, *g, *b) */
+
+ w = (0 < *r) ? 0 : *r;
+ w = (w < *g) ? w : *g;
+ w = (w < *b) ? w : *b;
+ w = -w;
+
+ /* Add just enough white to make r, g, b all positive. */
+
+ if (w > 0) {
+ *r += w; *g += w; *b += w;
+ return 1; /* Colour modified to fit RGB gamut */
+ }
+
+ return 0; /* Colour within RGB gamut */
+}
+
+/*Transform linear RGB values to nonlinear RGB values. Rec.
+ 709 is ITU-R Recommendation BT. 709 (1990) ``Basic
+ Parameter Values for the HDTV Standard for the Studio and
+ for International Programme Exchange'', formerly CCIR Rec.
+ 709.*/
+static void gamma_correct(float *c)
+{
+ /* Rec. 709 gamma correction. */
+ float cc = 0.018;
+
+ if (*c < cc) {
+ *c *= ((1.099 * pow(cc, 0.45)) - 0.099) / cc;
+ } else {
+ *c = (1.099 * pow(*c, 0.45)) - 0.099;
+ }
+}
+
+void gamma_correct_rgb(float *r, float *g, float *b)
+{
+ gamma_correct(r);
+ gamma_correct(g);
+ gamma_correct(b);
+}
+
/* we define a 'cpack' here as a (3 byte color code) number that can be expressed like 0xFFAA66 or so.
for that reason it is sensitive for endianness... with this function it works correctly
@@ -3412,6 +3623,8 @@ void tubemap(float x, float y, float z, float *u, float *v)
len= sqrt(x*x+y*y);
if(len>0) {
*u = (1.0 - (atan2(x/len,y/len) / M_PI)) / 2.0;
+ } else {
+ *v = *u = 0.0f; /* to avoid un-initialized variables */
}
}
@@ -3429,11 +3642,15 @@ void spheremap(float x, float y, float z, float *u, float *v)
z/=len;
*v = 1.0- saacos(z)/M_PI;
+ } else {
+ *v = *u = 0.0f; /* to avoid un-initialized variables */
}
}
/* ------------------------------------------------------------------------- */
+/* proposed api by ton and zr, not used yet */
+#if 0
/* ***************** m1 = m2 ***************** */
void cpy_m3_m3(float m1[][3], float m2[][3])
{
@@ -3457,7 +3674,6 @@ void ident_m4(float m[][4])
m[3][0]= m[3][1]= m[3][2]= 0.0;
}
-
/* ***************** m1 = m2 (pre) * m3 (post) ***************** */
void mul_m3_m3m3(float m1[][3], float m2[][3], float m3[][3])
{
@@ -3595,6 +3811,8 @@ void mul_v3_v3m4(float *v1, float *v2, float mat[][4])
}
+#endif
+
/* moved from effect.c
test if the line starting at p1 ending at p2 intersects the triangle v0..v2
return non zero if it does
@@ -3634,14 +3852,89 @@ int LineIntersectsTriangle(float p1[3], float p2[3], float v0[3], float v1[3], f
return 1;
}
+/* moved from effect.c
+ test if the ray starting at p1 going in d direction intersects the triangle v0..v2
+ return non zero if it does
+*/
+int RayIntersectsTriangle(float p1[3], float d[3], float v0[3], float v1[3], float v2[3], float *lambda, float *uv)
+{
+ float p[3], s[3], e1[3], e2[3], q[3];
+ float a, f, u, v;
+
+ VecSubf(e1, v1, v0);
+ VecSubf(e2, v2, v0);
+
+ Crossf(p, d, e2);
+ a = Inpf(e1, p);
+ if ((a > -0.000001) && (a < 0.000001)) return 0;
+ f = 1.0f/a;
+
+ VecSubf(s, p1, v0);
+
+ Crossf(q, s, e1);
+ *lambda = f * Inpf(e2, q);
+ if ((*lambda < 0.0)) return 0;
+
+ u = f * Inpf(s, p);
+ if ((u < 0.0)||(u > 1.0)) return 0;
+
+ v = f * Inpf(d, q);
+ if ((v < 0.0)||((u + v) > 1.0)) return 0;
+
+ if(uv) {
+ uv[0]= u;
+ uv[1]= v;
+ }
+
+ return 1;
+}
+
/* Adapted from the paper by Kasper Fauerby */
/* "Improved Collision detection and Response" */
+static int getLowestRoot(float a, float b, float c, float maxR, float* root)
+{
+ // Check if a solution exists
+ float determinant = b*b - 4.0f*a*c;
+
+ // If determinant is negative it means no solutions.
+ if (determinant >= 0.0f)
+ {
+ // calculate the two roots: (if determinant == 0 then
+ // x1==x2 but let’s disregard that slight optimization)
+ float sqrtD = sqrt(determinant);
+ float r1 = (-b - sqrtD) / (2.0f*a);
+ float r2 = (-b + sqrtD) / (2.0f*a);
+
+ // Sort so x1 <= x2
+ if (r1 > r2)
+ SWAP( float, r1, r2);
+
+ // Get lowest root:
+ if (r1 > 0.0f && r1 < maxR)
+ {
+ *root = r1;
+ return 1;
+ }
+
+ // It is possible that we want x2 - this can happen
+ // if x1 < 0
+ if (r2 > 0.0f && r2 < maxR)
+ {
+ *root = r2;
+ return 1;
+ }
+ }
+ // No (valid) solutions
+ return 0;
+}
+
int SweepingSphereIntersectsTriangleUV(float p1[3], float p2[3], float radius, float v0[3], float v1[3], float v2[3], float *lambda, float *ipoint)
{
float e1[3], e2[3], e3[3], point[3], vel[3], /*dist[3],*/ nor[3], temp[3], bv[3];
- float a, b, c, d, e, x, y, z, t, t0, t1, radius2=radius*radius;
+ float a, b, c, d, e, x, y, z, radius2=radius*radius;
float elen2,edotv,edotbv,nordotv,vel2;
- int embedded_in_plane=0, found_by_sweep=0;
+ float newLambda;
+ int found_by_sweep=0;
VecSubf(e1,v1,v0);
VecSubf(e2,v2,v0);
@@ -3650,44 +3943,41 @@ int SweepingSphereIntersectsTriangleUV(float p1[3], float p2[3], float radius, f
/*---test plane of tri---*/
Crossf(nor,e1,e2);
Normalize(nor);
+
/* flip normal */
if(Inpf(nor,vel)>0.0f) VecMulf(nor,-1.0f);
a=Inpf(p1,nor)-Inpf(v0,nor);
-
nordotv=Inpf(nor,vel);
- if ((nordotv > -0.000001) && (nordotv < 0.000001)) {
- if(fabs(a)>=1.0f)
+ if (fabs(nordotv) < 0.000001)
+ {
+ if(fabs(a)>=radius)
+ {
return 0;
- else{
- embedded_in_plane=1;
- t0=0.0f;
- t1=1.0f;
}
}
- else{
- t0=(radius-a)/nordotv;
- t1=(-radius-a)/nordotv;
- /* make t0<t1 */
- if(t0>t1){b=t1; t1=t0; t0=b;}
+ else
+ {
+ float t0=(-a+radius)/nordotv;
+ float t1=(-a-radius)/nordotv;
+
+ if(t0>t1)
+ SWAP(float, t0, t1);
if(t0>1.0f || t1<0.0f) return 0;
/* clamp to [0,1] */
- t0=(t0<0.0f)?0.0f:((t0>1.0f)?1.0:t0);
- t1=(t1<0.0f)?0.0f:((t1>1.0f)?1.0:t1);
- }
+ CLAMP(t0, 0.0f, 1.0f);
+ CLAMP(t1, 0.0f, 1.0f);
-/*---test inside of tri---*/
- if(embedded_in_plane==0){
+ /*---test inside of tri---*/
/* plane intersection point */
- VecCopyf(point,vel);
- VecMulf(point,t0);
- VecAddf(point,point,p1);
- VecCopyf(temp,nor);
- VecMulf(temp,radius);
- VecSubf(point,point,temp);
+
+ point[0] = p1[0] + vel[0]*t0 - nor[0]*radius;
+ point[1] = p1[1] + vel[1]*t0 - nor[1]*radius;
+ point[2] = p1[2] + vel[2]*t0 - nor[2]*radius;
+
/* is the point in the tri? */
a=Inpf(e1,e1);
@@ -3702,14 +3992,19 @@ int SweepingSphereIntersectsTriangleUV(float p1[3], float p2[3], float radius, f
y=e*a-d*b;
z=x+y-(a*c-b*b);
- if(( ((unsigned int)z)& ~(((unsigned int)x)|((unsigned int)y)) ) & 0x80000000){
+
+ if( z <= 0.0f && (x >= 0.0f && y >= 0.0f))
+ {
+ //( ((unsigned int)z)& ~(((unsigned int)x)|((unsigned int)y)) ) & 0x80000000){
*lambda=t0;
VecCopyf(ipoint,point);
return 1;
}
}
+
*lambda=1.0f;
+
/*---test points---*/
a=vel2=Inpf(vel,vel);
@@ -3717,73 +4012,42 @@ int SweepingSphereIntersectsTriangleUV(float p1[3], float p2[3], float radius, f
VecSubf(temp,p1,v0);
b=2.0f*Inpf(vel,temp);
c=Inpf(temp,temp)-radius2;
- d=b*b-4*a*c;
-
- if(d>=0.0f){
- if(d==0.0f)
- t=-b/2*a;
- else{
- z=sqrt(d);
- x=(-b-z)*0.5/a;
- y=(-b+z)*0.5/a;
- t=x<y?x:y;
- }
- if(t>0.0 && t < *lambda){
- *lambda=t;
- VecCopyf(ipoint,v0);
- found_by_sweep=1;
- }
+ if(getLowestRoot(a, b, c, *lambda, lambda))
+ {
+ VecCopyf(ipoint,v0);
+ found_by_sweep=1;
}
/*v1*/
VecSubf(temp,p1,v1);
b=2.0f*Inpf(vel,temp);
c=Inpf(temp,temp)-radius2;
- d=b*b-4*a*c;
-
- if(d>=0.0f){
- if(d==0.0f)
- t=-b/2*a;
- else{
- z=sqrt(d);
- x=(-b-z)*0.5/a;
- y=(-b+z)*0.5/a;
- t=x<y?x:y;
- }
- if(t>0.0 && t < *lambda){
- *lambda=t;
- VecCopyf(ipoint,v1);
- found_by_sweep=1;
- }
+ if(getLowestRoot(a, b, c, *lambda, lambda))
+ {
+ VecCopyf(ipoint,v1);
+ found_by_sweep=1;
}
+
/*v2*/
VecSubf(temp,p1,v2);
b=2.0f*Inpf(vel,temp);
c=Inpf(temp,temp)-radius2;
- d=b*b-4*a*c;
-
- if(d>=0.0f){
- if(d==0.0f)
- t=-b/2*a;
- else{
- z=sqrt(d);
- x=(-b-z)*0.5/a;
- y=(-b+z)*0.5/a;
- t=x<y?x:y;
- }
- if(t>0.0 && t < *lambda){
- *lambda=t;
- VecCopyf(ipoint,v2);
- found_by_sweep=1;
- }
+ if(getLowestRoot(a, b, c, *lambda, lambda))
+ {
+ VecCopyf(ipoint,v2);
+ found_by_sweep=1;
}
/*---test edges---*/
+ VecSubf(e3,v2,v1); //wasnt yet calculated
+
+
/*e1*/
VecSubf(bv,v0,p1);
+
elen2 = Inpf(e1,e1);
edotv = Inpf(e1,vel);
edotbv = Inpf(e1,bv);
@@ -3791,27 +4055,18 @@ int SweepingSphereIntersectsTriangleUV(float p1[3], float p2[3], float radius, f
a=elen2*(-Inpf(vel,vel))+edotv*edotv;
b=2.0f*(elen2*Inpf(vel,bv)-edotv*edotbv);
c=elen2*(radius2-Inpf(bv,bv))+edotbv*edotbv;
- d=b*b-4*a*c;
- if(d>=0.0f){
- if(d==0.0f)
- t=-b/2*a;
- else{
- z=sqrt(d);
- x=(-b-z)*0.5/a;
- y=(-b+z)*0.5/a;
- t=x<y?x:y;
- }
-
- e=(edotv*t-edotbv)/elen2;
- if((e>=0.0f) && (e<=1.0f)){
- if(t>0.0 && t < *lambda){
- *lambda=t;
- VecCopyf(ipoint,e1);
- VecMulf(ipoint,e);
- VecAddf(ipoint,ipoint,v0);
- found_by_sweep=1;
- }
+ if(getLowestRoot(a, b, c, *lambda, &newLambda))
+ {
+ e=(edotv*newLambda-edotbv)/elen2;
+
+ if(e >= 0.0f && e <= 1.0f)
+ {
+ *lambda = newLambda;
+ VecCopyf(ipoint,e1);
+ VecMulf(ipoint,e);
+ VecAddf(ipoint,ipoint,v0);
+ found_by_sweep=1;
}
}
@@ -3824,32 +4079,27 @@ int SweepingSphereIntersectsTriangleUV(float p1[3], float p2[3], float radius, f
a=elen2*(-Inpf(vel,vel))+edotv*edotv;
b=2.0f*(elen2*Inpf(vel,bv)-edotv*edotbv);
c=elen2*(radius2-Inpf(bv,bv))+edotbv*edotbv;
- d=b*b-4*a*c;
- if(d>=0.0f){
- if(d==0.0f)
- t=-b/2*a;
- else{
- z=sqrt(d);
- x=(-b-z)*0.5/a;
- y=(-b+z)*0.5/a;
- t=x<y?x:y;
- }
- e=(edotv*t-edotbv)/elen2;
-
- if((e>=0.0f) && (e<=1.0f)){
- if(t>0.0 && t < *lambda){
- *lambda=t;
- VecCopyf(ipoint,e2);
- VecMulf(ipoint,e);
- VecAddf(ipoint,ipoint,v0);
- found_by_sweep=1;
- }
+ if(getLowestRoot(a, b, c, *lambda, &newLambda))
+ {
+ e=(edotv*newLambda-edotbv)/elen2;
+
+ if(e >= 0.0f && e <= 1.0f)
+ {
+ *lambda = newLambda;
+ VecCopyf(ipoint,e2);
+ VecMulf(ipoint,e);
+ VecAddf(ipoint,ipoint,v0);
+ found_by_sweep=1;
}
}
/*e3*/
- VecSubf(e3,v2,v1);
+ VecSubf(bv,v0,p1);
+ elen2 = Inpf(e1,e1);
+ edotv = Inpf(e1,vel);
+ edotbv = Inpf(e1,bv);
+
VecSubf(bv,v1,p1);
elen2 = Inpf(e3,e3);
edotv = Inpf(e3,vel);
@@ -3858,30 +4108,22 @@ int SweepingSphereIntersectsTriangleUV(float p1[3], float p2[3], float radius, f
a=elen2*(-Inpf(vel,vel))+edotv*edotv;
b=2.0f*(elen2*Inpf(vel,bv)-edotv*edotbv);
c=elen2*(radius2-Inpf(bv,bv))+edotbv*edotbv;
- d=b*b-4*a*c;
- if(d>=0.0f){
- if(d==0.0f)
- t=-b/2*a;
- else{
- z=sqrt(d);
- x=(-b-z)*0.5/a;
- y=(-b+z)*0.5/a;
- t=x<y?x:y;
- }
- e=(edotv*t-edotbv)/elen2;
-
- if((e>=0.0f) && (e<=1.0f)){
- if(t>0.0 && t < *lambda){
- *lambda=t;
- VecCopyf(ipoint,e3);
- VecMulf(ipoint,e);
- VecAddf(ipoint,ipoint,v1);
- found_by_sweep=1;
- }
+ if(getLowestRoot(a, b, c, *lambda, &newLambda))
+ {
+ e=(edotv*newLambda-edotbv)/elen2;
+
+ if(e >= 0.0f && e <= 1.0f)
+ {
+ *lambda = newLambda;
+ VecCopyf(ipoint,e3);
+ VecMulf(ipoint,e);
+ VecAddf(ipoint,ipoint,v1);
+ found_by_sweep=1;
}
}
+
return found_by_sweep;
}
int AxialLineIntersectsTriangle(int axis, float p1[3], float p2[3], float v0[3], float v1[3], float v2[3], float *lambda)
@@ -3928,6 +4170,74 @@ int AxialLineIntersectsTriangle(int axis, float p1[3], float p2[3], float v0[3],
return 1;
}
+/* Returns the number of point of interests
+ * 0 - lines are colinear
+ * 1 - lines are coplanar, i1 is set to intersection
+ * 2 - i1 and i2 are the nearest points on line 1 (v1, v2) and line 2 (v3, v4) respectively
+ * */
+int LineIntersectLine(float v1[3], float v2[3], float v3[3], float v4[3], float i1[3], float i2[3])
+{
+ float a[3], b[3], c[3], ab[3], cb[3], dir1[3], dir2[3];
+ float d;
+
+ VecSubf(c, v3, v1);
+ VecSubf(a, v2, v1);
+ VecSubf(b, v4, v3);
+
+ VecCopyf(dir1, a);
+ Normalize(dir1);
+ VecCopyf(dir2, b);
+ Normalize(dir2);
+ d = Inpf(dir1, dir2);
+ if (d == 1.0f || d == -1.0f) {
+ /* colinear */
+ return 0;
+ }
+
+ Crossf(ab, a, b);
+ d = Inpf(c, ab);
+
+ /* test if the two lines are coplanar */
+ if (d > -0.000001f && d < 0.000001f) {
+ Crossf(cb, c, b);
+
+ VecMulf(a, Inpf(cb, ab) / Inpf(ab, ab));
+ VecAddf(i1, v1, a);
+ VecCopyf(i2, i1);
+
+ return 1; /* one intersection only */
+ }
+ /* if not */
+ else {
+ float n[3], t[3];
+ float v3t[3], v4t[3];
+ VecSubf(t, v1, v3);
+
+ /* offset between both plane where the lines lies */
+ Crossf(n, a, b);
+ Projf(t, t, n);
+
+ /* for the first line, offset the second line until it is coplanar */
+ VecAddf(v3t, v3, t);
+ VecAddf(v4t, v4, t);
+
+ VecSubf(c, v3t, v1);
+ VecSubf(a, v2, v1);
+ VecSubf(b, v4t, v3);
+
+ Crossf(ab, a, b);
+ Crossf(cb, c, b);
+
+ VecMulf(a, Inpf(cb, ab) / Inpf(ab, ab));
+ VecAddf(i1, v1, a);
+
+ /* for the second line, just substract the offset from the first intersection point */
+ VecSubf(i2, i1, t);
+
+ return 2; /* two nearest points */
+ }
+}
+
int AabbIntersectAabb(float min1[3], float max1[3], float min2[3], float max2[3])
{
return (min1[0]<max2[0] && min1[1]<max2[1] && min1[2]<max2[2] &&
@@ -3950,7 +4260,7 @@ float lambda_cp_line_ex(float p[3], float l1[3], float l2[3], float cp[3])
}
/* little sister we only need to know lambda */
-float lambda_cp_line(float p[3], float l1[3], float l2[3])
+static float lambda_cp_line(float p[3], float l1[3], float l2[3])
{
float h[3],u[3];
VecSubf(u, l2, l1);
@@ -4166,7 +4476,7 @@ void VecfCubicInterpol(float *x1, float *v1, float *x2, float *v2, float t, floa
v[2]= 3*a[2]*t2 + 2*b[2]*t + v1[2];
}
-int point_in_slice(float p[3], float v1[3], float l1[3], float l2[3])
+static int point_in_slice(float p[3], float v1[3], float l1[3], float l2[3])
{
/*
what is a slice ?
@@ -4193,7 +4503,7 @@ but see a 'spat' which is a deformed cube with paired parallel planes needs only
/*adult sister defining the slice planes by the origin and the normal
NOTE |normal| may not be 1 but defining the thickness of the slice*/
-int point_in_slice_as(float p[3],float origin[3],float normal[3])
+static int point_in_slice_as(float p[3],float origin[3],float normal[3])
{
float h,rp[3];
VecSubf(rp,p,origin);
@@ -4203,7 +4513,7 @@ int point_in_slice_as(float p[3],float origin[3],float normal[3])
}
/*mama (knowing the squared lenght of the normal)*/
-int point_in_slice_m(float p[3],float origin[3],float normal[3],float lns)
+static int point_in_slice_m(float p[3],float origin[3],float normal[3],float lns)
{
float h,rp[3];
VecSubf(rp,p,origin);
@@ -4293,3 +4603,80 @@ void LocQuatSizeToMat4(float mat[][4], float loc[3], float quat[4], float size[3
mat[3][1] = loc[1];
mat[3][2] = loc[2];
}
+
+/* Tangents */
+
+/* For normal map tangents we need to detect uv boundaries, and only average
+ * tangents in case the uvs are connected. Alternative would be to store 1
+ * tangent per face rather than 4 per face vertex, but that's not compatible
+ * with games */
+
+
+/* from BKE_mesh.h */
+#define STD_UV_CONNECT_LIMIT 0.0001f
+
+void sum_or_add_vertex_tangent(void *arena, VertexTangent **vtang, float *tang, float *uv)
+{
+ VertexTangent *vt;
+
+ /* find a tangent with connected uvs */
+ for(vt= *vtang; vt; vt=vt->next) {
+ if(fabs(uv[0]-vt->uv[0]) < STD_UV_CONNECT_LIMIT && fabs(uv[1]-vt->uv[1]) < STD_UV_CONNECT_LIMIT) {
+ VecAddf(vt->tang, vt->tang, tang);
+ return;
+ }
+ }
+
+ /* if not found, append a new one */
+ vt= BLI_memarena_alloc((MemArena *)arena, sizeof(VertexTangent));
+ VecCopyf(vt->tang, tang);
+ vt->uv[0]= uv[0];
+ vt->uv[1]= uv[1];
+
+ if(*vtang)
+ vt->next= *vtang;
+ *vtang= vt;
+}
+
+float *find_vertex_tangent(VertexTangent *vtang, float *uv)
+{
+ VertexTangent *vt;
+ static float nulltang[3] = {0.0f, 0.0f, 0.0f};
+
+ for(vt= vtang; vt; vt=vt->next)
+ if(fabs(uv[0]-vt->uv[0]) < STD_UV_CONNECT_LIMIT && fabs(uv[1]-vt->uv[1]) < STD_UV_CONNECT_LIMIT)
+ return vt->tang;
+
+ return nulltang; /* shouldn't happen, except for nan or so */
+}
+
+void tangent_from_uv(float *uv1, float *uv2, float *uv3, float *co1, float *co2, float *co3, float *n, float *tang)
+{
+ float tangv[3], ct[3], e1[3], e2[3], s1, t1, s2, t2, det;
+
+ s1= uv2[0] - uv1[0];
+ s2= uv3[0] - uv1[0];
+ t1= uv2[1] - uv1[1];
+ t2= uv3[1] - uv1[1];
+ det= 1.0f / (s1 * t2 - s2 * t1);
+
+ /* normals in render are inversed... */
+ VecSubf(e1, co1, co2);
+ VecSubf(e2, co1, co3);
+ tang[0] = (t2*e1[0] - t1*e2[0])*det;
+ tang[1] = (t2*e1[1] - t1*e2[1])*det;
+ tang[2] = (t2*e1[2] - t1*e2[2])*det;
+ tangv[0] = (s1*e2[0] - s2*e1[0])*det;
+ tangv[1] = (s1*e2[1] - s2*e1[1])*det;
+ tangv[2] = (s1*e2[2] - s2*e1[2])*det;
+ Crossf(ct, tang, tangv);
+
+ /* check flip */
+ if ((ct[0]*n[0] + ct[1]*n[1] + ct[2]*n[2]) < 0.0f)
+ VecMulf(tang, -1.0f);
+}
+
+/* used for zoom values*/
+float power_of_2(float val) {
+ return pow(2, ceil(log(val) / log(2)));
+}
diff --git a/source/blender/blenlib/intern/boxpack2d.c b/source/blender/blenlib/intern/boxpack2d.c
index 21810613c7f..db7bae8a91d 100644
--- a/source/blender/blenlib/intern/boxpack2d.c
+++ b/source/blender/blenlib/intern/boxpack2d.c
@@ -42,6 +42,8 @@
#define TRF 2
#define TLF 4
#define BRF 8
+#define CORNERFLAGS (BLF|TRF|TLF|BRF)
+
#define BL 0
#define TR 1
#define TL 2
@@ -130,7 +132,7 @@ static int vertex_sort(const void *p1, const void *p2)
* 'box->index' is not used at all, the only reason its there
* is that the box array is sorted by area and programs need to be able
* to have some way of writing the boxes back to the original data.
- * len - the number of boxes in teh array.
+ * len - the number of boxes in the array.
* tot_width and tot_height are set so you can normalize the data.
* */
void boxPack2D(boxPack *boxarray, int len, float *tot_width, float *tot_height)
@@ -159,7 +161,7 @@ void boxPack2D(boxPack *boxarray, int len, float *tot_width, float *tot_height)
vert->blb = vert->brb = vert->tlb =\
vert->isect_cache[0] = vert->isect_cache[1] =\
vert->isect_cache[2] = vert->isect_cache[3] = NULL;
- vert->free = 15 &~ TRF;
+ vert->free = CORNERFLAGS &~ TRF;
vert->trb = box;
vert->index = i; i++;
box->v[BL] = vert; vert++;
@@ -167,7 +169,7 @@ void boxPack2D(boxPack *boxarray, int len, float *tot_width, float *tot_height)
vert->trb= vert->brb = vert->tlb =\
vert->isect_cache[0] = vert->isect_cache[1] =\
vert->isect_cache[2] = vert->isect_cache[3] = NULL;
- vert->free = 15 &~ BLF;
+ vert->free = CORNERFLAGS &~ BLF;
vert->blb = box;
vert->index = i; i++;
box->v[TR] = vert; vert++;
@@ -175,7 +177,7 @@ void boxPack2D(boxPack *boxarray, int len, float *tot_width, float *tot_height)
vert->trb = vert->blb = vert->tlb =\
vert->isect_cache[0] = vert->isect_cache[1] =\
vert->isect_cache[2] = vert->isect_cache[3] = NULL;
- vert->free = 15 &~ BRF;
+ vert->free = CORNERFLAGS &~ BRF;
vert->brb = box;
vert->index = i; i++;
box->v[TL] = vert; vert++;
@@ -183,7 +185,7 @@ void boxPack2D(boxPack *boxarray, int len, float *tot_width, float *tot_height)
vert->trb = vert->blb = vert->brb =\
vert->isect_cache[0] = vert->isect_cache[1] =\
vert->isect_cache[2] = vert->isect_cache[3] = NULL;
- vert->free = 15 &~ TLF;
+ vert->free = CORNERFLAGS &~ TLF;
vert->tlb = box;
vert->index = i; i++;
box->v[BR] = vert; vert++;
diff --git a/source/blender/blenlib/intern/bpath.c b/source/blender/blenlib/intern/bpath.c
index 17d428a6b10..16eb3ff3865 100644
--- a/source/blender/blenlib/intern/bpath.c
+++ b/source/blender/blenlib/intern/bpath.c
@@ -28,11 +28,13 @@
#include "BLI_bpath.h"
#include "BKE_global.h"
+//XXX #include "BIF_screen.h" /* only for wait cursor */
#include "DNA_ID.h" /* Library */
#include "DNA_vfont_types.h"
#include "DNA_image_types.h"
#include "DNA_sound_types.h"
#include "DNA_scene_types.h" /* to get the current frame */
+#include "DNA_sequence_types.h"
#include <stdlib.h>
#include <string.h>
@@ -40,6 +42,10 @@
#include "BKE_image.h" /* so we can check the image's type */
#include "BKE_utildefines.h"
+#include "MEM_guardedalloc.h"
+
+/* for sequence */
+//XXX #include "BSE_sequence.h"
/* for writing to a textblock */
#include "BKE_text.h"
@@ -66,39 +72,66 @@
#define FILE_MAX 240
-
/* TODO - BPATH_PLUGIN, BPATH_SEQ */
enum BPathTypes {
BPATH_IMAGE = 0,
BPATH_SOUND,
BPATH_FONT,
BPATH_LIB,
+ BPATH_SEQ,
BPATH_DONE
};
-
void BLI_bpathIterator_init( struct BPathIterator *bpi ) {
bpi->type = BPATH_IMAGE;
bpi->data = NULL;
+
+ bpi->getpath_callback = NULL;
+ bpi->setpath_callback = NULL;
+
+ /* Sequencer spesific */
+ bpi->seqdata.totseq = 0;
+ bpi->seqdata.seq = 0;
+ bpi->seqdata.seqar = NULL;
+ bpi->seqdata.scene = NULL;
+
BLI_bpathIterator_step(bpi);
}
-char* BLI_bpathIterator_getPath( struct BPathIterator *bpi) {
- return bpi->path;
+void BLI_bpathIterator_free( struct BPathIterator *bpi ) {
+ if (bpi->seqdata.seqar)
+ MEM_freeN((void *)bpi->seqdata.seqar);
+ bpi->seqdata.seqar = NULL;
+ bpi->seqdata.scene = NULL;
}
-void BLI_bpathIterator_copyPathExpanded( struct BPathIterator *bpi, char *path_expanded) {
- char *filepath, *libpath;
+
+void BLI_bpathIterator_getPath( struct BPathIterator *bpi, char *path) {
+ if (bpi->getpath_callback) {
+ bpi->getpath_callback( bpi, path );
+ } else {
+ strcpy(path, bpi->path); /* warning, we assume 'path' are long enough */
+ }
+}
+
+void BLI_bpathIterator_setPath( struct BPathIterator *bpi, char *path) {
+ if (bpi->setpath_callback) {
+ bpi->setpath_callback( bpi, path );
+ } else {
+ strcpy(bpi->path, path); /* warning, we assume 'path' are long enough */
+ }
+}
+
+void BLI_bpathIterator_getPathExpanded( struct BPathIterator *bpi, char *path_expanded) {
+ char *libpath;
- filepath = BLI_bpathIterator_getPath(bpi);
+ BLI_bpathIterator_getPath(bpi, path_expanded);
libpath = BLI_bpathIterator_getLib(bpi);
- BLI_strncpy(path_expanded, filepath, FILE_MAXDIR*2);
-
if (libpath) { /* check the files location relative to its library path */
- BLI_convertstringcode(path_expanded, libpath, G.scene->r.cfra);
+ BLI_convertstringcode(path_expanded, libpath);
} else { /* local data, use the blend files path */
- BLI_convertstringcode(path_expanded, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(path_expanded, G.sce);
}
}
char* BLI_bpathIterator_getLib( struct BPathIterator *bpi) {
@@ -115,7 +148,7 @@ int BLI_bpathIterator_getPathMaxLen( struct BPathIterator *bpi) {
}
/* gets the first or the next image that has a path - not a viewer node or generated image */
-static struct Image *ima_getpath__internal(struct Image *ima, int step_next) {
+static struct Image *ima_stepdata__internal(struct Image *ima, int step_next) {
if (ima==NULL)
return NULL;
@@ -131,7 +164,7 @@ static struct Image *ima_getpath__internal(struct Image *ima, int step_next) {
return ima;
}
-static struct VFont *vf_getpath__internal(struct VFont *vf, int step_next) {
+static struct VFont *vf_stepdata__internal(struct VFont *vf, int step_next) {
if (vf==NULL)
return NULL;
@@ -149,7 +182,7 @@ static struct VFont *vf_getpath__internal(struct VFont *vf, int step_next) {
return vf;
}
-static struct bSound *snd_getpath__internal(struct bSound *snd, int step_next) {
+static struct bSound *snd_stepdata__internal(struct bSound *snd, int step_next) {
if (snd==NULL)
return NULL;
@@ -167,13 +200,117 @@ static struct bSound *snd_getpath__internal(struct bSound *snd, int step_next) {
return snd;
}
+static struct Sequence *seq_stepdata__internal(struct BPathIterator *bpi, int step_next) {
+ Sequence *seq;
+
+ /* Initializing */
+ if (bpi->seqdata.scene==NULL) {
+ bpi->seqdata.scene= G.main->scene.first;
+ }
+
+ if (step_next) {
+ bpi->seqdata.seq++;
+ }
+
+ while (bpi->seqdata.scene) {
+
+ if (bpi->seqdata.scene->ed) {
+ if (bpi->seqdata.seqar == NULL) {
+ /* allocate the sequencer array */
+ build_seqar( &(((Editing *)bpi->seqdata.scene->ed)->seqbase), &bpi->seqdata.seqar, &bpi->seqdata.totseq);
+ bpi->seqdata.seq = 0;
+ }
+
+ if (bpi->seqdata.seq >= bpi->seqdata.totseq) {
+ seq = NULL;
+ } else {
+ seq = bpi->seqdata.seqar[bpi->seqdata.seq];
+ while (!SEQ_HAS_PATH(seq)) {
+ bpi->seqdata.seq++;
+ if (bpi->seqdata.seq >= bpi->seqdata.totseq) {
+ seq = NULL;
+ break;
+ }
+ seq = bpi->seqdata.seqar[bpi->seqdata.seq];
+ }
+ }
+ if (seq) {
+ return seq;
+ } else {
+ /* keep looking through the next scene, reallocate seq array */
+ if (bpi->seqdata.seqar) {
+ MEM_freeN((void *)bpi->seqdata.seqar);
+ bpi->seqdata.seqar = NULL;
+ }
+ bpi->seqdata.scene = bpi->seqdata.scene->id.next;
+ }
+ } else {
+ /* no seq data in this scene, next */
+ bpi->seqdata.scene = bpi->seqdata.scene->id.next;
+ }
+ }
+
+ return NULL;
+}
+
+static void seq_getpath(struct BPathIterator *bpi, char *path) {
+ Sequence *seq = (Sequence *)bpi->data;
+
+
+ path[0] = '\0'; /* incase we cant get the path */
+ if (seq==NULL) return;
+ if (SEQ_HAS_PATH(seq)) {
+ if (seq->type == SEQ_IMAGE || seq->type == SEQ_MOVIE) {
+ BLI_strncpy(path, seq->strip->dir, FILE_MAX);
+ BLI_add_slash(path); /* incase its missing */
+ if (seq->strip->stripdata) { /* should always be true! */
+ /* Using the first image is weak for image sequences */
+ strcat(path, seq->strip->stripdata->name);
+ }
+ } else {
+ /* simple case */
+ BLI_strncpy(seq->strip->dir, path, sizeof(seq->strip->dir));
+ }
+ }
+}
+
+static void seq_setpath(struct BPathIterator *bpi, char *path) {
+ Sequence *seq = (Sequence *)bpi->data;
+ if (seq==NULL) return;
+
+ if (SEQ_HAS_PATH(seq)) {
+ if (seq->type == SEQ_IMAGE || seq->type == SEQ_MOVIE) {
+ BLI_split_dirfile_basic(path, seq->strip->dir, seq->strip->stripdata->name);
+ } else {
+ /* simple case */
+ BLI_strncpy(seq->strip->dir, path, sizeof(seq->strip->dir));
+ }
+ }
+}
+
+static void bpi_type_step__internal( struct BPathIterator *bpi) {
+ bpi->type++; /* advance to the next type */
+ bpi->data = NULL;
+
+ switch (bpi->type) {
+ case BPATH_SEQ:
+ bpi->getpath_callback = seq_getpath;
+ bpi->setpath_callback = seq_setpath;
+ break;
+ default:
+ bpi->getpath_callback = NULL;
+ bpi->setpath_callback = NULL;
+ break;
+ }
+}
+
void BLI_bpathIterator_step( struct BPathIterator *bpi) {
while (bpi->type != BPATH_DONE) {
if ((bpi->type) == BPATH_IMAGE) {
/*if (bpi->data) bpi->data = ((ID *)bpi->data)->next;*/
- if (bpi->data) bpi->data = ima_getpath__internal( (Image *)bpi->data, 1 ); /* must skip images that have no path */
- else bpi->data = ima_getpath__internal(G.main->image.first, 0);
+ if (bpi->data) bpi->data = ima_stepdata__internal( (Image *)bpi->data, 1 ); /* must skip images that have no path */
+ else bpi->data = ima_stepdata__internal(G.main->image.first, 0);
if (bpi->data) {
/* get the path info from this datatype */
@@ -188,13 +325,13 @@ void BLI_bpathIterator_step( struct BPathIterator *bpi) {
break;
} else {
- bpi->type+=1; /* advance to the next type */
+ bpi_type_step__internal(bpi);
}
} else if ((bpi->type) == BPATH_SOUND) {
- if (bpi->data) bpi->data = snd_getpath__internal( (bSound *)bpi->data, 1 ); /* must skip images that have no path */
- else bpi->data = snd_getpath__internal(G.main->sound.first, 0);
+ if (bpi->data) bpi->data = snd_stepdata__internal( (bSound *)bpi->data, 1 ); /* must skip images that have no path */
+ else bpi->data = snd_stepdata__internal(G.main->sound.first, 0);
if (bpi->data) {
/* get the path info from this datatype */
@@ -208,14 +345,14 @@ void BLI_bpathIterator_step( struct BPathIterator *bpi) {
/* we are done, advancing to the next item, this type worked fine */
break;
} else {
- bpi->type+=1; /* advance to the next type */
+ bpi_type_step__internal(bpi);
}
} else if ((bpi->type) == BPATH_FONT) {
- if (bpi->data) bpi->data = vf_getpath__internal( (VFont *)bpi->data, 1 );
- else bpi->data = vf_getpath__internal( G.main->vfont.first, 0 );
+ if (bpi->data) bpi->data = vf_stepdata__internal( (VFont *)bpi->data, 1 );
+ else bpi->data = vf_stepdata__internal( G.main->vfont.first, 0 );
if (bpi->data) {
/* get the path info from this datatype */
@@ -229,12 +366,10 @@ void BLI_bpathIterator_step( struct BPathIterator *bpi) {
/* we are done, advancing to the next item, this type worked fine */
break;
} else {
- bpi->type+=1; /* advance to the next type */
+ bpi_type_step__internal(bpi);
}
-
} else if ((bpi->type) == BPATH_LIB) {
-
if (bpi->data) bpi->data = ((ID *)bpi->data)->next;
else bpi->data = G.main->library.first;
@@ -250,7 +385,19 @@ void BLI_bpathIterator_step( struct BPathIterator *bpi) {
/* we are done, advancing to the next item, this type worked fine */
break;
} else {
- bpi->type+=1; /* advance to the next type */
+ bpi_type_step__internal(bpi);
+ }
+ } else if ((bpi->type) == BPATH_SEQ) {
+ if (bpi->data) bpi->data = seq_stepdata__internal( bpi, 1 );
+ else bpi->data = seq_stepdata__internal( bpi, 0 );
+ if (bpi->data) {
+ Sequence *seq = (Sequence *)bpi->data;
+ bpi->lib = NULL;
+ bpi->name = seq->name+2;
+ bpi->len = sizeof(seq->strip->stripdata->name);
+ break;
+ } else {
+ bpi_type_step__internal(bpi);
}
}
}
@@ -279,6 +426,9 @@ static void bpathToText(Text *btxt, struct BPathIterator *bpi)
case BPATH_LIB:
txt_insert_buf( btxt, "Library \"" );
break;
+ case BPATH_SEQ:
+ txt_insert_buf( btxt, "Sequence \"" );
+ break;
default:
txt_insert_buf( btxt, "Unknown \"" );
break;
@@ -291,7 +441,7 @@ static void bpathToText(Text *btxt, struct BPathIterator *bpi)
}
txt_insert_buf( btxt, "\" " );
- BLI_bpathIterator_copyPathExpanded(bpi, path_expanded);
+ BLI_bpathIterator_getPathExpanded(bpi, path_expanded);
txt_insert_buf( btxt, path_expanded );
txt_insert_buf( btxt, "\n" );
@@ -299,74 +449,148 @@ static void bpathToText(Text *btxt, struct BPathIterator *bpi)
}
/* high level function */
-Text *checkMissingFiles(void) {
+void checkMissingFiles( char *txtname ) {
Text *btxt = NULL;
struct BPathIterator bpi;
/* be sure there is low chance of the path being too short */
char filepath_expanded[FILE_MAXDIR*2];
- char *filepath, *libpath;
- int files_missing = 0;
BLI_bpathIterator_init(&bpi);
while (!BLI_bpathIterator_isDone(&bpi)) {
- filepath = BLI_bpathIterator_getPath(&bpi);
- libpath = BLI_bpathIterator_getLib(&bpi);
-
- BLI_bpathIterator_copyPathExpanded( &bpi, filepath_expanded );
+ BLI_bpathIterator_getPathExpanded( &bpi, filepath_expanded );
if (!BLI_exists(filepath_expanded)) {
- if (!btxt)
- btxt = add_empty_text( "missing_files.txt" );
-
+ if (!btxt) {
+ btxt = add_empty_text( "missing_files.log" );
+ if (txtname) {
+ BLI_strncpy(txtname, btxt->id.name+2, 24);
+ }
+ }
bpathToText(btxt, &bpi);
- files_missing = 1;
}
BLI_bpathIterator_step(&bpi);
}
- return btxt;
+ BLI_bpathIterator_free(&bpi);
}
/* dont log any errors at the moment, should probably do this */
-void makeFilesRelative(int *tot, int *changed, int *failed, int *linked) {
+void makeFilesRelative(char *txtname, int *tot, int *changed, int *failed, int *linked) {
struct BPathIterator bpi;
- char *filepath, *libpath;
+ char filepath[FILE_MAX], *libpath;
/* be sure there is low chance of the path being too short */
char filepath_relative[(FILE_MAXDIR * 2) + FILE_MAXFILE];
+ Text *btxt = NULL;
+
*tot = *changed = *failed = *linked = 0;
BLI_bpathIterator_init(&bpi);
while (!BLI_bpathIterator_isDone(&bpi)) {
- filepath = BLI_bpathIterator_getPath(&bpi);
+ BLI_bpathIterator_getPath(&bpi, filepath);
libpath = BLI_bpathIterator_getLib(&bpi);
if(strncmp(filepath, "//", 2)) {
- if (libpath) { /* cant make relative if we are kibrary - TODO, LOG THIS */
+ if (libpath) { /* cant make relative if we are library - TODO, LOG THIS */
(*linked)++;
} else { /* local data, use the blend files path */
BLI_strncpy(filepath_relative, filepath, sizeof(filepath_relative));
+ /* Important BLI_cleanup_dir runs before the path is made relative
+ * because it wont work for paths that start with "//../" */
+ BLI_cleanup_file(G.sce, filepath_relative); /* fix any /foo/../foo/ */
BLI_makestringcode(G.sce, filepath_relative);
- if (BLI_bpathIterator_getPathMaxLen(&bpi) < strlen(filepath_relative)) {
+ /* be safe and check the length */
+ if (BLI_bpathIterator_getPathMaxLen(&bpi) <= strlen(filepath_relative)) {
+ if (!btxt) {
+ btxt = add_empty_text( "missing_no_rel.log" );
+ if (txtname) {
+ BLI_strncpy(txtname, btxt->id.name+2, 24);
+ }
+ }
+ bpathToText(btxt, &bpi);
(*failed)++;
} else {
- /* safe to to check the length */
if(strncmp(filepath_relative, "//", 2)==0) {
- strcpy(filepath, filepath_relative);
+ BLI_bpathIterator_setPath(&bpi, filepath_relative);
(*changed)++;
} else {
+ if (!btxt) {
+ btxt = add_empty_text( "missing_no_rel.log" );
+ if (txtname) {
+ BLI_strncpy(txtname, btxt->id.name+2, 24);
+ }
+ }
+ bpathToText(btxt, &bpi);
(*failed)++;
}
}
}
}
+ BLI_bpathIterator_step(&bpi);
+ (*tot)++;
+ }
+ BLI_bpathIterator_free(&bpi);
+}
+
+/* dont log any errors at the moment, should probably do this -
+ * Verry similar to makeFilesRelative - keep in sync! */
+void makeFilesAbsolute(char *txtname, int *tot, int *changed, int *failed, int *linked) {
+ struct BPathIterator bpi;
+ char filepath[FILE_MAX], *libpath;
+
+ /* be sure there is low chance of the path being too short */
+ char filepath_absolute[(FILE_MAXDIR * 2) + FILE_MAXFILE];
+
+ Text *btxt = NULL;
+
+ *tot = *changed = *failed = *linked = 0;
+
+ BLI_bpathIterator_init(&bpi);
+ while (!BLI_bpathIterator_isDone(&bpi)) {
+ BLI_bpathIterator_getPath(&bpi, filepath);
+ libpath = BLI_bpathIterator_getLib(&bpi);
+ if(strncmp(filepath, "//", 2)==0) {
+ if (libpath) { /* cant make absolute if we are library - TODO, LOG THIS */
+ (*linked)++;
+ } else { /* get the expanded path and check it is relative or too long */
+ BLI_bpathIterator_getPathExpanded( &bpi, filepath_absolute );
+ BLI_cleanup_file(G.sce, filepath_absolute); /* fix any /foo/../foo/ */
+ /* to be safe, check the length */
+ if (BLI_bpathIterator_getPathMaxLen(&bpi) <= strlen(filepath_absolute)) {
+ if (!btxt) {
+ btxt = add_empty_text( "missing_no_abs.log" );
+ if (txtname) {
+ BLI_strncpy(txtname, btxt->id.name+2, 24);
+ }
+ }
+ bpathToText(btxt, &bpi);
+ (*failed)++;
+ } else {
+ if(strncmp(filepath_absolute, "//", 2)) {
+ BLI_bpathIterator_setPath(&bpi, filepath_absolute);
+ (*changed)++;
+ } else {
+ if (!btxt) {
+ btxt = add_empty_text( "missing_no_abs.log" );
+ if (txtname) {
+ BLI_strncpy(txtname, btxt->id.name+2, 24);
+ }
+ }
+ bpathToText(btxt, &bpi);
+ (*failed)++;
+ }
+ }
+ }
+ }
BLI_bpathIterator_step(&bpi);
(*tot)++;
}
+ BLI_bpathIterator_free(&bpi);
}
+
/* find this file recursively, use the biggest file so thumbnails dont get used by mistake
- dir: subdir to search
- filename: set this filename
@@ -377,14 +601,11 @@ static int findFileRecursive(char *filename_new, const char *dirname, const char
{
/* file searching stuff */
DIR *dir;
- int file = 0;
struct dirent *de;
struct stat status;
char path[FILE_MAX];
int size;
- printf("DIR %s\n", dirname);
-
dir = opendir(dirname);
if (dir==0)
@@ -406,14 +627,10 @@ static int findFileRecursive(char *filename_new, const char *dirname, const char
if (S_ISREG(status.st_mode)) { /* is file */
if (strncmp(filename, de->d_name, FILE_MAX)==0) { /* name matches */
/* open the file to read its size */
- file = open(path, O_BINARY|O_RDONLY);
- if (file >=0 ) {
- size = BLI_filesize(file);
- if (size > *filesize) { /* find the biggest file */
- *filesize = size;
- BLI_strncpy(filename_new, path, FILE_MAX);
- }
- close(file);
+ size = BLI_filepathsize(path);
+ if ((size > 0) && (size > *filesize)) { /* find the biggest file */
+ *filesize = size;
+ BLI_strncpy(filename_new, path, FILE_MAX);
}
}
} else if (S_ISDIR(status.st_mode)) { /* is subdir */
@@ -434,28 +651,35 @@ void findMissingFiles(char *str) {
/* be sure there is low chance of the path being too short */
char filepath_expanded[FILE_MAXDIR*2];
- char *filepath, *libpath;
+ char filepath[FILE_MAX], *libpath;
int filesize, recur_depth;
- char dirname[FILE_MAX], filename[FILE_MAX], filename_new[FILE_MAX], dummyname[FILE_MAX];
+ char dirname[FILE_MAX], filename[FILE_MAX], filename_new[FILE_MAX];
+
+ //XXX waitcursor( 1 );
- BLI_split_dirfile(str, dirname, dummyname);
+ BLI_split_dirfile_basic(str, dirname, NULL);
BLI_bpathIterator_init(&bpi);
while (!BLI_bpathIterator_isDone(&bpi)) {
- filepath = BLI_bpathIterator_getPath(&bpi);
+ BLI_bpathIterator_getPath(&bpi, filepath);
libpath = BLI_bpathIterator_getLib(&bpi);
+ /* Check if esc was pressed because searching files can be slow */
+ /*XXX if (blender_test_break()) {
+ break;
+ }*/
+
if (libpath==NULL) {
- BLI_bpathIterator_copyPathExpanded( &bpi, filepath_expanded );
+ BLI_bpathIterator_getPathExpanded( &bpi, filepath_expanded );
if (!BLI_exists(filepath_expanded)) {
/* can the dir be opened? */
filesize = -1;
recur_depth = 0;
- BLI_split_dirfile(filepath, dummyname, filename); /* the file to find */
+ BLI_split_dirfile_basic(filepath, NULL, filename); /* the file to find */
findFileRecursive(filename_new, dirname, filename, &filesize, &recur_depth);
if (filesize == -1) { /* could not open dir */
@@ -472,11 +696,14 @@ void findMissingFiles(char *str) {
if (G.relbase_valid)
BLI_makestringcode(G.sce, filename_new);
- strcpy( BLI_bpathIterator_getPath( &bpi ), filename_new );
+ BLI_bpathIterator_setPath( &bpi, filename_new );
}
}
}
}
BLI_bpathIterator_step(&bpi);
}
+ BLI_bpathIterator_free(&bpi);
+
+ //XXX waitcursor( 0 );
}
diff --git a/source/blender/blenlib/intern/dynlib.c b/source/blender/blenlib/intern/dynlib.c
index c4692995f20..858aa6e60bf 100644
--- a/source/blender/blenlib/intern/dynlib.c
+++ b/source/blender/blenlib/intern/dynlib.c
@@ -77,12 +77,9 @@ char *PIL_dynlib_get_error_as_string(PILdynlib* lib) {
int err;
/* if lib is NULL reset the last error code */
- if (!lib) {
- SetLastError(ERROR_SUCCESS);
- return NULL;
- }
-
err= GetLastError();
+ if (!lib) SetLastError(ERROR_SUCCESS);
+
if (err) {
static char buf[1024];
@@ -96,7 +93,7 @@ char *PIL_dynlib_get_error_as_string(PILdynlib* lib) {
return buf;
}
- return NULL;
+ return err;
}
void PIL_dynlib_close(PILdynlib *lib) {
diff --git a/source/blender/blenlib/intern/edgehash.c b/source/blender/blenlib/intern/edgehash.c
index 6aa0ded63b9..603c85655d7 100644
--- a/source/blender/blenlib/intern/edgehash.c
+++ b/source/blender/blenlib/intern/edgehash.c
@@ -77,8 +77,12 @@ void BLI_edgehash_insert(EdgeHash *eh, int v0, int v1, void *val) {
unsigned int hash;
Entry *e= malloc(sizeof(*e));
- if (v1<v0) v0 ^= v1 ^= v0 ^= v1;
- hash = EDGEHASH(v0,v1)%eh->nbuckets;
+ if (v1<v0) {
+ v0 ^= v1;
+ v1 ^= v0;
+ v0 ^= v1;
+ }
+ hash = EDGEHASH(v0,v1)%eh->nbuckets;
e->v0 = v0;
e->v1 = v1;
@@ -114,7 +118,11 @@ void** BLI_edgehash_lookup_p(EdgeHash *eh, int v0, int v1) {
unsigned int hash;
Entry *e;
- if (v1<v0) v0 ^= v1 ^= v0 ^= v1;
+ if (v1<v0) {
+ v0 ^= v1;
+ v1 ^= v0;
+ v0 ^= v1;
+ }
hash = EDGEHASH(v0,v1)%eh->nbuckets;
for (e= eh->buckets[hash]; e; e= e->next)
if (v0==e->v0 && v1==e->v1)
@@ -200,6 +208,11 @@ void *BLI_edgehashIterator_getValue(EdgeHashIterator *ehi) {
return ehi->curEntry?ehi->curEntry->val:NULL;
}
+void BLI_edgehashIterator_setValue(EdgeHashIterator *ehi, void *val) {
+ if(ehi->curEntry)
+ ehi->curEntry->val= val;
+}
+
void BLI_edgehashIterator_step(EdgeHashIterator *ehi) {
if (ehi->curEntry) {
ehi->curEntry= ehi->curEntry->next;
diff --git a/source/blender/blenlib/intern/fileops.c b/source/blender/blenlib/intern/fileops.c
index f55cd05e53e..a64185a896a 100644
--- a/source/blender/blenlib/intern/fileops.c
+++ b/source/blender/blenlib/intern/fileops.c
@@ -6,7 +6,7 @@
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
+ * of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -56,6 +56,8 @@
#include "BKE_utildefines.h"
#include <errno.h>
+#include "BLO_sys_types.h" // for intptr_t support
+
/* implementations: */
char *first_slash(char *string) {
char *ffslash, *fbslash;
@@ -66,11 +68,11 @@ char *first_slash(char *string) {
if (!ffslash) return fbslash;
else if (!fbslash) return ffslash;
- if ((long)ffslash < (long)fbslash) return ffslash;
+ if ((intptr_t)ffslash < (intptr_t)fbslash) return ffslash;
else return fbslash;
}
-char *BLI_last_slash(char *string) {
+char *BLI_last_slash(const char *string) {
char *lfslash, *lbslash;
lfslash= strrchr(string, '/');
@@ -79,10 +81,43 @@ char *BLI_last_slash(char *string) {
if (!lfslash) return lbslash;
else if (!lbslash) return lfslash;
- if ((long)lfslash < (long)lbslash) return lbslash;
+ if ((intptr_t)lfslash < (intptr_t)lbslash) return lbslash;
else return lfslash;
}
+/* adds a slash if there isnt one there alredy */
+void BLI_add_slash(char *string) {
+ int len = strlen(string);
+#ifdef WIN32
+ if (len==0 || string[len-1]!='\\') {
+ string[len] = '\\';
+ string[len+1] = '\0';
+ }
+#else
+ if (len==0 || string[len-1]!='/') {
+ string[len] = '/';
+ string[len+1] = '\0';
+ }
+#endif
+}
+
+/* removes a slash if there is one */
+void BLI_del_slash(char *string) {
+ int len = strlen(string);
+ while (len) {
+#ifdef WIN32
+ if (string[len-1]=='\\') {
+#else
+ if (string[len-1]=='/') {
+#endif
+ string[len-1] = '\0';
+ len--;
+ } else {
+ break;
+ }
+ }
+}
+
/* gzip the file in from and write it to "to".
return -1 if zlib fails, -2 if the originating file does not exist
note: will remove the "from" file
@@ -131,6 +166,23 @@ int BLI_is_writable(char *filename)
}
}
+int BLI_touch(const char *file)
+{
+ FILE *f = fopen(file,"r+b");
+ if (f != NULL) {
+ char c = getc(f);
+ rewind(f);
+ putc(c,f);
+ } else {
+ f = fopen(file,"wb");
+ }
+ if (f) {
+ fclose(f);
+ return 1;
+ }
+ return 0;
+}
+
#ifdef WIN32
static char str[MAXPATHLEN+12];
@@ -152,12 +204,6 @@ int BLI_delete(char *file, int dir, int recursive) {
return err;
}
-int BLI_touch(char *file) {
- callLocalErrorCallBack("Touching files is unsupported on Windows");
-
- return 1;
-}
-
int BLI_move(char *file, char *to) {
int err;
@@ -214,12 +260,6 @@ int BLI_link(char *file, char *to) {
return 1;
}
-int BLI_backup(char *file, char *from, char *to) {
- callLocalErrorCallBack("Backing up files is unsupported on Windows");
-
- return 1;
-}
-
int BLI_exists(char *file) {
return (GetFileAttributes(file) != 0xFFFFFFFF);
}
@@ -257,7 +297,8 @@ void BLI_recurdir_fileops(char *dirname) {
int BLI_rename(char *from, char *to) {
if (!BLI_exists(from)) return 0;
- if (BLI_exists(to))
+ /* make sure the filenames are different (case insensitive) before removing */
+ if (BLI_exists(to) && BLI_strcasecmp(from, to))
if(BLI_delete(to, 0, 0)) return 1;
return rename(from, to);
@@ -278,26 +319,21 @@ int BLI_delete(char *file, int dir, int recursive)
printf("Error: not deleted file %s because of quote!\n", file);
}
else {
- if (recursive) sprintf(str, "/bin/rm -rf \"%s\"", file);
- else if (dir) sprintf(str, "/bin/rmdir \"%s\"", file);
- else sprintf(str, "/bin/rm -f \"%s\"", file);
-
- return system(str);
+ if (recursive) {
+ sprintf(str, "/bin/rm -rf \"%s\"", file);
+ return system(str);
+ }
+ else if (dir) {
+ sprintf(str, "/bin/rmdir \"%s\"", file);
+ return system(str);
+ }
+ else {
+ return remove(file); //sprintf(str, "/bin/rm -f \"%s\"", file);
+ }
}
return -1;
}
-int BLI_touch(char *file)
-{
-
- if( BLI_exists("/bin/touch") )
- sprintf(str, "/bin/touch %s", file);
- else
- sprintf(str, "/usr/bin/touch %s", file);
-
- return system(str);
-}
-
int BLI_move(char *file, char *to) {
sprintf(str, "/bin/mv -f \"%s\" \"%s\"", file, to);
@@ -316,12 +352,6 @@ int BLI_link(char *file, char *to) {
return system(str);
}
-int BLI_backup(char *file, char *from, char *to) {
- sprintf(str, "/bin/su root -c 'cd %s; /bin/tar cf - \"%s\" | (/bin/cd %s; /bin/tar xf -)'", from, file, to);
-
- return system(str);
-}
-
int BLI_exists(char *file) {
return BLI_exist(file);
}
diff --git a/source/blender/blenlib/intern/freetypefont.c b/source/blender/blenlib/intern/freetypefont.c
index f788f9cf255..2c114ea6971 100644
--- a/source/blender/blenlib/intern/freetypefont.c
+++ b/source/blender/blenlib/intern/freetypefont.c
@@ -151,7 +151,7 @@ void freetypechar_to_vchar(FT_Face face, FT_ULong charcode, VFontData *vfd)
nu->type= CU_BEZIER+CU_2D;
nu->pntsu = onpoints[j];
nu->resolu= 8;
- nu->flagu= 1;
+ nu->flagu= CU_CYCLIC;
nu->bezt = bezt;
//individual curve loop, start-end
@@ -399,8 +399,6 @@ static VFontData *objfnt_to_ftvfontdata(PackedFile * pf)
break;
lcode = charcode;
}
-
- err = FT_Set_Charmap( face, (FT_CharMap) FT_ENCODING_UNICODE );
return vfd;
}
diff --git a/source/blender/blenlib/intern/graph.c b/source/blender/blenlib/intern/graph.c
new file mode 100644
index 00000000000..8f35b38379e
--- /dev/null
+++ b/source/blender/blenlib/intern/graph.c
@@ -0,0 +1,1087 @@
+/**
+ * $Id:
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * Contributor(s): Martin Poirier
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ * graph.c: Common graph interface and methods
+ */
+
+#include <float.h>
+#include <math.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_graph.h"
+#include "BLI_blenlib.h"
+#include "BLI_arithb.h"
+
+#include "BKE_utildefines.h"
+
+static void testRadialSymmetry(BGraph *graph, BNode* root_node, RadialArc* ring, int total, float axis[3], float limit, int group);
+
+static void handleAxialSymmetry(BGraph *graph, BNode *root_node, int depth, float axis[3], float limit);
+static void testAxialSymmetry(BGraph *graph, BNode* root_node, BNode* node1, BNode* node2, BArc* arc1, BArc* arc2, float axis[3], float limit, int group);
+static void flagAxialSymmetry(BNode *root_node, BNode *end_node, BArc *arc, int group);
+
+void BLI_freeNode(BGraph *graph, BNode *node)
+{
+ if (node->arcs)
+ {
+ MEM_freeN(node->arcs);
+ }
+
+ if (graph->free_node)
+ {
+ graph->free_node(node);
+ }
+}
+
+void BLI_removeNode(BGraph *graph, BNode *node)
+{
+ BLI_freeNode(graph, node);
+ BLI_freelinkN(&graph->nodes, node);
+}
+
+BNode *BLI_otherNode(BArc *arc, BNode *node)
+{
+ return (arc->head == node) ? arc->tail : arc->head;
+}
+
+void BLI_removeArc(BGraph *graph, BArc *arc)
+{
+ if (graph->free_arc)
+ {
+ graph->free_arc(arc);
+ }
+
+ BLI_freelinkN(&graph->arcs, arc);
+}
+
+void BLI_flagNodes(BGraph *graph, int flag)
+{
+ BNode *node;
+
+ for(node = graph->nodes.first; node; node = node->next)
+ {
+ node->flag = flag;
+ }
+}
+
+void BLI_flagArcs(BGraph *graph, int flag)
+{
+ BArc *arc;
+
+ for(arc = graph->arcs.first; arc; arc = arc->next)
+ {
+ arc->flag = flag;
+ }
+}
+
+static void addArcToNodeAdjacencyList(BNode *node, BArc *arc)
+{
+ node->arcs[node->flag] = arc;
+ node->flag++;
+}
+
+void BLI_buildAdjacencyList(BGraph *graph)
+{
+ BNode *node;
+ BArc *arc;
+
+ for(node = graph->nodes.first; node; node = node->next)
+ {
+ if (node->arcs != NULL)
+ {
+ MEM_freeN(node->arcs);
+ }
+
+ node->arcs = MEM_callocN((node->degree) * sizeof(BArc*), "adjacency list");
+
+ /* temporary use to indicate the first index available in the lists */
+ node->flag = 0;
+ }
+
+ for(arc = graph->arcs.first; arc; arc= arc->next)
+ {
+ addArcToNodeAdjacencyList(arc->head, arc);
+ addArcToNodeAdjacencyList(arc->tail, arc);
+ }
+
+ for(node = graph->nodes.first; node; node = node->next)
+ {
+ if (node->degree != node->flag)
+ {
+ printf("error in node [%p]. Added only %i arcs out of %i\n", node, node->flag, node->degree);
+ }
+ }
+}
+
+void BLI_rebuildAdjacencyListForNode(BGraph* graph, BNode *node)
+{
+ BArc *arc;
+
+ if (node->arcs != NULL)
+ {
+ MEM_freeN(node->arcs);
+ }
+
+ node->arcs = MEM_callocN((node->degree) * sizeof(BArc*), "adjacency list");
+
+ /* temporary use to indicate the first index available in the lists */
+ node->flag = 0;
+
+ for(arc = graph->arcs.first; arc; arc= arc->next)
+ {
+ if (arc->head == node)
+ {
+ addArcToNodeAdjacencyList(arc->head, arc);
+ }
+ else if (arc->tail == node)
+ {
+ addArcToNodeAdjacencyList(arc->tail, arc);
+ }
+ }
+
+ if (node->degree != node->flag)
+ {
+ printf("error in node [%p]. Added only %i arcs out of %i\n", node, node->flag, node->degree);
+ }
+}
+
+void BLI_freeAdjacencyList(BGraph *graph)
+{
+ BNode *node;
+
+ for(node = graph->nodes.first; node; node = node->next)
+ {
+ if (node->arcs != NULL)
+ {
+ MEM_freeN(node->arcs);
+ node->arcs = NULL;
+ }
+ }
+}
+
+int BLI_hasAdjacencyList(BGraph *graph)
+{
+ BNode *node;
+
+ for(node = graph->nodes.first; node; node = node->next)
+ {
+ if (node->arcs == NULL)
+ {
+ return 0;
+ }
+ }
+
+ return 1;
+}
+
+void BLI_replaceNodeInArc(BGraph *graph, BArc *arc, BNode *node_src, BNode *node_replaced)
+{
+ if (arc->head == node_replaced)
+ {
+ arc->head = node_src;
+ node_src->degree++;
+ }
+
+ if (arc->tail == node_replaced)
+ {
+ arc->tail = node_src;
+ node_src->degree++;
+ }
+
+ if (arc->head == arc->tail)
+ {
+ node_src->degree -= 2;
+
+ graph->free_arc(arc);
+ BLI_freelinkN(&graph->arcs, arc);
+ }
+
+ if (node_replaced->degree == 0)
+ {
+ BLI_removeNode(graph, node_replaced);
+ }
+}
+
+void BLI_replaceNode(BGraph *graph, BNode *node_src, BNode *node_replaced)
+{
+ BArc *arc, *next_arc;
+
+ for (arc = graph->arcs.first; arc; arc = next_arc)
+ {
+ next_arc = arc->next;
+
+ if (arc->head == node_replaced)
+ {
+ arc->head = node_src;
+ node_replaced->degree--;
+ node_src->degree++;
+ }
+
+ if (arc->tail == node_replaced)
+ {
+ arc->tail = node_src;
+ node_replaced->degree--;
+ node_src->degree++;
+ }
+
+ if (arc->head == arc->tail)
+ {
+ node_src->degree -= 2;
+
+ graph->free_arc(arc);
+ BLI_freelinkN(&graph->arcs, arc);
+ }
+ }
+
+ if (node_replaced->degree == 0)
+ {
+ BLI_removeNode(graph, node_replaced);
+ }
+}
+
+void BLI_removeDoubleNodes(BGraph *graph, float limit)
+{
+ BNode *node_src, *node_replaced;
+
+ for(node_src = graph->nodes.first; node_src; node_src = node_src->next)
+ {
+ for(node_replaced = graph->nodes.first; node_replaced; node_replaced = node_replaced->next)
+ {
+ if (node_replaced != node_src && VecLenf(node_replaced->p, node_src->p) <= limit)
+ {
+ BLI_replaceNode(graph, node_src, node_replaced);
+ }
+ }
+ }
+
+}
+
+BNode * BLI_FindNodeByPosition(BGraph *graph, float *p, float limit)
+{
+ BNode *closest_node = NULL, *node;
+ float min_distance;
+
+ for(node = graph->nodes.first; node; node = node->next)
+ {
+ float distance = VecLenf(p, node->p);
+ if (distance <= limit && (closest_node == NULL || distance < min_distance))
+ {
+ closest_node = node;
+ min_distance = distance;
+ }
+ }
+
+ return closest_node;
+}
+/************************************* SUBGRAPH DETECTION **********************************************/
+
+void flagSubgraph(BNode *node, int subgraph)
+{
+ if (node->subgraph_index == 0)
+ {
+ BArc *arc;
+ int i;
+
+ node->subgraph_index = subgraph;
+
+ for(i = 0; i < node->degree; i++)
+ {
+ arc = node->arcs[i];
+ flagSubgraph(BLI_otherNode(arc, node), subgraph);
+ }
+ }
+}
+
+int BLI_FlagSubgraphs(BGraph *graph)
+{
+ BNode *node;
+ int subgraph = 0;
+
+ if (BLI_hasAdjacencyList(graph) == 0)
+ {
+ BLI_buildAdjacencyList(graph);
+ }
+
+ for(node = graph->nodes.first; node; node = node->next)
+ {
+ node->subgraph_index = 0;
+ }
+
+ for (node = graph->nodes.first; node; node = node->next)
+ {
+ if (node->subgraph_index == 0)
+ {
+ subgraph++;
+ flagSubgraph(node, subgraph);
+ }
+ }
+
+ return subgraph;
+}
+
+void BLI_ReflagSubgraph(BGraph *graph, int old_subgraph, int new_subgraph)
+{
+ BNode *node;
+
+ for (node = graph->nodes.first; node; node = node->next)
+ {
+ if (node->flag == old_subgraph)
+ {
+ node->flag = new_subgraph;
+ }
+ }
+}
+
+/*************************************** CYCLE DETECTION ***********************************************/
+
+int detectCycle(BNode *node, BArc *src_arc)
+{
+ int value = 0;
+
+ if (node->flag == 0)
+ {
+ int i;
+
+ /* mark node as visited */
+ node->flag = 1;
+
+ for(i = 0; i < node->degree && value == 0; i++)
+ {
+ BArc *arc = node->arcs[i];
+
+ /* don't go back on the source arc */
+ if (arc != src_arc)
+ {
+ value = detectCycle(BLI_otherNode(arc, node), arc);
+ }
+ }
+ }
+ else
+ {
+ value = 1;
+ }
+
+ return value;
+}
+
+int BLI_isGraphCyclic(BGraph *graph)
+{
+ BNode *node;
+ int value = 0;
+
+ /* NEED TO CHECK IF ADJACENCY LIST EXIST */
+
+ /* Mark all nodes as not visited */
+ BLI_flagNodes(graph, 0);
+
+ /* detectCycles in subgraphs */
+ for(node = graph->nodes.first; node && value == 0; node = node->next)
+ {
+ /* only for nodes in subgraphs that haven't been visited yet */
+ if (node->flag == 0)
+ {
+ value = value || detectCycle(node, NULL);
+ }
+ }
+
+ return value;
+}
+
+BArc * BLI_findConnectedArc(BGraph *graph, BArc *arc, BNode *v)
+{
+ BArc *nextArc = arc->next;
+
+ for(nextArc = graph->arcs.first; nextArc; nextArc = nextArc->next)
+ {
+ if (arc != nextArc && (nextArc->head == v || nextArc->tail == v))
+ {
+ break;
+ }
+ }
+
+ return nextArc;
+}
+
+/*********************************** GRAPH AS TREE FUNCTIONS *******************************************/
+
+int subtreeShape(BNode *node, BArc *rootArc, int include_root)
+{
+ int depth = 0;
+
+ node->flag = 1;
+
+ if (include_root)
+ {
+ BNode *newNode = BLI_otherNode(rootArc, node);
+ return subtreeShape(newNode, rootArc, 0);
+ }
+ else
+ {
+ /* Base case, no arcs leading away */
+ if (node->arcs == NULL || *(node->arcs) == NULL)
+ {
+ return 0;
+ }
+ else
+ {
+ int i;
+
+ for(i = 0; i < node->degree; i++)
+ {
+ BArc *arc = node->arcs[i];
+ BNode *newNode = BLI_otherNode(arc, node);
+
+ /* stop immediate and cyclic backtracking */
+ if (arc != rootArc && newNode->flag == 0)
+ {
+ depth += subtreeShape(newNode, arc, 0);
+ }
+ }
+ }
+
+ return SHAPE_RADIX * depth + 1;
+ }
+}
+
+int BLI_subtreeShape(BGraph *graph, BNode *node, BArc *rootArc, int include_root)
+{
+ BNode *test_node;
+
+ BLI_flagNodes(graph, 0);
+ return subtreeShape(node, rootArc, include_root);
+}
+
+float BLI_subtreeLength(BNode *node)
+{
+ float length = 0;
+ int i;
+
+ node->flag = 0; /* flag node as visited */
+
+ for(i = 0; i < node->degree; i++)
+ {
+ BArc *arc = node->arcs[i];
+ BNode *other_node = BLI_otherNode(arc, node);
+
+ if (other_node->flag != 0)
+ {
+ float subgraph_length = arc->length + BLI_subtreeLength(other_node);
+ length = MAX2(length, subgraph_length);
+ }
+ }
+
+ return length;
+}
+
+void BLI_calcGraphLength(BGraph *graph)
+{
+ float length = 0;
+ int nb_subgraphs;
+ int i;
+
+ nb_subgraphs = BLI_FlagSubgraphs(graph);
+
+ for (i = 1; i <= nb_subgraphs; i++)
+ {
+ BNode *node;
+
+ for (node = graph->nodes.first; node; node = node->next)
+ {
+ /* start on an external node of the subgraph */
+ if (node->subgraph_index == i && node->degree == 1)
+ {
+ float subgraph_length = BLI_subtreeLength(node);
+ length = MAX2(length, subgraph_length);
+ break;
+ }
+ }
+ }
+
+ graph->length = length;
+}
+
+/********************************* SYMMETRY DETECTION **************************************************/
+
+void markdownSymmetryArc(BGraph *graph, BArc *arc, BNode *node, int level, float limit);
+
+void BLI_mirrorAlongAxis(float v[3], float center[3], float axis[3])
+{
+ float dv[3], pv[3];
+
+ VecSubf(dv, v, center);
+ Projf(pv, dv, axis);
+ VecMulf(pv, -2);
+ VecAddf(v, v, pv);
+}
+
+static void testRadialSymmetry(BGraph *graph, BNode* root_node, RadialArc* ring, int total, float axis[3], float limit, int group)
+{
+ int symmetric = 1;
+ int i;
+
+ /* sort ring by angle */
+ for (i = 0; i < total - 1; i++)
+ {
+ float minAngle = FLT_MAX;
+ int minIndex = -1;
+ int j;
+
+ for (j = i + 1; j < total; j++)
+ {
+ float angle = Inpf(ring[i].n, ring[j].n);
+
+ /* map negative values to 1..2 */
+ if (angle < 0)
+ {
+ angle = 1 - angle;
+ }
+
+ if (angle < minAngle)
+ {
+ minIndex = j;
+ minAngle = angle;
+ }
+ }
+
+ /* swap if needed */
+ if (minIndex != i + 1)
+ {
+ RadialArc tmp;
+ tmp = ring[i + 1];
+ ring[i + 1] = ring[minIndex];
+ ring[minIndex] = tmp;
+ }
+ }
+
+ for (i = 0; i < total && symmetric; i++)
+ {
+ BNode *node1, *node2;
+ float tangent[3];
+ float normal[3];
+ float p[3];
+ int j = (i + 1) % total; /* next arc in the circular list */
+
+ VecAddf(tangent, ring[i].n, ring[j].n);
+ Crossf(normal, tangent, axis);
+
+ node1 = BLI_otherNode(ring[i].arc, root_node);
+ node2 = BLI_otherNode(ring[j].arc, root_node);
+
+ VECCOPY(p, node2->p);
+ BLI_mirrorAlongAxis(p, root_node->p, normal);
+
+ /* check if it's within limit before continuing */
+ if (VecLenf(node1->p, p) > limit)
+ {
+ symmetric = 0;
+ }
+
+ }
+
+ if (symmetric)
+ {
+ /* mark node as symmetric physically */
+ VECCOPY(root_node->symmetry_axis, axis);
+ root_node->symmetry_flag |= SYM_PHYSICAL;
+ root_node->symmetry_flag |= SYM_RADIAL;
+
+ /* FLAG SYMMETRY GROUP */
+ for (i = 0; i < total; i++)
+ {
+ ring[i].arc->symmetry_group = group;
+ ring[i].arc->symmetry_flag = SYM_SIDE_RADIAL + i;
+ }
+
+ if (graph->radial_symmetry)
+ {
+ graph->radial_symmetry(root_node, ring, total);
+ }
+ }
+}
+
+static void handleRadialSymmetry(BGraph *graph, BNode *root_node, int depth, float axis[3], float limit)
+{
+ RadialArc *ring = NULL;
+ RadialArc *unit;
+ int total = 0;
+ int group;
+ int first;
+ int i;
+
+ /* mark topological symmetry */
+ root_node->symmetry_flag |= SYM_TOPOLOGICAL;
+
+ /* total the number of arcs in the symmetry ring */
+ for (i = 0; i < root_node->degree; i++)
+ {
+ BArc *connectedArc = root_node->arcs[i];
+
+ /* depth is store as a negative in flag. symmetry level is positive */
+ if (connectedArc->symmetry_level == -depth)
+ {
+ total++;
+ }
+ }
+
+ ring = MEM_callocN(sizeof(RadialArc) * total, "radial symmetry ring");
+ unit = ring;
+
+ /* fill in the ring */
+ for (unit = ring, i = 0; i < root_node->degree; i++)
+ {
+ BArc *connectedArc = root_node->arcs[i];
+
+ /* depth is store as a negative in flag. symmetry level is positive */
+ if (connectedArc->symmetry_level == -depth)
+ {
+ BNode *otherNode = BLI_otherNode(connectedArc, root_node);
+ float vec[3];
+
+ unit->arc = connectedArc;
+
+ /* project the node to node vector on the symmetry plane */
+ VecSubf(unit->n, otherNode->p, root_node->p);
+ Projf(vec, unit->n, axis);
+ VecSubf(unit->n, unit->n, vec);
+
+ Normalize(unit->n);
+
+ unit++;
+ }
+ }
+
+ /* sort ring by arc length
+ * using a rather bogus insertion sort
+ * butrings will never get too big to matter
+ * */
+ for (i = 0; i < total; i++)
+ {
+ int j;
+
+ for (j = i - 1; j >= 0; j--)
+ {
+ BArc *arc1, *arc2;
+
+ arc1 = ring[j].arc;
+ arc2 = ring[j + 1].arc;
+
+ if (arc1->length > arc2->length)
+ {
+ /* swap with smaller */
+ RadialArc tmp;
+
+ tmp = ring[j + 1];
+ ring[j + 1] = ring[j];
+ ring[j] = tmp;
+ }
+ else
+ {
+ break;
+ }
+ }
+ }
+
+ /* Dispatch to specific symmetry tests */
+ first = 0;
+ group = 0;
+
+ for (i = 1; i < total; i++)
+ {
+ int dispatch = 0;
+ int last = i - 1;
+
+ if (fabs(ring[first].arc->length - ring[i].arc->length) > limit)
+ {
+ dispatch = 1;
+ }
+
+ /* if not dispatching already and on last arc
+ * Dispatch using current arc as last
+ * */
+ if (dispatch == 0 && i == total - 1)
+ {
+ last = i;
+ dispatch = 1;
+ }
+
+ if (dispatch)
+ {
+ int sub_total = last - first + 1;
+
+ group += 1;
+
+ if (sub_total == 1)
+ {
+ group -= 1; /* not really a group so decrement */
+ /* NOTHING TO DO */
+ }
+ else if (sub_total == 2)
+ {
+ BArc *arc1, *arc2;
+ BNode *node1, *node2;
+
+ arc1 = ring[first].arc;
+ arc2 = ring[last].arc;
+
+ node1 = BLI_otherNode(arc1, root_node);
+ node2 = BLI_otherNode(arc2, root_node);
+
+ testAxialSymmetry(graph, root_node, node1, node2, arc1, arc2, axis, limit, group);
+ }
+ else if (sub_total != total) /* allocate a new sub ring if needed */
+ {
+ RadialArc *sub_ring = MEM_callocN(sizeof(RadialArc) * sub_total, "radial symmetry ring");
+ int sub_i;
+
+ /* fill in the sub ring */
+ for (sub_i = 0; sub_i < sub_total; sub_i++)
+ {
+ sub_ring[sub_i] = ring[first + sub_i];
+ }
+
+ testRadialSymmetry(graph, root_node, sub_ring, sub_total, axis, limit, group);
+
+ MEM_freeN(sub_ring);
+ }
+ else if (sub_total == total)
+ {
+ testRadialSymmetry(graph, root_node, ring, total, axis, limit, group);
+ }
+
+ first = i;
+ }
+ }
+
+
+ MEM_freeN(ring);
+}
+
+static void flagAxialSymmetry(BNode *root_node, BNode *end_node, BArc *arc, int group)
+{
+ float vec[3];
+
+ arc->symmetry_group = group;
+
+ VecSubf(vec, end_node->p, root_node->p);
+
+ if (Inpf(vec, root_node->symmetry_axis) < 0)
+ {
+ arc->symmetry_flag |= SYM_SIDE_NEGATIVE;
+ }
+ else
+ {
+ arc->symmetry_flag |= SYM_SIDE_POSITIVE;
+ }
+}
+
+static void testAxialSymmetry(BGraph *graph, BNode* root_node, BNode* node1, BNode* node2, BArc* arc1, BArc* arc2, float axis[3], float limit, int group)
+{
+ float nor[3], vec[3], p[3];
+
+ VecSubf(p, node1->p, root_node->p);
+ Crossf(nor, p, axis);
+
+ VecSubf(p, root_node->p, node2->p);
+ Crossf(vec, p, axis);
+ VecAddf(vec, vec, nor);
+
+ Crossf(nor, vec, axis);
+
+ if (abs(nor[0]) > abs(nor[1]) && abs(nor[0]) > abs(nor[2]) && nor[0] < 0)
+ {
+ VecMulf(nor, -1);
+ }
+ else if (abs(nor[1]) > abs(nor[0]) && abs(nor[1]) > abs(nor[2]) && nor[1] < 0)
+ {
+ VecMulf(nor, -1);
+ }
+ else if (abs(nor[2]) > abs(nor[1]) && abs(nor[2]) > abs(nor[0]) && nor[2] < 0)
+ {
+ VecMulf(nor, -1);
+ }
+
+ /* mirror node2 along axis */
+ VECCOPY(p, node2->p);
+ BLI_mirrorAlongAxis(p, root_node->p, nor);
+
+ /* check if it's within limit before continuing */
+ if (VecLenf(node1->p, p) <= limit)
+ {
+ /* mark node as symmetric physically */
+ VECCOPY(root_node->symmetry_axis, nor);
+ root_node->symmetry_flag |= SYM_PHYSICAL;
+ root_node->symmetry_flag |= SYM_AXIAL;
+
+ /* flag side on arcs */
+ flagAxialSymmetry(root_node, node1, arc1, group);
+ flagAxialSymmetry(root_node, node2, arc2, group);
+
+ if (graph->axial_symmetry)
+ {
+ graph->axial_symmetry(root_node, node1, node2, arc1, arc2);
+ }
+ }
+ else
+ {
+ /* NOT SYMMETRIC */
+ }
+}
+
+static void handleAxialSymmetry(BGraph *graph, BNode *root_node, int depth, float axis[3], float limit)
+{
+ BArc *arc1 = NULL, *arc2 = NULL;
+ BNode *node1 = NULL, *node2 = NULL;
+ int i;
+
+ /* mark topological symmetry */
+ root_node->symmetry_flag |= SYM_TOPOLOGICAL;
+
+ for (i = 0; i < root_node->degree; i++)
+ {
+ BArc *connectedArc = root_node->arcs[i];
+
+ /* depth is store as a negative in flag. symmetry level is positive */
+ if (connectedArc->symmetry_level == -depth)
+ {
+ if (arc1 == NULL)
+ {
+ arc1 = connectedArc;
+ node1 = BLI_otherNode(arc1, root_node);
+ }
+ else
+ {
+ arc2 = connectedArc;
+ node2 = BLI_otherNode(arc2, root_node);
+ break; /* Can stop now, the two arcs have been found */
+ }
+ }
+ }
+
+ /* shouldn't happen, but just to be sure */
+ if (node1 == NULL || node2 == NULL)
+ {
+ return;
+ }
+
+ testAxialSymmetry(graph, root_node, node1, node2, arc1, arc2, axis, limit, 1);
+}
+
+static void markdownSecondarySymmetry(BGraph *graph, BNode *node, int depth, int level, float limit)
+{
+ float axis[3] = {0, 0, 0};
+ int count = 0;
+ int i;
+
+ /* count the number of branches in this symmetry group
+ * and determinte the axis of symmetry
+ * */
+ for (i = 0; i < node->degree; i++)
+ {
+ BArc *connectedArc = node->arcs[i];
+
+ /* depth is store as a negative in flag. symmetry level is positive */
+ if (connectedArc->symmetry_level == -depth)
+ {
+ count++;
+ }
+ /* If arc is on the axis */
+ else if (connectedArc->symmetry_level == level)
+ {
+ VecAddf(axis, axis, connectedArc->head->p);
+ VecSubf(axis, axis, connectedArc->tail->p);
+ }
+ }
+
+ Normalize(axis);
+
+ /* Split between axial and radial symmetry */
+ if (count == 2)
+ {
+ handleAxialSymmetry(graph, node, depth, axis, limit);
+ }
+ else
+ {
+ handleRadialSymmetry(graph, node, depth, axis, limit);
+ }
+
+ /* markdown secondary symetries */
+ for (i = 0; i < node->degree; i++)
+ {
+ BArc *connectedArc = node->arcs[i];
+
+ if (connectedArc->symmetry_level == -depth)
+ {
+ /* markdown symmetry for branches corresponding to the depth */
+ markdownSymmetryArc(graph, connectedArc, node, level + 1, limit);
+ }
+ }
+}
+
+void markdownSymmetryArc(BGraph *graph, BArc *arc, BNode *node, int level, float limit)
+{
+ int i;
+
+ /* if arc is null, we start straight from a node */
+ if (arc)
+ {
+ arc->symmetry_level = level;
+
+ node = BLI_otherNode(arc, node);
+ }
+
+ for (i = 0; i < node->degree; i++)
+ {
+ BArc *connectedArc = node->arcs[i];
+
+ if (connectedArc != arc)
+ {
+ BNode *connectedNode = BLI_otherNode(connectedArc, node);
+
+ /* symmetry level is positive value, negative values is subtree depth */
+ connectedArc->symmetry_level = -BLI_subtreeShape(graph, connectedNode, connectedArc, 0);
+ }
+ }
+
+ arc = NULL;
+
+ for (i = 0; i < node->degree; i++)
+ {
+ int issymmetryAxis = 0;
+ BArc *connectedArc = node->arcs[i];
+
+ /* only arcs not already marked as symetric */
+ if (connectedArc->symmetry_level < 0)
+ {
+ int j;
+
+ /* true by default */
+ issymmetryAxis = 1;
+
+ for (j = 0; j < node->degree; j++)
+ {
+ BArc *otherArc = node->arcs[j];
+
+ /* different arc, same depth */
+ if (otherArc != connectedArc && otherArc->symmetry_level == connectedArc->symmetry_level)
+ {
+ /* not on the symmetry axis */
+ issymmetryAxis = 0;
+ break;
+ }
+ }
+ }
+
+ /* arc could be on the symmetry axis */
+ if (issymmetryAxis == 1)
+ {
+ /* no arc as been marked previously, keep this one */
+ if (arc == NULL)
+ {
+ arc = connectedArc;
+ }
+ else if (connectedArc->symmetry_level < arc->symmetry_level)
+ {
+ /* go with more complex subtree as symmetry arc */
+ arc = connectedArc;
+ }
+ }
+ }
+
+ /* go down the arc continuing the symmetry axis */
+ if (arc)
+ {
+ markdownSymmetryArc(graph, arc, node, level, limit);
+ }
+
+
+ /* secondary symmetry */
+ for (i = 0; i < node->degree; i++)
+ {
+ BArc *connectedArc = node->arcs[i];
+
+ /* only arcs not already marked as symetric and is not the next arc on the symmetry axis */
+ if (connectedArc->symmetry_level < 0)
+ {
+ /* subtree depth is store as a negative value in the symmetry */
+ markdownSecondarySymmetry(graph, node, -connectedArc->symmetry_level, level, limit);
+ }
+ }
+}
+
+void BLI_markdownSymmetry(BGraph *graph, BNode *root_node, float limit)
+{
+ BNode *node;
+ BArc *arc;
+
+ if (BLI_isGraphCyclic(graph))
+ {
+ return;
+ }
+
+ /* mark down all arcs as non-symetric */
+ BLI_flagArcs(graph, 0);
+
+ /* mark down all nodes as not on the symmetry axis */
+ BLI_flagNodes(graph, 0);
+
+ node = root_node;
+
+ /* sanity check REMOVE ME */
+ if (node->degree > 0)
+ {
+ arc = node->arcs[0];
+
+ if (node->degree == 1)
+ {
+ markdownSymmetryArc(graph, arc, node, 1, limit);
+ }
+ else
+ {
+ markdownSymmetryArc(graph, NULL, node, 1, limit);
+ }
+
+
+
+ /* mark down non-symetric arcs */
+ for (arc = graph->arcs.first; arc; arc = arc->next)
+ {
+ if (arc->symmetry_level < 0)
+ {
+ arc->symmetry_level = 0;
+ }
+ else
+ {
+ /* mark down nodes with the lowest level symmetry axis */
+ if (arc->head->symmetry_level == 0 || arc->head->symmetry_level > arc->symmetry_level)
+ {
+ arc->head->symmetry_level = arc->symmetry_level;
+ }
+ if (arc->tail->symmetry_level == 0 || arc->tail->symmetry_level > arc->symmetry_level)
+ {
+ arc->tail->symmetry_level = arc->symmetry_level;
+ }
+ }
+ }
+ }
+}
+
diff --git a/source/blender/blenlib/intern/noise.c b/source/blender/blenlib/intern/noise.c
index a678c44d4bf..0bd30a69d05 100644
--- a/source/blender/blenlib/intern/noise.c
+++ b/source/blender/blenlib/intern/noise.c
@@ -387,55 +387,521 @@ static char p[512+2]= {
float g[512+2][3]= {
-0.33783,0.715698,-0.611206,-0.944031,-0.326599,-0.045624,-0.101074,-0.416443,-0.903503,0.799286,0.49411,-0.341949,-0.854645,0.518036,0.033936,0.42514,-0.437866,-0.792114,-0.358948,0.597046,0.717377,-0.985413,0.144714,0.089294,-0.601776,-0.33728,-0.723907,-0.449921,0.594513,0.666382,0.208313,-0.10791,
-0.972076,0.575317,0.060425,0.815643,0.293365,-0.875702,-0.383453,0.293762,0.465759,0.834686,-0.846008,-0.233398,-0.47934,-0.115814,0.143036,-0.98291,0.204681,-0.949036,-0.239532,0.946716,-0.263947,0.184326,-0.235596,0.573822,0.784332,0.203705,-0.372253,-0.905487,0.756989,-0.651031,0.055298,0.497803,
-0.814697,-0.297363,-0.16214,0.063995,-0.98468,-0.329254,0.834381,0.441925,0.703827,-0.527039,-0.476227,0.956421,0.266113,0.119781,0.480133,0.482849,0.7323,-0.18631,0.961212,-0.203125,-0.748474,-0.656921,-0.090393,-0.085052,-0.165253,0.982544,-0.76947,0.628174,-0.115234,0.383148,0.537659,0.751068,
-0.616486,-0.668488,-0.415924,-0.259979,-0.630005,0.73175,0.570953,-0.087952,0.816223,-0.458008,0.023254,0.888611,-0.196167,0.976563,-0.088287,-0.263885,-0.69812,-0.665527,0.437134,-0.892273,-0.112793,-0.621674,-0.230438,0.748566,0.232422,0.900574,-0.367249,0.22229,-0.796143,0.562744,-0.665497,-0.73764,
-0.11377,0.670135,0.704803,0.232605,0.895599,0.429749,-0.114655,-0.11557,-0.474243,0.872742,0.621826,0.604004,-0.498444,-0.832214,0.012756,0.55426,-0.702484,0.705994,-0.089661,-0.692017,0.649292,0.315399,-0.175995,-0.977997,0.111877,0.096954,-0.04953,0.994019,0.635284,-0.606689,-0.477783,-0.261261,
--0.607422,-0.750153,0.983276,0.165436,0.075958,-0.29837,0.404083,-0.864655,-0.638672,0.507721,0.578156,0.388214,0.412079,0.824249,0.556183,-0.208832,0.804352,0.778442,0.562012,0.27951,-0.616577,0.781921,-0.091522,0.196289,0.051056,0.979187,-0.121216,0.207153,-0.970734,-0.173401,-0.384735,0.906555,
-0.161499,-0.723236,-0.671387,0.178497,-0.006226,-0.983887,-0.126038,0.15799,0.97934,0.830475,-0.024811,0.556458,-0.510132,-0.76944,0.384247,0.81424,0.200104,-0.544891,-0.112549,-0.393311,-0.912445,0.56189,0.152222,-0.813049,0.198914,-0.254517,-0.946381,-0.41217,0.690979,-0.593811,-0.407257,0.324524,
-0.853668,-0.690186,0.366119,-0.624115,-0.428345,0.844147,-0.322296,-0.21228,-0.297546,-0.930756,-0.273071,0.516113,0.811798,0.928314,0.371643,0.007233,0.785828,-0.479218,-0.390778,-0.704895,0.058929,0.706818,0.173248,0.203583,0.963562,0.422211,-0.904297,-0.062469,-0.363312,-0.182465,0.913605,0.254028,
--0.552307,-0.793945,-0.28891,-0.765747,-0.574554,0.058319,0.291382,0.954803,0.946136,-0.303925,0.111267,-0.078156,0.443695,-0.892731,0.182098,0.89389,0.409515,-0.680298,-0.213318,0.701141,0.062469,0.848389,-0.525635,-0.72879,-0.641846,0.238342,-0.88089,0.427673,0.202637,-0.532501,-0.21405,0.818878,
-0.948975,-0.305084,0.07962,0.925446,0.374664,0.055817,0.820923,0.565491,0.079102,0.25882,0.099792,-0.960724,-0.294617,0.910522,0.289978,0.137115,0.320038,-0.937408,-0.908386,0.345276,-0.235718,-0.936218,0.138763,0.322754,0.366577,0.925934,-0.090637,0.309296,-0.686829,-0.657684,0.66983,0.024445,
-0.742065,-0.917999,-0.059113,-0.392059,0.365509,0.462158,-0.807922,0.083374,0.996399,-0.014801,0.593842,0.253143,-0.763672,0.974976,-0.165466,0.148285,0.918976,0.137299,0.369537,0.294952,0.694977,0.655731,0.943085,0.152618,-0.295319,0.58783,-0.598236,0.544495,0.203796,0.678223,0.705994,-0.478821,
--0.661011,0.577667,0.719055,-0.1698,-0.673828,-0.132172,-0.965332,0.225006,-0.981873,-0.14502,0.121979,0.763458,0.579742,0.284546,-0.893188,0.079681,0.442474,-0.795776,-0.523804,0.303802,0.734955,0.67804,-0.007446,0.15506,0.986267,-0.056183,0.258026,0.571503,-0.778931,-0.681549,-0.702087,-0.206116,
--0.96286,-0.177185,0.203613,-0.470978,-0.515106,0.716095,-0.740326,0.57135,0.354095,-0.56012,-0.824982,-0.074982,-0.507874,0.753204,0.417969,-0.503113,0.038147,0.863342,0.594025,0.673553,-0.439758,-0.119873,-0.005524,-0.992737,0.098267,-0.213776,0.971893,-0.615631,0.643951,0.454163,0.896851,-0.441071,
-0.032166,-0.555023,0.750763,-0.358093,0.398773,0.304688,0.864929,-0.722961,0.303589,0.620544,-0.63559,-0.621948,-0.457306,-0.293243,0.072327,0.953278,-0.491638,0.661041,-0.566772,-0.304199,-0.572083,-0.761688,0.908081,-0.398956,0.127014,-0.523621,-0.549683,-0.650848,-0.932922,-0.19986,0.299408,0.099426,
-0.140869,0.984985,-0.020325,-0.999756,-0.002319,0.952667,0.280853,-0.11615,-0.971893,0.082581,0.220337,0.65921,0.705292,-0.260651,0.733063,-0.175537,0.657043,-0.555206,0.429504,-0.712189,0.400421,-0.89859,0.179352,0.750885,-0.19696,0.630341,0.785675,-0.569336,0.241821,-0.058899,-0.464111,0.883789,
-0.129608,-0.94519,0.299622,-0.357819,0.907654,0.219238,-0.842133,-0.439117,-0.312927,-0.313477,0.84433,0.434479,-0.241211,0.053253,0.968994,0.063873,0.823273,0.563965,0.476288,0.862152,-0.172516,0.620941,-0.298126,0.724915,0.25238,-0.749359,-0.612122,-0.577545,0.386566,0.718994,-0.406342,-0.737976,
-0.538696,0.04718,0.556305,0.82959,-0.802856,0.587463,0.101166,-0.707733,-0.705963,0.026428,0.374908,0.68457,0.625092,0.472137,0.208405,-0.856506,-0.703064,-0.581085,-0.409821,-0.417206,-0.736328,0.532623,-0.447876,-0.20285,-0.870728,0.086945,-0.990417,0.107086,0.183685,0.018341,-0.982788,0.560638,
--0.428864,0.708282,0.296722,-0.952576,-0.0672,0.135773,0.990265,0.030243,-0.068787,0.654724,0.752686,0.762604,-0.551758,0.337585,-0.819611,-0.407684,0.402466,-0.727844,-0.55072,-0.408539,-0.855774,-0.480011,0.19281,0.693176,-0.079285,0.716339,0.226013,0.650116,-0.725433,0.246704,0.953369,-0.173553,
--0.970398,-0.239227,-0.03244,0.136383,-0.394318,0.908752,0.813232,0.558167,0.164368,0.40451,0.549042,-0.731323,-0.380249,-0.566711,0.730865,0.022156,0.932739,0.359741,0.00824,0.996552,-0.082306,0.956635,-0.065338,-0.283722,-0.743561,0.008209,0.668579,-0.859589,-0.509674,0.035767,-0.852234,0.363678,
--0.375977,-0.201965,-0.970795,-0.12915,0.313477,0.947327,0.06546,-0.254028,-0.528259,0.81015,0.628052,0.601105,0.49411,-0.494385,0.868378,0.037933,0.275635,-0.086426,0.957336,-0.197937,0.468903,-0.860748,0.895599,0.399384,0.195801,0.560791,0.825012,-0.069214,0.304199,-0.849487,0.43103,0.096375,
-0.93576,0.339111,-0.051422,0.408966,-0.911072,0.330444,0.942841,-0.042389,-0.452362,-0.786407,0.420563,0.134308,-0.933472,-0.332489,0.80191,-0.566711,-0.188934,-0.987946,-0.105988,0.112518,-0.24408,0.892242,-0.379791,-0.920502,0.229095,-0.316376,0.7789,0.325958,0.535706,-0.912872,0.185211,-0.36377,
--0.184784,0.565369,-0.803833,-0.018463,0.119537,0.992615,-0.259247,-0.935608,0.239532,-0.82373,-0.449127,-0.345947,-0.433105,0.659515,0.614349,-0.822754,0.378845,-0.423676,0.687195,-0.674835,-0.26889,-0.246582,-0.800842,0.545715,-0.729187,-0.207794,0.651978,0.653534,-0.610443,-0.447388,0.492584,-0.023346,
-0.869934,0.609039,0.009094,-0.79306,0.962494,-0.271088,-0.00885,0.2659,-0.004913,0.963959,0.651245,0.553619,-0.518951,0.280548,-0.84314,0.458618,-0.175293,-0.983215,0.049805,0.035339,-0.979919,0.196045,-0.982941,0.164307,-0.082245,0.233734,-0.97226,-0.005005,-0.747253,-0.611328,0.260437,0.645599,
-0.592773,0.481384,0.117706,-0.949524,-0.29068,-0.535004,-0.791901,-0.294312,-0.627167,-0.214447,0.748718,-0.047974,-0.813477,-0.57959,-0.175537,0.477264,-0.860992,0.738556,-0.414246,-0.53183,0.562561,-0.704071,0.433289,-0.754944,0.64801,-0.100586,0.114716,0.044525,-0.992371,0.966003,0.244873,-0.082764,
-0.33783,0.715698,-0.611206,-0.944031,-0.326599,-0.045624,-0.101074,-0.416443,-0.903503,0.799286,0.49411,-0.341949,-0.854645,0.518036,0.033936,0.42514,-0.437866,-0.792114,-0.358948,0.597046,0.717377,-0.985413,0.144714,0.089294,-0.601776,-0.33728,-0.723907,-0.449921,0.594513,0.666382,0.208313,-0.10791,
-0.972076,0.575317,0.060425,0.815643,0.293365,-0.875702,-0.383453,0.293762,0.465759,0.834686,-0.846008,-0.233398,-0.47934,-0.115814,0.143036,-0.98291,0.204681,-0.949036,-0.239532,0.946716,-0.263947,0.184326,-0.235596,0.573822,0.784332,0.203705,-0.372253,-0.905487,0.756989,-0.651031,0.055298,0.497803,
-0.814697,-0.297363,-0.16214,0.063995,-0.98468,-0.329254,0.834381,0.441925,0.703827,-0.527039,-0.476227,0.956421,0.266113,0.119781,0.480133,0.482849,0.7323,-0.18631,0.961212,-0.203125,-0.748474,-0.656921,-0.090393,-0.085052,-0.165253,0.982544,-0.76947,0.628174,-0.115234,0.383148,0.537659,0.751068,
-0.616486,-0.668488,-0.415924,-0.259979,-0.630005,0.73175,0.570953,-0.087952,0.816223,-0.458008,0.023254,0.888611,-0.196167,0.976563,-0.088287,-0.263885,-0.69812,-0.665527,0.437134,-0.892273,-0.112793,-0.621674,-0.230438,0.748566,0.232422,0.900574,-0.367249,0.22229,-0.796143,0.562744,-0.665497,-0.73764,
-0.11377,0.670135,0.704803,0.232605,0.895599,0.429749,-0.114655,-0.11557,-0.474243,0.872742,0.621826,0.604004,-0.498444,-0.832214,0.012756,0.55426,-0.702484,0.705994,-0.089661,-0.692017,0.649292,0.315399,-0.175995,-0.977997,0.111877,0.096954,-0.04953,0.994019,0.635284,-0.606689,-0.477783,-0.261261,
--0.607422,-0.750153,0.983276,0.165436,0.075958,-0.29837,0.404083,-0.864655,-0.638672,0.507721,0.578156,0.388214,0.412079,0.824249,0.556183,-0.208832,0.804352,0.778442,0.562012,0.27951,-0.616577,0.781921,-0.091522,0.196289,0.051056,0.979187,-0.121216,0.207153,-0.970734,-0.173401,-0.384735,0.906555,
-0.161499,-0.723236,-0.671387,0.178497,-0.006226,-0.983887,-0.126038,0.15799,0.97934,0.830475,-0.024811,0.556458,-0.510132,-0.76944,0.384247,0.81424,0.200104,-0.544891,-0.112549,-0.393311,-0.912445,0.56189,0.152222,-0.813049,0.198914,-0.254517,-0.946381,-0.41217,0.690979,-0.593811,-0.407257,0.324524,
-0.853668,-0.690186,0.366119,-0.624115,-0.428345,0.844147,-0.322296,-0.21228,-0.297546,-0.930756,-0.273071,0.516113,0.811798,0.928314,0.371643,0.007233,0.785828,-0.479218,-0.390778,-0.704895,0.058929,0.706818,0.173248,0.203583,0.963562,0.422211,-0.904297,-0.062469,-0.363312,-0.182465,0.913605,0.254028,
--0.552307,-0.793945,-0.28891,-0.765747,-0.574554,0.058319,0.291382,0.954803,0.946136,-0.303925,0.111267,-0.078156,0.443695,-0.892731,0.182098,0.89389,0.409515,-0.680298,-0.213318,0.701141,0.062469,0.848389,-0.525635,-0.72879,-0.641846,0.238342,-0.88089,0.427673,0.202637,-0.532501,-0.21405,0.818878,
-0.948975,-0.305084,0.07962,0.925446,0.374664,0.055817,0.820923,0.565491,0.079102,0.25882,0.099792,-0.960724,-0.294617,0.910522,0.289978,0.137115,0.320038,-0.937408,-0.908386,0.345276,-0.235718,-0.936218,0.138763,0.322754,0.366577,0.925934,-0.090637,0.309296,-0.686829,-0.657684,0.66983,0.024445,
-0.742065,-0.917999,-0.059113,-0.392059,0.365509,0.462158,-0.807922,0.083374,0.996399,-0.014801,0.593842,0.253143,-0.763672,0.974976,-0.165466,0.148285,0.918976,0.137299,0.369537,0.294952,0.694977,0.655731,0.943085,0.152618,-0.295319,0.58783,-0.598236,0.544495,0.203796,0.678223,0.705994,-0.478821,
--0.661011,0.577667,0.719055,-0.1698,-0.673828,-0.132172,-0.965332,0.225006,-0.981873,-0.14502,0.121979,0.763458,0.579742,0.284546,-0.893188,0.079681,0.442474,-0.795776,-0.523804,0.303802,0.734955,0.67804,-0.007446,0.15506,0.986267,-0.056183,0.258026,0.571503,-0.778931,-0.681549,-0.702087,-0.206116,
--0.96286,-0.177185,0.203613,-0.470978,-0.515106,0.716095,-0.740326,0.57135,0.354095,-0.56012,-0.824982,-0.074982,-0.507874,0.753204,0.417969,-0.503113,0.038147,0.863342,0.594025,0.673553,-0.439758,-0.119873,-0.005524,-0.992737,0.098267,-0.213776,0.971893,-0.615631,0.643951,0.454163,0.896851,-0.441071,
-0.032166,-0.555023,0.750763,-0.358093,0.398773,0.304688,0.864929,-0.722961,0.303589,0.620544,-0.63559,-0.621948,-0.457306,-0.293243,0.072327,0.953278,-0.491638,0.661041,-0.566772,-0.304199,-0.572083,-0.761688,0.908081,-0.398956,0.127014,-0.523621,-0.549683,-0.650848,-0.932922,-0.19986,0.299408,0.099426,
-0.140869,0.984985,-0.020325,-0.999756,-0.002319,0.952667,0.280853,-0.11615,-0.971893,0.082581,0.220337,0.65921,0.705292,-0.260651,0.733063,-0.175537,0.657043,-0.555206,0.429504,-0.712189,0.400421,-0.89859,0.179352,0.750885,-0.19696,0.630341,0.785675,-0.569336,0.241821,-0.058899,-0.464111,0.883789,
-0.129608,-0.94519,0.299622,-0.357819,0.907654,0.219238,-0.842133,-0.439117,-0.312927,-0.313477,0.84433,0.434479,-0.241211,0.053253,0.968994,0.063873,0.823273,0.563965,0.476288,0.862152,-0.172516,0.620941,-0.298126,0.724915,0.25238,-0.749359,-0.612122,-0.577545,0.386566,0.718994,-0.406342,-0.737976,
-0.538696,0.04718,0.556305,0.82959,-0.802856,0.587463,0.101166,-0.707733,-0.705963,0.026428,0.374908,0.68457,0.625092,0.472137,0.208405,-0.856506,-0.703064,-0.581085,-0.409821,-0.417206,-0.736328,0.532623,-0.447876,-0.20285,-0.870728,0.086945,-0.990417,0.107086,0.183685,0.018341,-0.982788,0.560638,
--0.428864,0.708282,0.296722,-0.952576,-0.0672,0.135773,0.990265,0.030243,-0.068787,0.654724,0.752686,0.762604,-0.551758,0.337585,-0.819611,-0.407684,0.402466,-0.727844,-0.55072,-0.408539,-0.855774,-0.480011,0.19281,0.693176,-0.079285,0.716339,0.226013,0.650116,-0.725433,0.246704,0.953369,-0.173553,
--0.970398,-0.239227,-0.03244,0.136383,-0.394318,0.908752,0.813232,0.558167,0.164368,0.40451,0.549042,-0.731323,-0.380249,-0.566711,0.730865,0.022156,0.932739,0.359741,0.00824,0.996552,-0.082306,0.956635,-0.065338,-0.283722,-0.743561,0.008209,0.668579,-0.859589,-0.509674,0.035767,-0.852234,0.363678,
--0.375977,-0.201965,-0.970795,-0.12915,0.313477,0.947327,0.06546,-0.254028,-0.528259,0.81015,0.628052,0.601105,0.49411,-0.494385,0.868378,0.037933,0.275635,-0.086426,0.957336,-0.197937,0.468903,-0.860748,0.895599,0.399384,0.195801,0.560791,0.825012,-0.069214,0.304199,-0.849487,0.43103,0.096375,
-0.93576,0.339111,-0.051422,0.408966,-0.911072,0.330444,0.942841,-0.042389,-0.452362,-0.786407,0.420563,0.134308,-0.933472,-0.332489,0.80191,-0.566711,-0.188934,-0.987946,-0.105988,0.112518,-0.24408,0.892242,-0.379791,-0.920502,0.229095,-0.316376,0.7789,0.325958,0.535706,-0.912872,0.185211,-0.36377,
--0.184784,0.565369,-0.803833,-0.018463,0.119537,0.992615,-0.259247,-0.935608,0.239532,-0.82373,-0.449127,-0.345947,-0.433105,0.659515,0.614349,-0.822754,0.378845,-0.423676,0.687195,-0.674835,-0.26889,-0.246582,-0.800842,0.545715,-0.729187,-0.207794,0.651978,0.653534,-0.610443,-0.447388,0.492584,-0.023346,
-0.869934,0.609039,0.009094,-0.79306,0.962494,-0.271088,-0.00885,0.2659,-0.004913,0.963959,0.651245,0.553619,-0.518951,0.280548,-0.84314,0.458618,-0.175293,-0.983215,0.049805,0.035339,-0.979919,0.196045,-0.982941,0.164307,-0.082245,0.233734,-0.97226,-0.005005,-0.747253,-0.611328,0.260437,0.645599,
-0.592773,0.481384,0.117706,-0.949524,-0.29068,-0.535004,-0.791901,-0.294312,-0.627167,-0.214447,0.748718,-0.047974,-0.813477,-0.57959,-0.175537,0.477264,-0.860992,0.738556,-0.414246,-0.53183,0.562561,-0.704071,0.433289,-0.754944,0.64801,-0.100586,0.114716,0.044525,-0.992371,0.966003,0.244873,-0.082764,
-0.33783,0.715698,-0.611206,-0.944031,-0.326599,-0.045624};
+ {0.33783, 0.715698, -0.611206},
+ {-0.944031, -0.326599, -0.045624},
+ {-0.101074, -0.416443, -0.903503},
+ {0.799286, 0.49411, -0.341949},
+ {-0.854645, 0.518036, 0.033936},
+ {0.42514, -0.437866, -0.792114},
+ {-0.358948, 0.597046, 0.717377},
+ {-0.985413, 0.144714, 0.089294},
+ {-0.601776, -0.33728, -0.723907},
+ {-0.449921, 0.594513, 0.666382},
+ {0.208313, -0.10791, 0.972076},
+ {0.575317, 0.060425, 0.815643},
+ {0.293365, -0.875702, -0.383453},
+ {0.293762, 0.465759, 0.834686},
+ {-0.846008, -0.233398, -0.47934},
+ {-0.115814, 0.143036, -0.98291},
+ {0.204681, -0.949036, -0.239532},
+ {0.946716, -0.263947, 0.184326},
+ {-0.235596, 0.573822, 0.784332},
+ {0.203705, -0.372253, -0.905487},
+ {0.756989, -0.651031, 0.055298},
+ {0.497803, 0.814697, -0.297363},
+ {-0.16214, 0.063995, -0.98468},
+ {-0.329254, 0.834381, 0.441925},
+ {0.703827, -0.527039, -0.476227},
+ {0.956421, 0.266113, 0.119781},
+ {0.480133, 0.482849, 0.7323},
+ {-0.18631, 0.961212, -0.203125},
+ {-0.748474, -0.656921, -0.090393},
+ {-0.085052, -0.165253, 0.982544},
+ {-0.76947, 0.628174, -0.115234},
+ {0.383148, 0.537659, 0.751068},
+ {0.616486, -0.668488, -0.415924},
+ {-0.259979, -0.630005, 0.73175},
+ {0.570953, -0.087952, 0.816223},
+ {-0.458008, 0.023254, 0.888611},
+ {-0.196167, 0.976563, -0.088287},
+ {-0.263885, -0.69812, -0.665527},
+ {0.437134, -0.892273, -0.112793},
+ {-0.621674, -0.230438, 0.748566},
+ {0.232422, 0.900574, -0.367249},
+ {0.22229, -0.796143, 0.562744},
+ {-0.665497, -0.73764, 0.11377},
+ {0.670135, 0.704803, 0.232605},
+ {0.895599, 0.429749, -0.114655},
+ {-0.11557, -0.474243, 0.872742},
+ {0.621826, 0.604004, -0.498444},
+ {-0.832214, 0.012756, 0.55426},
+ {-0.702484, 0.705994, -0.089661},
+ {-0.692017, 0.649292, 0.315399},
+ {-0.175995, -0.977997, 0.111877},
+ {0.096954, -0.04953, 0.994019},
+ {0.635284, -0.606689, -0.477783},
+ {-0.261261, -0.607422, -0.750153},
+ {0.983276, 0.165436, 0.075958},
+ {-0.29837, 0.404083, -0.864655},
+ {-0.638672, 0.507721, 0.578156},
+ {0.388214, 0.412079, 0.824249},
+ {0.556183, -0.208832, 0.804352},
+ {0.778442, 0.562012, 0.27951},
+ {-0.616577, 0.781921, -0.091522},
+ {0.196289, 0.051056, 0.979187},
+ {-0.121216, 0.207153, -0.970734},
+ {-0.173401, -0.384735, 0.906555},
+ {0.161499, -0.723236, -0.671387},
+ {0.178497, -0.006226, -0.983887},
+ {-0.126038, 0.15799, 0.97934},
+ {0.830475, -0.024811, 0.556458},
+ {-0.510132, -0.76944, 0.384247},
+ {0.81424, 0.200104, -0.544891},
+ {-0.112549, -0.393311, -0.912445},
+ {0.56189, 0.152222, -0.813049},
+ {0.198914, -0.254517, -0.946381},
+ {-0.41217, 0.690979, -0.593811},
+ {-0.407257, 0.324524, 0.853668},
+ {-0.690186, 0.366119, -0.624115},
+ {-0.428345, 0.844147, -0.322296},
+ {-0.21228, -0.297546, -0.930756},
+ {-0.273071, 0.516113, 0.811798},
+ {0.928314, 0.371643, 0.007233},
+ {0.785828, -0.479218, -0.390778},
+ {-0.704895, 0.058929, 0.706818},
+ {0.173248, 0.203583, 0.963562},
+ {0.422211, -0.904297, -0.062469},
+ {-0.363312, -0.182465, 0.913605},
+ {0.254028, -0.552307, -0.793945},
+ {-0.28891, -0.765747, -0.574554},
+ {0.058319, 0.291382, 0.954803},
+ {0.946136, -0.303925, 0.111267},
+ {-0.078156, 0.443695, -0.892731},
+ {0.182098, 0.89389, 0.409515},
+ {-0.680298, -0.213318, 0.701141},
+ {0.062469, 0.848389, -0.525635},
+ {-0.72879, -0.641846, 0.238342},
+ {-0.88089, 0.427673, 0.202637},
+ {-0.532501, -0.21405, 0.818878},
+ {0.948975, -0.305084, 0.07962},
+ {0.925446, 0.374664, 0.055817},
+ {0.820923, 0.565491, 0.079102},
+ {0.25882, 0.099792, -0.960724},
+ {-0.294617, 0.910522, 0.289978},
+ {0.137115, 0.320038, -0.937408},
+ {-0.908386, 0.345276, -0.235718},
+ {-0.936218, 0.138763, 0.322754},
+ {0.366577, 0.925934, -0.090637},
+ {0.309296, -0.686829, -0.657684},
+ {0.66983, 0.024445, 0.742065},
+ {-0.917999, -0.059113, -0.392059},
+ {0.365509, 0.462158, -0.807922},
+ {0.083374, 0.996399, -0.014801},
+ {0.593842, 0.253143, -0.763672},
+ {0.974976, -0.165466, 0.148285},
+ {0.918976, 0.137299, 0.369537},
+ {0.294952, 0.694977, 0.655731},
+ {0.943085, 0.152618, -0.295319},
+ {0.58783, -0.598236, 0.544495},
+ {0.203796, 0.678223, 0.705994},
+ {-0.478821, -0.661011, 0.577667},
+ {0.719055, -0.1698, -0.673828},
+ {-0.132172, -0.965332, 0.225006},
+ {-0.981873, -0.14502, 0.121979},
+ {0.763458, 0.579742, 0.284546},
+ {-0.893188, 0.079681, 0.442474},
+ {-0.795776, -0.523804, 0.303802},
+ {0.734955, 0.67804, -0.007446},
+ {0.15506, 0.986267, -0.056183},
+ {0.258026, 0.571503, -0.778931},
+ {-0.681549, -0.702087, -0.206116},
+ {-0.96286, -0.177185, 0.203613},
+ {-0.470978, -0.515106, 0.716095},
+ {-0.740326, 0.57135, 0.354095},
+ {-0.56012, -0.824982, -0.074982},
+ {-0.507874, 0.753204, 0.417969},
+ {-0.503113, 0.038147, 0.863342},
+ {0.594025, 0.673553, -0.439758},
+ {-0.119873, -0.005524, -0.992737},
+ {0.098267, -0.213776, 0.971893},
+ {-0.615631, 0.643951, 0.454163},
+ {0.896851, -0.441071, 0.032166},
+ {-0.555023, 0.750763, -0.358093},
+ {0.398773, 0.304688, 0.864929},
+ {-0.722961, 0.303589, 0.620544},
+ {-0.63559, -0.621948, -0.457306},
+ {-0.293243, 0.072327, 0.953278},
+ {-0.491638, 0.661041, -0.566772},
+ {-0.304199, -0.572083, -0.761688},
+ {0.908081, -0.398956, 0.127014},
+ {-0.523621, -0.549683, -0.650848},
+ {-0.932922, -0.19986, 0.299408},
+ {0.099426, 0.140869, 0.984985},
+ {-0.020325, -0.999756, -0.002319},
+ {0.952667, 0.280853, -0.11615},
+ {-0.971893, 0.082581, 0.220337},
+ {0.65921, 0.705292, -0.260651},
+ {0.733063, -0.175537, 0.657043},
+ {-0.555206, 0.429504, -0.712189},
+ {0.400421, -0.89859, 0.179352},
+ {0.750885, -0.19696, 0.630341},
+ {0.785675, -0.569336, 0.241821},
+ {-0.058899, -0.464111, 0.883789},
+ {0.129608, -0.94519, 0.299622},
+ {-0.357819, 0.907654, 0.219238},
+ {-0.842133, -0.439117, -0.312927},
+ {-0.313477, 0.84433, 0.434479},
+ {-0.241211, 0.053253, 0.968994},
+ {0.063873, 0.823273, 0.563965},
+ {0.476288, 0.862152, -0.172516},
+ {0.620941, -0.298126, 0.724915},
+ {0.25238, -0.749359, -0.612122},
+ {-0.577545, 0.386566, 0.718994},
+ {-0.406342, -0.737976, 0.538696},
+ {0.04718, 0.556305, 0.82959},
+ {-0.802856, 0.587463, 0.101166},
+ {-0.707733, -0.705963, 0.026428},
+ {0.374908, 0.68457, 0.625092},
+ {0.472137, 0.208405, -0.856506},
+ {-0.703064, -0.581085, -0.409821},
+ {-0.417206, -0.736328, 0.532623},
+ {-0.447876, -0.20285, -0.870728},
+ {0.086945, -0.990417, 0.107086},
+ {0.183685, 0.018341, -0.982788},
+ {0.560638, -0.428864, 0.708282},
+ {0.296722, -0.952576, -0.0672},
+ {0.135773, 0.990265, 0.030243},
+ {-0.068787, 0.654724, 0.752686},
+ {0.762604, -0.551758, 0.337585},
+ {-0.819611, -0.407684, 0.402466},
+ {-0.727844, -0.55072, -0.408539},
+ {-0.855774, -0.480011, 0.19281},
+ {0.693176, -0.079285, 0.716339},
+ {0.226013, 0.650116, -0.725433},
+ {0.246704, 0.953369, -0.173553},
+ {-0.970398, -0.239227, -0.03244},
+ {0.136383, -0.394318, 0.908752},
+ {0.813232, 0.558167, 0.164368},
+ {0.40451, 0.549042, -0.731323},
+ {-0.380249, -0.566711, 0.730865},
+ {0.022156, 0.932739, 0.359741},
+ {0.00824, 0.996552, -0.082306},
+ {0.956635, -0.065338, -0.283722},
+ {-0.743561, 0.008209, 0.668579},
+ {-0.859589, -0.509674, 0.035767},
+ {-0.852234, 0.363678, -0.375977},
+ {-0.201965, -0.970795, -0.12915},
+ {0.313477, 0.947327, 0.06546},
+ {-0.254028, -0.528259, 0.81015},
+ {0.628052, 0.601105, 0.49411},
+ {-0.494385, 0.868378, 0.037933},
+ {0.275635, -0.086426, 0.957336},
+ {-0.197937, 0.468903, -0.860748},
+ {0.895599, 0.399384, 0.195801},
+ {0.560791, 0.825012, -0.069214},
+ {0.304199, -0.849487, 0.43103},
+ {0.096375, 0.93576, 0.339111},
+ {-0.051422, 0.408966, -0.911072},
+ {0.330444, 0.942841, -0.042389},
+ {-0.452362, -0.786407, 0.420563},
+ {0.134308, -0.933472, -0.332489},
+ {0.80191, -0.566711, -0.188934},
+ {-0.987946, -0.105988, 0.112518},
+ {-0.24408, 0.892242, -0.379791},
+ {-0.920502, 0.229095, -0.316376},
+ {0.7789, 0.325958, 0.535706},
+ {-0.912872, 0.185211, -0.36377},
+ {-0.184784, 0.565369, -0.803833},
+ {-0.018463, 0.119537, 0.992615},
+ {-0.259247, -0.935608, 0.239532},
+ {-0.82373, -0.449127, -0.345947},
+ {-0.433105, 0.659515, 0.614349},
+ {-0.822754, 0.378845, -0.423676},
+ {0.687195, -0.674835, -0.26889},
+ {-0.246582, -0.800842, 0.545715},
+ {-0.729187, -0.207794, 0.651978},
+ {0.653534, -0.610443, -0.447388},
+ {0.492584, -0.023346, 0.869934},
+ {0.609039, 0.009094, -0.79306},
+ {0.962494, -0.271088, -0.00885},
+ {0.2659, -0.004913, 0.963959},
+ {0.651245, 0.553619, -0.518951},
+ {0.280548, -0.84314, 0.458618},
+ {-0.175293, -0.983215, 0.049805},
+ {0.035339, -0.979919, 0.196045},
+ {-0.982941, 0.164307, -0.082245},
+ {0.233734, -0.97226, -0.005005},
+ {-0.747253, -0.611328, 0.260437},
+ {0.645599, 0.592773, 0.481384},
+ {0.117706, -0.949524, -0.29068},
+ {-0.535004, -0.791901, -0.294312},
+ {-0.627167, -0.214447, 0.748718},
+ {-0.047974, -0.813477, -0.57959},
+ {-0.175537, 0.477264, -0.860992},
+ {0.738556, -0.414246, -0.53183},
+ {0.562561, -0.704071, 0.433289},
+ {-0.754944, 0.64801, -0.100586},
+ {0.114716, 0.044525, -0.992371},
+ {0.966003, 0.244873, -0.082764},
+ {0.33783, 0.715698, -0.611206},
+ {-0.944031, -0.326599, -0.045624},
+ {-0.101074, -0.416443, -0.903503},
+ {0.799286, 0.49411, -0.341949},
+ {-0.854645, 0.518036, 0.033936},
+ {0.42514, -0.437866, -0.792114},
+ {-0.358948, 0.597046, 0.717377},
+ {-0.985413, 0.144714, 0.089294},
+ {-0.601776, -0.33728, -0.723907},
+ {-0.449921, 0.594513, 0.666382},
+ {0.208313, -0.10791, 0.972076},
+ {0.575317, 0.060425, 0.815643},
+ {0.293365, -0.875702, -0.383453},
+ {0.293762, 0.465759, 0.834686},
+ {-0.846008, -0.233398, -0.47934},
+ {-0.115814, 0.143036, -0.98291},
+ {0.204681, -0.949036, -0.239532},
+ {0.946716, -0.263947, 0.184326},
+ {-0.235596, 0.573822, 0.784332},
+ {0.203705, -0.372253, -0.905487},
+ {0.756989, -0.651031, 0.055298},
+ {0.497803, 0.814697, -0.297363},
+ {-0.16214, 0.063995, -0.98468},
+ {-0.329254, 0.834381, 0.441925},
+ {0.703827, -0.527039, -0.476227},
+ {0.956421, 0.266113, 0.119781},
+ {0.480133, 0.482849, 0.7323},
+ {-0.18631, 0.961212, -0.203125},
+ {-0.748474, -0.656921, -0.090393},
+ {-0.085052, -0.165253, 0.982544},
+ {-0.76947, 0.628174, -0.115234},
+ {0.383148, 0.537659, 0.751068},
+ {0.616486, -0.668488, -0.415924},
+ {-0.259979, -0.630005, 0.73175},
+ {0.570953, -0.087952, 0.816223},
+ {-0.458008, 0.023254, 0.888611},
+ {-0.196167, 0.976563, -0.088287},
+ {-0.263885, -0.69812, -0.665527},
+ {0.437134, -0.892273, -0.112793},
+ {-0.621674, -0.230438, 0.748566},
+ {0.232422, 0.900574, -0.367249},
+ {0.22229, -0.796143, 0.562744},
+ {-0.665497, -0.73764, 0.11377},
+ {0.670135, 0.704803, 0.232605},
+ {0.895599, 0.429749, -0.114655},
+ {-0.11557, -0.474243, 0.872742},
+ {0.621826, 0.604004, -0.498444},
+ {-0.832214, 0.012756, 0.55426},
+ {-0.702484, 0.705994, -0.089661},
+ {-0.692017, 0.649292, 0.315399},
+ {-0.175995, -0.977997, 0.111877},
+ {0.096954, -0.04953, 0.994019},
+ {0.635284, -0.606689, -0.477783},
+ {-0.261261, -0.607422, -0.750153},
+ {0.983276, 0.165436, 0.075958},
+ {-0.29837, 0.404083, -0.864655},
+ {-0.638672, 0.507721, 0.578156},
+ {0.388214, 0.412079, 0.824249},
+ {0.556183, -0.208832, 0.804352},
+ {0.778442, 0.562012, 0.27951},
+ {-0.616577, 0.781921, -0.091522},
+ {0.196289, 0.051056, 0.979187},
+ {-0.121216, 0.207153, -0.970734},
+ {-0.173401, -0.384735, 0.906555},
+ {0.161499, -0.723236, -0.671387},
+ {0.178497, -0.006226, -0.983887},
+ {-0.126038, 0.15799, 0.97934},
+ {0.830475, -0.024811, 0.556458},
+ {-0.510132, -0.76944, 0.384247},
+ {0.81424, 0.200104, -0.544891},
+ {-0.112549, -0.393311, -0.912445},
+ {0.56189, 0.152222, -0.813049},
+ {0.198914, -0.254517, -0.946381},
+ {-0.41217, 0.690979, -0.593811},
+ {-0.407257, 0.324524, 0.853668},
+ {-0.690186, 0.366119, -0.624115},
+ {-0.428345, 0.844147, -0.322296},
+ {-0.21228, -0.297546, -0.930756},
+ {-0.273071, 0.516113, 0.811798},
+ {0.928314, 0.371643, 0.007233},
+ {0.785828, -0.479218, -0.390778},
+ {-0.704895, 0.058929, 0.706818},
+ {0.173248, 0.203583, 0.963562},
+ {0.422211, -0.904297, -0.062469},
+ {-0.363312, -0.182465, 0.913605},
+ {0.254028, -0.552307, -0.793945},
+ {-0.28891, -0.765747, -0.574554},
+ {0.058319, 0.291382, 0.954803},
+ {0.946136, -0.303925, 0.111267},
+ {-0.078156, 0.443695, -0.892731},
+ {0.182098, 0.89389, 0.409515},
+ {-0.680298, -0.213318, 0.701141},
+ {0.062469, 0.848389, -0.525635},
+ {-0.72879, -0.641846, 0.238342},
+ {-0.88089, 0.427673, 0.202637},
+ {-0.532501, -0.21405, 0.818878},
+ {0.948975, -0.305084, 0.07962},
+ {0.925446, 0.374664, 0.055817},
+ {0.820923, 0.565491, 0.079102},
+ {0.25882, 0.099792, -0.960724},
+ {-0.294617, 0.910522, 0.289978},
+ {0.137115, 0.320038, -0.937408},
+ {-0.908386, 0.345276, -0.235718},
+ {-0.936218, 0.138763, 0.322754},
+ {0.366577, 0.925934, -0.090637},
+ {0.309296, -0.686829, -0.657684},
+ {0.66983, 0.024445, 0.742065},
+ {-0.917999, -0.059113, -0.392059},
+ {0.365509, 0.462158, -0.807922},
+ {0.083374, 0.996399, -0.014801},
+ {0.593842, 0.253143, -0.763672},
+ {0.974976, -0.165466, 0.148285},
+ {0.918976, 0.137299, 0.369537},
+ {0.294952, 0.694977, 0.655731},
+ {0.943085, 0.152618, -0.295319},
+ {0.58783, -0.598236, 0.544495},
+ {0.203796, 0.678223, 0.705994},
+ {-0.478821, -0.661011, 0.577667},
+ {0.719055, -0.1698, -0.673828},
+ {-0.132172, -0.965332, 0.225006},
+ {-0.981873, -0.14502, 0.121979},
+ {0.763458, 0.579742, 0.284546},
+ {-0.893188, 0.079681, 0.442474},
+ {-0.795776, -0.523804, 0.303802},
+ {0.734955, 0.67804, -0.007446},
+ {0.15506, 0.986267, -0.056183},
+ {0.258026, 0.571503, -0.778931},
+ {-0.681549, -0.702087, -0.206116},
+ {-0.96286, -0.177185, 0.203613},
+ {-0.470978, -0.515106, 0.716095},
+ {-0.740326, 0.57135, 0.354095},
+ {-0.56012, -0.824982, -0.074982},
+ {-0.507874, 0.753204, 0.417969},
+ {-0.503113, 0.038147, 0.863342},
+ {0.594025, 0.673553, -0.439758},
+ {-0.119873, -0.005524, -0.992737},
+ {0.098267, -0.213776, 0.971893},
+ {-0.615631, 0.643951, 0.454163},
+ {0.896851, -0.441071, 0.032166},
+ {-0.555023, 0.750763, -0.358093},
+ {0.398773, 0.304688, 0.864929},
+ {-0.722961, 0.303589, 0.620544},
+ {-0.63559, -0.621948, -0.457306},
+ {-0.293243, 0.072327, 0.953278},
+ {-0.491638, 0.661041, -0.566772},
+ {-0.304199, -0.572083, -0.761688},
+ {0.908081, -0.398956, 0.127014},
+ {-0.523621, -0.549683, -0.650848},
+ {-0.932922, -0.19986, 0.299408},
+ {0.099426, 0.140869, 0.984985},
+ {-0.020325, -0.999756, -0.002319},
+ {0.952667, 0.280853, -0.11615},
+ {-0.971893, 0.082581, 0.220337},
+ {0.65921, 0.705292, -0.260651},
+ {0.733063, -0.175537, 0.657043},
+ {-0.555206, 0.429504, -0.712189},
+ {0.400421, -0.89859, 0.179352},
+ {0.750885, -0.19696, 0.630341},
+ {0.785675, -0.569336, 0.241821},
+ {-0.058899, -0.464111, 0.883789},
+ {0.129608, -0.94519, 0.299622},
+ {-0.357819, 0.907654, 0.219238},
+ {-0.842133, -0.439117, -0.312927},
+ {-0.313477, 0.84433, 0.434479},
+ {-0.241211, 0.053253, 0.968994},
+ {0.063873, 0.823273, 0.563965},
+ {0.476288, 0.862152, -0.172516},
+ {0.620941, -0.298126, 0.724915},
+ {0.25238, -0.749359, -0.612122},
+ {-0.577545, 0.386566, 0.718994},
+ {-0.406342, -0.737976, 0.538696},
+ {0.04718, 0.556305, 0.82959},
+ {-0.802856, 0.587463, 0.101166},
+ {-0.707733, -0.705963, 0.026428},
+ {0.374908, 0.68457, 0.625092},
+ {0.472137, 0.208405, -0.856506},
+ {-0.703064, -0.581085, -0.409821},
+ {-0.417206, -0.736328, 0.532623},
+ {-0.447876, -0.20285, -0.870728},
+ {0.086945, -0.990417, 0.107086},
+ {0.183685, 0.018341, -0.982788},
+ {0.560638, -0.428864, 0.708282},
+ {0.296722, -0.952576, -0.0672},
+ {0.135773, 0.990265, 0.030243},
+ {-0.068787, 0.654724, 0.752686},
+ {0.762604, -0.551758, 0.337585},
+ {-0.819611, -0.407684, 0.402466},
+ {-0.727844, -0.55072, -0.408539},
+ {-0.855774, -0.480011, 0.19281},
+ {0.693176, -0.079285, 0.716339},
+ {0.226013, 0.650116, -0.725433},
+ {0.246704, 0.953369, -0.173553},
+ {-0.970398, -0.239227, -0.03244},
+ {0.136383, -0.394318, 0.908752},
+ {0.813232, 0.558167, 0.164368},
+ {0.40451, 0.549042, -0.731323},
+ {-0.380249, -0.566711, 0.730865},
+ {0.022156, 0.932739, 0.359741},
+ {0.00824, 0.996552, -0.082306},
+ {0.956635, -0.065338, -0.283722},
+ {-0.743561, 0.008209, 0.668579},
+ {-0.859589, -0.509674, 0.035767},
+ {-0.852234, 0.363678, -0.375977},
+ {-0.201965, -0.970795, -0.12915},
+ {0.313477, 0.947327, 0.06546},
+ {-0.254028, -0.528259, 0.81015},
+ {0.628052, 0.601105, 0.49411},
+ {-0.494385, 0.868378, 0.037933},
+ {0.275635, -0.086426, 0.957336},
+ {-0.197937, 0.468903, -0.860748},
+ {0.895599, 0.399384, 0.195801},
+ {0.560791, 0.825012, -0.069214},
+ {0.304199, -0.849487, 0.43103},
+ {0.096375, 0.93576, 0.339111},
+ {-0.051422, 0.408966, -0.911072},
+ {0.330444, 0.942841, -0.042389},
+ {-0.452362, -0.786407, 0.420563},
+ {0.134308, -0.933472, -0.332489},
+ {0.80191, -0.566711, -0.188934},
+ {-0.987946, -0.105988, 0.112518},
+ {-0.24408, 0.892242, -0.379791},
+ {-0.920502, 0.229095, -0.316376},
+ {0.7789, 0.325958, 0.535706},
+ {-0.912872, 0.185211, -0.36377},
+ {-0.184784, 0.565369, -0.803833},
+ {-0.018463, 0.119537, 0.992615},
+ {-0.259247, -0.935608, 0.239532},
+ {-0.82373, -0.449127, -0.345947},
+ {-0.433105, 0.659515, 0.614349},
+ {-0.822754, 0.378845, -0.423676},
+ {0.687195, -0.674835, -0.26889},
+ {-0.246582, -0.800842, 0.545715},
+ {-0.729187, -0.207794, 0.651978},
+ {0.653534, -0.610443, -0.447388},
+ {0.492584, -0.023346, 0.869934},
+ {0.609039, 0.009094, -0.79306},
+ {0.962494, -0.271088, -0.00885},
+ {0.2659, -0.004913, 0.963959},
+ {0.651245, 0.553619, -0.518951},
+ {0.280548, -0.84314, 0.458618},
+ {-0.175293, -0.983215, 0.049805},
+ {0.035339, -0.979919, 0.196045},
+ {-0.982941, 0.164307, -0.082245},
+ {0.233734, -0.97226, -0.005005},
+ {-0.747253, -0.611328, 0.260437},
+ {0.645599, 0.592773, 0.481384},
+ {0.117706, -0.949524, -0.29068},
+ {-0.535004, -0.791901, -0.294312},
+ {-0.627167, -0.214447, 0.748718},
+ {-0.047974, -0.813477, -0.57959},
+ {-0.175537, 0.477264, -0.860992},
+ {0.738556, -0.414246, -0.53183},
+ {0.562561, -0.704071, 0.433289},
+ {-0.754944, 0.64801, -0.100586},
+ {0.114716, 0.044525, -0.992371},
+ {0.966003, 0.244873, -0.082764},
+ {0.33783, 0.715698, -0.611206},
+ {-0.944031, -0.326599, -0.045624},
+};
diff --git a/source/blender/blenlib/intern/psfont.c b/source/blender/blenlib/intern/psfont.c
index cf58f44ad2c..54d7f8ec1af 100644
--- a/source/blender/blenlib/intern/psfont.c
+++ b/source/blender/blenlib/intern/psfont.c
@@ -43,6 +43,8 @@
#include "DNA_packedFile_types.h"
#include "DNA_curve_types.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
@@ -54,7 +56,7 @@ typedef struct chardesc {
short llx, lly; /* bounding box */
short urx, ury;
short *data; /* char data */
- long datalen;
+ intptr_t datalen;
} chardesc;
typedef struct objfnt {
@@ -256,290 +258,290 @@ static int sp;
static int savesplines = 1;
static pschar ISOcharlist[NASCII] = {
- "/space", 040, 0,
- "/exclam", 041, 0,
- "/quotedbl", 042, 0,
- "/numbersign", 043, 0,
- "/dollar", 044, 0,
- "/percent", 045, 0,
- "/ampersand", 046, 0,
- "/quoteright", 047, 0,
-
- "/parenleft", 050, 0,
- "/parenright", 051, 0,
- "/asterisk", 052, 0,
- "/plus", 053, 0,
- "/comma", 054, 0,
- "/hyphen", 055, 0,
- "/period", 056, 0,
- "/slash", 057, 0,
-
- "/zero", 060, 0,
- "/one", 061, 0,
- "/two", 062, 0,
- "/three", 063, 0,
- "/four", 064, 0,
- "/five", 065, 0,
- "/six", 066, 0,
- "/seven", 067, 0,
-
- "/eight", 070, 0,
- "/nine", 071, 0,
- "/colon", 072, 0,
- "/semicolon", 073, 0,
- "/less", 074, 0,
- "/equal", 075, 0,
- "/greater", 076, 0,
- "/question", 077, 0,
-
- "/at", 0100, 0,
- "/A", 0101, 0,
- "/B", 0102, 0,
- "/C", 0103, 0,
- "/D", 0104, 0,
- "/E", 0105, 0,
- "/F", 0106, 0,
- "/G", 0107, 0,
-
- "/H", 0110, 0,
- "/I", 0111, 0,
- "/J", 0112, 0,
- "/K", 0113, 0,
- "/L", 0114, 0,
- "/M", 0115, 0,
- "/N", 0116, 0,
- "/O", 0117, 0,
-
- "/P", 0120, 0,
- "/Q", 0121, 0,
- "/R", 0122, 0,
- "/S", 0123, 0,
- "/T", 0124, 0,
- "/U", 0125, 0,
- "/V", 0126, 0,
- "/W", 0127, 0,
-
- "/X", 0130, 0,
- "/Y", 0131, 0,
- "/Z", 0132, 0,
- "/bracketleft", 0133, 0,
- "/backslash", 0134, 0,
- "/bracketright", 0135, 0,
- "/asciicircum", 0136, 0,
- "/underscore", 0137, 0,
-
- "/quoteleft", 0140, 0,
- "/a", 0141, 0,
- "/b", 0142, 0,
- "/c", 0143, 0,
- "/d", 0144, 0,
- "/e", 0145, 0,
- "/f", 0146, 0,
- "/g", 0147, 0,
-
- "/h", 0150, 0,
- "/i", 0151, 0,
- "/j", 0152, 0,
- "/k", 0153, 0,
- "/l", 0154, 0,
- "/m", 0155, 0,
- "/n", 0156, 0,
- "/o", 0157, 0,
-
- "/p", 0160, 0,
- "/q", 0161, 0,
- "/r", 0162, 0,
- "/s", 0163, 0,
- "/t", 0164, 0,
- "/u", 0165, 0,
- "/v", 0166, 0,
- "/w", 0167, 0,
-
- "/x", 0170, 0,
- "/y", 0171, 0,
- "/z", 0172, 0,
- "/braceleft", 0173, 0,
- "/bar", 0174, 0,
- "/braceright", 0175, 0,
- "/asciitilde", 0176, 0,
- "/", 0177, 0,
+ {"/space", 040, 0},
+ {"/exclam", 041, 0},
+ {"/quotedbl", 042, 0},
+ {"/numbersign", 043, 0},
+ {"/dollar", 044, 0},
+ {"/percent", 045, 0},
+ {"/ampersand", 046, 0},
+ {"/quoteright", 047, 0},
+
+ {"/parenleft", 050, 0},
+ {"/parenright", 051, 0},
+ {"/asterisk", 052, 0},
+ {"/plus", 053, 0},
+ {"/comma", 054, 0},
+ {"/hyphen", 055, 0},
+ {"/period", 056, 0},
+ {"/slash", 057, 0},
+
+ {"/zero", 060, 0},
+ {"/one", 061, 0},
+ {"/two", 062, 0},
+ {"/three", 063, 0},
+ {"/four", 064, 0},
+ {"/five", 065, 0},
+ {"/six", 066, 0},
+ {"/seven", 067, 0},
+
+ {"/eight", 070, 0},
+ {"/nine", 071, 0},
+ {"/colon", 072, 0},
+ {"/semicolon", 073, 0},
+ {"/less", 074, 0},
+ {"/equal", 075, 0},
+ {"/greater", 076, 0},
+ {"/question", 077, 0},
+
+ {"/at", 0100, 0},
+ {"/A", 0101, 0},
+ {"/B", 0102, 0},
+ {"/C", 0103, 0},
+ {"/D", 0104, 0},
+ {"/E", 0105, 0},
+ {"/F", 0106, 0},
+ {"/G", 0107, 0},
+
+ {"/H", 0110, 0},
+ {"/I", 0111, 0},
+ {"/J", 0112, 0},
+ {"/K", 0113, 0},
+ {"/L", 0114, 0},
+ {"/M", 0115, 0},
+ {"/N", 0116, 0},
+ {"/O", 0117, 0},
+
+ {"/P", 0120, 0},
+ {"/Q", 0121, 0},
+ {"/R", 0122, 0},
+ {"/S", 0123, 0},
+ {"/T", 0124, 0},
+ {"/U", 0125, 0},
+ {"/V", 0126, 0},
+ {"/W", 0127, 0},
+
+ {"/X", 0130, 0},
+ {"/Y", 0131, 0},
+ {"/Z", 0132, 0},
+ {"/bracketleft", 0133, 0},
+ {"/backslash", 0134, 0},
+ {"/bracketright", 0135, 0},
+ {"/asciicircum", 0136, 0},
+ {"/underscore", 0137, 0},
+
+ {"/quoteleft", 0140, 0},
+ {"/a", 0141, 0},
+ {"/b", 0142, 0},
+ {"/c", 0143, 0},
+ {"/d", 0144, 0},
+ {"/e", 0145, 0},
+ {"/f", 0146, 0},
+ {"/g", 0147, 0},
+
+ {"/h", 0150, 0},
+ {"/i", 0151, 0},
+ {"/j", 0152, 0},
+ {"/k", 0153, 0},
+ {"/l", 0154, 0},
+ {"/m", 0155, 0},
+ {"/n", 0156, 0},
+ {"/o", 0157, 0},
+
+ {"/p", 0160, 0},
+ {"/q", 0161, 0},
+ {"/r", 0162, 0},
+ {"/s", 0163, 0},
+ {"/t", 0164, 0},
+ {"/u", 0165, 0},
+ {"/v", 0166, 0},
+ {"/w", 0167, 0},
+
+ {"/x", 0170, 0},
+ {"/y", 0171, 0},
+ {"/z", 0172, 0},
+ {"/braceleft", 0173, 0},
+ {"/bar", 0174, 0},
+ {"/braceright", 0175, 0},
+ {"/asciitilde", 0176, 0},
+ {"/", 0177, 0},
/* nonstandard defs */
- "/quotedblleft", 0200, 0,
- "/quotedblright", 0201, 0,
- "/quotedblbase", 0202, 0,
- "/quotesinglbase", 0203, 0,
- "/guilsinglleft", 0204, 0,
- "/guilsinglright", 0205, 0,
- "/endash", 0206, 0,
- "/dagger", 0207, 0,
-
- "/daggerdbl", 0210, 0,
- "/trademark", 0211, 0,
- "/bullet", 0212, 0,
- "/perthousand", 0213, 0,
- "/Lslash", 0214, 0,
- "/OE", 0215, 0,
- "/lslash", 0216, 0,
- "/oe", 0217, 0,
+ {"/quotedblleft", 0200, 0},
+ {"/quotedblright", 0201, 0},
+ {"/quotedblbase", 0202, 0},
+ {"/quotesinglbase", 0203, 0},
+ {"/guilsinglleft", 0204, 0},
+ {"/guilsinglright", 0205, 0},
+ {"/endash", 0206, 0},
+ {"/dagger", 0207, 0},
+
+ {"/daggerdbl", 0210, 0},
+ {"/trademark", 0211, 0},
+ {"/bullet", 0212, 0},
+ {"/perthousand", 0213, 0},
+ {"/Lslash", 0214, 0},
+ {"/OE", 0215, 0},
+ {"/lslash", 0216, 0},
+ {"/oe", 0217, 0},
/* endnonstandard defs */
- "/dotlessi", 0220, 0,
- "/grave", 0221, 0,
- "/acute", 0222, 0,
- "/circumflex", 0223, 0,
- "/tilde", 0224, 0,
- "/", 0225, 0,
- "/breve", 0226, 0,
- "/dotaccent", 0227, 0,
-
- "/", 0230, 0,
- "/", 0231, 0,
- "/ring", 0232, 0,
- "/", 0233, 0,
- "/", 0234, 0,
- "/hungarumlaut", 0235, 0,
- "/ogonek", 0236, 0,
- "/caron", 0237, 0,
-
- "/", 0240, 0,
- "/exclamdown", 0241, 0,
- "/cent", 0242, 0,
- "/sterling", 0243, 0,
- "/florin", 0244, 0,
- "/yen", 0245, 0,
- "/brokenbar", 0246, 0,
- "/section", 0247, 0,
-
- "/dieresis", 0250, 0,
- "/copyright", 0251, 0,
- "/ordfeminine", 0252, 0,
- "/guillemotleft", 0253, 0,
- "/logicalnot", 0254, 0,
- "/hyphen", 0255, 0,
- "/registered", 0256, 0,
- "/macron", 0257, 0,
-
- "/degree", 0260, 0,
- "/plusminus", 0261, 0,
- "/twosuperior", 0262, 0,
- "/threesuperior", 0263, 0,
- "/acute", 0264, 0,
- "/mu", 0265, 0,
- "/paragraph", 0266, 0,
- "/periodcentered", 0267, 0,
-
- "/cedilla", 0270, 0,
- "/onesuperior", 0271, 0,
- "/ordmasculine", 0272, 0,
- "/guillemotright", 0273, 0,
- "/onequarter", 0274, 0,
- "/onehalf", 0275, 0,
- "/threequarters", 0276, 0,
- "/questiondown", 0277, 0,
-
- "/Agrave", 0300, 0,
- "/Aacute", 0301, 0,
- "/Acircumflex", 0302, 0,
- "/Atilde", 0303, 0,
- "/Adieresis", 0304, 0,
- "/Aring", 0305, 0,
- "/AE", 0306, 0,
- "/Ccedilla", 0307, 0,
-
- "/Egrave", 0310, 0,
- "/Eacute", 0311, 0,
- "/Ecircumflex", 0312, 0,
- "/Edieresis", 0313, 0,
- "/Igrave", 0314, 0,
- "/Iacute", 0315, 0,
- "/Icircumflex", 0316, 0,
- "/Idieresis", 0317, 0,
-
- "/Eth", 0320, 0,
- "/Ntilde", 0321, 0,
- "/Ograve", 0322, 0,
- "/Oacute", 0323, 0,
- "/Ocircumflex", 0324, 0,
- "/Otilde", 0325, 0,
- "/Odieresis", 0326, 0,
- "/multiply", 0327, 0,
-
- "/Oslash", 0330, 0,
- "/Ugrave", 0331, 0,
- "/Uacute", 0332, 0,
- "/Ucircumflex", 0333, 0,
- "/Udieresis", 0334, 0,
- "/Yacute", 0335, 0,
- "/Thorn", 0336, 0,
- "/germandbls", 0337, 0,
-
- "/agrave", 0340, 0,
- "/aacute", 0341, 0,
- "/acircumflex", 0342, 0,
- "/atilde", 0343, 0,
- "/adieresis", 0344, 0,
- "/aring", 0345, 0,
- "/ae", 0346, 0,
- "/ccedilla", 0347, 0,
-
- "/egrave", 0350, 0,
- "/eacute", 0351, 0,
- "/ecircumflex", 0352, 0,
- "/edieresis", 0353, 0,
- "/igrave", 0354, 0,
- "/iacute", 0355, 0,
- "/icircumflex", 0356, 0,
- "/idieresis", 0357, 0,
-
- "/eth", 0360, 0,
- "/ntilde", 0361, 0,
- "/ograve", 0362, 0,
- "/oacute", 0363, 0,
- "/ocircumflex", 0364, 0,
- "/otilde", 0365, 0,
- "/odieresis", 0366, 0,
- "/divide", 0367, 0,
-
- "/oslash", 0370, 0,
- "/ugrave", 0371, 0,
- "/uacute", 0372, 0,
- "/ucircumflex", 0373, 0,
- "/udieresis", 0374, 0,
- "/yacute", 0375, 0,
- "/thorn", 0376, 0,
- "/ydieresis", 0377, 0,
+ {"/dotlessi", 0220, 0},
+ {"/grave", 0221, 0},
+ {"/acute", 0222, 0},
+ {"/circumflex", 0223, 0},
+ {"/tilde", 0224, 0},
+ {"/", 0225, 0},
+ {"/breve", 0226, 0},
+ {"/dotaccent", 0227, 0},
+
+ {"/", 0230, 0},
+ {"/", 0231, 0},
+ {"/ring", 0232, 0},
+ {"/", 0233, 0},
+ {"/", 0234, 0},
+ {"/hungarumlaut", 0235, 0},
+ {"/ogonek", 0236, 0},
+ {"/caron", 0237, 0},
+
+ {"/", 0240, 0},
+ {"/exclamdown", 0241, 0},
+ {"/cent", 0242, 0},
+ {"/sterling", 0243, 0},
+ {"/florin", 0244, 0},
+ {"/yen", 0245, 0},
+ {"/brokenbar", 0246, 0},
+ {"/section", 0247, 0},
+
+ {"/dieresis", 0250, 0},
+ {"/copyright", 0251, 0},
+ {"/ordfeminine", 0252, 0},
+ {"/guillemotleft", 0253, 0},
+ {"/logicalnot", 0254, 0},
+ {"/hyphen", 0255, 0},
+ {"/registered", 0256, 0},
+ {"/macron", 0257, 0},
+
+ {"/degree", 0260, 0},
+ {"/plusminus", 0261, 0},
+ {"/twosuperior", 0262, 0},
+ {"/threesuperior", 0263, 0},
+ {"/acute", 0264, 0},
+ {"/mu", 0265, 0},
+ {"/paragraph", 0266, 0},
+ {"/periodcentered", 0267, 0},
+
+ {"/cedilla", 0270, 0},
+ {"/onesuperior", 0271, 0},
+ {"/ordmasculine", 0272, 0},
+ {"/guillemotright", 0273, 0},
+ {"/onequarter", 0274, 0},
+ {"/onehalf", 0275, 0},
+ {"/threequarters", 0276, 0},
+ {"/questiondown", 0277, 0},
+
+ {"/Agrave", 0300, 0},
+ {"/Aacute", 0301, 0},
+ {"/Acircumflex", 0302, 0},
+ {"/Atilde", 0303, 0},
+ {"/Adieresis", 0304, 0},
+ {"/Aring", 0305, 0},
+ {"/AE", 0306, 0},
+ {"/Ccedilla", 0307, 0},
+
+ {"/Egrave", 0310, 0},
+ {"/Eacute", 0311, 0},
+ {"/Ecircumflex", 0312, 0},
+ {"/Edieresis", 0313, 0},
+ {"/Igrave", 0314, 0},
+ {"/Iacute", 0315, 0},
+ {"/Icircumflex", 0316, 0},
+ {"/Idieresis", 0317, 0},
+
+ {"/Eth", 0320, 0},
+ {"/Ntilde", 0321, 0},
+ {"/Ograve", 0322, 0},
+ {"/Oacute", 0323, 0},
+ {"/Ocircumflex", 0324, 0},
+ {"/Otilde", 0325, 0},
+ {"/Odieresis", 0326, 0},
+ {"/multiply", 0327, 0},
+
+ {"/Oslash", 0330, 0},
+ {"/Ugrave", 0331, 0},
+ {"/Uacute", 0332, 0},
+ {"/Ucircumflex",0333, 0},
+ {"/Udieresis", 0334, 0},
+ {"/Yacute", 0335, 0},
+ {"/Thorn", 0336, 0},
+ {"/germandbls", 0337, 0},
+
+ {"/agrave", 0340, 0},
+ {"/aacute", 0341, 0},
+ {"/acircumflex",0342, 0},
+ {"/atilde", 0343, 0},
+ {"/adieresis", 0344, 0},
+ {"/aring", 0345, 0},
+ {"/ae", 0346, 0},
+ {"/ccedilla", 0347, 0},
+
+ {"/egrave", 0350, 0},
+ {"/eacute", 0351, 0},
+ {"/ecircumflex", 0352, 0},
+ {"/edieresis", 0353, 0},
+ {"/igrave", 0354, 0},
+ {"/iacute", 0355, 0},
+ {"/icircumflex", 0356, 0},
+ {"/idieresis", 0357, 0},
+
+ {"/eth", 0360, 0},
+ {"/ntilde", 0361, 0},
+ {"/ograve", 0362, 0},
+ {"/oacute", 0363, 0},
+ {"/ocircumflex",0364, 0},
+ {"/otilde", 0365, 0},
+ {"/odieresis", 0366, 0},
+ {"/divide", 0367, 0},
+
+ {"/oslash", 0370, 0},
+ {"/ugrave", 0371, 0},
+ {"/uacute", 0372, 0},
+ {"/ucircumflex",0373, 0},
+ {"/udieresis", 0374, 0},
+ {"/yacute", 0375, 0},
+ {"/thorn", 0376, 0},
+ {"/ydieresis", 0377, 0},
};
static short STDvsISO [][2] = {
- 0341, 0306, /* AE */
- 0351, 0330, /* Oslash */
- 0302, 0222, /* acute */
- 0361, 0346, /* ae */
- 0306, 0226, /* breve */
- 0317, 0237, /* caron */
- 0313, 0270, /* cedilla */
- 0303, 0223, /* circumflex */
- 0250, 0244, /* currency */
- 0310, 0250, /* dieresis */
- 0307, 0227, /* dotaccent */
- 0365, 0220, /* dotlessi */
- 0373, 0337, /* germandbls */
- 0301, 0221, /* grave */
- 0315, 0235, /* hungarumlaut */
- 0055, 0255, /* hyphen */
- 0305, 0257, /* macron */
- 0316, 0236, /* ogenek */
- 0343, 0252, /* ordfeminine */
- 0353, 0272, /* ordmasculine */
- 0371, 0370, /* oslash */
- 0264, 0267, /* periodcentered */
- 0312, 0232, /* ring */
- 0304, 0224, /* tilde */
+ {0341, 0306}, /* AE */
+ {0351, 0330}, /* Oslash */
+ {0302, 0222}, /* acute */
+ {0361, 0346}, /* ae */
+ {0306, 0226}, /* breve */
+ {0317, 0237}, /* caron */
+ {0313, 0270}, /* cedilla */
+ {0303, 0223}, /* circumflex */
+ {0250, 0244}, /* currency */
+ {0310, 0250}, /* dieresis */
+ {0307, 0227}, /* dotaccent */
+ {0365, 0220}, /* dotlessi */
+ {0373, 0337}, /* germandbls */
+ {0301, 0221}, /* grave */
+ {0315, 0235}, /* hungarumlaut */
+ {0055, 0255}, /* hyphen */
+ {0305, 0257}, /* macron */
+ {0316, 0236}, /* ogenek */
+ {0343, 0252}, /* ordfeminine */
+ {0353, 0272}, /* ordmasculine */
+ {0371, 0370}, /* oslash */
+ {0264, 0267}, /* periodcentered */
+ {0312, 0232}, /* ring */
+ {0304, 0224}, /* tilde */
};
/* from objfont.c, rest is in lfm_s !!*/
@@ -975,7 +977,7 @@ static void applymat(float mat[][2], float *x, float *y)
static void setcharlist(void)
{
- char *name, found;
+ char *name; /*found;*/
int i, j;
for(i=0; i<NASCII; i++) ISOcharlist[i].prog = -1;
@@ -983,11 +985,11 @@ static void setcharlist(void)
for(j=0; j<my_nchars; j++) {
name = my_charname[j];
if(name) {
- found = 0;
+ /*found = 0;*/
for(i=0; i<NASCII; i++) {
if(ISOcharlist[i].name && (strcmp(name,ISOcharlist[i].name) == 0)){
ISOcharlist[i].prog = j;
- found = 1;
+ /*found = 1;*/
}
}
/*if (found == 0) printf("no match found for: %s\n", name);*/
@@ -1256,10 +1258,10 @@ static void subr0(void)
int x1, y1;
int x2, y2;
int x3, y3;
- int xpos, ypos, noise;
+ int noise;
- ypos = pop();
- xpos = pop();
+ pop(); /* xpos, unused */
+ pop(); /* ypos, unused */
noise = pop();
if(coordpos!=7) {
fprintf(stderr,"subr0: bad poop\n");
@@ -1946,7 +1948,7 @@ static VFontData *objfnt_to_vfontdata(objfnt *fnt)
chardesc *cd;
short *_data, *data;
int a, i, count, stop, ready, meet;
- short first[2], last[2];
+ short first[2]={0,0}, last[2]={0,0};
struct Nurb *nu;
struct BezTriple *bezt, *bez2;
float scale, dx, dy;
@@ -2017,7 +2019,7 @@ static VFontData *objfnt_to_vfontdata(objfnt *fnt)
nu->type= CU_BEZIER+CU_2D;
nu->pntsu = count;
nu->resolu= 8;
- nu->flagu= 1;
+ nu->flagu= CU_CYCLIC;
nu->bezt = bezt;
stop = 0;
diff --git a/source/blender/blenlib/intern/rand.c b/source/blender/blenlib/intern/rand.c
index ccc478203fe..c484a307393 100644
--- a/source/blender/blenlib/intern/rand.c
+++ b/source/blender/blenlib/intern/rand.c
@@ -81,6 +81,16 @@ void rng_seed(RNG *rng, unsigned int seed) {
rng->X= (((r_uint64) seed)<<16) | LOWSEED;
}
+void rng_srandom(RNG *rng, unsigned int seed) {
+ extern unsigned char hash[]; // noise.c
+
+ rng_seed(rng, seed + hash[seed & 255]);
+ seed= rng_getInt(rng);
+ rng_seed(rng, seed + hash[seed & 255]);
+ seed= rng_getInt(rng);
+ rng_seed(rng, seed + hash[seed & 255]);
+}
+
int rng_getInt(RNG *rng) {
rng->X= (MULTIPLIER*rng->X + ADDEND)&MASK;
return (int) (rng->X>>17);
@@ -132,13 +142,7 @@ void BLI_srand(unsigned int seed) {
/* using hash table to create better seed */
void BLI_srandom(unsigned int seed) {
- extern unsigned char hash[]; // noise.c
-
- rng_seed(&theBLI_rng, seed + hash[seed & 255]);
- seed= rng_getInt(&theBLI_rng);
- rng_seed(&theBLI_rng, seed + hash[seed & 255]);
- seed= rng_getInt(&theBLI_rng);
- rng_seed(&theBLI_rng, seed + hash[seed & 255]);
+ rng_srandom(&theBLI_rng, seed);
}
int BLI_rand(void) {
diff --git a/source/blender/blenlib/intern/storage.c b/source/blender/blenlib/intern/storage.c
index 6e64a98af2a..ca7a376d3a2 100644
--- a/source/blender/blenlib/intern/storage.c
+++ b/source/blender/blenlib/intern/storage.c
@@ -47,7 +47,9 @@
#include <time.h>
#include <sys/stat.h>
-#if !defined(linux) && (defined(__sgi) || defined(__sun__) || defined(__sun) || defined(__sparc) || defined(__sparc__))
+#if defined (__sun__) || defined (__sun)
+#include <sys/statvfs.h> /* Other modern unix os's should probably use this also */
+#elif !defined(__FreeBSD__) && !defined(linux) && (defined(__sgi) || defined(__sparc) || defined(__sparc__))
#include <sys/statfs.h>
#endif
@@ -176,7 +178,12 @@ double BLI_diskfree(char *dir)
return (double) (freec*bytesps*sectorspc);
#else
+
+#if defined (__sun__) || defined (__sun)
+ struct statvfs disk;
+#else
struct statfs disk;
+#endif
char name[FILE_MAXDIR],*slash;
int len = strlen(dir);
@@ -196,12 +203,12 @@ double BLI_diskfree(char *dir)
#ifdef __BeOS
return -1;
#endif
-#if !defined(linux) && (defined (__sgi) || defined (__sun__) || defined (__sun) || defined(__sparc) || defined(__sparc__))
- if (statfs(name, &disk, sizeof(struct statfs), 0)){
- /* printf("diskfree: Couldn't get information about %s.\n",dir); */
- return(-1);
- }
+#if defined (__sun__) || defined (__sun)
+ if (statvfs(name, &disk)) return(-1);
+#elif !defined(__FreeBSD__) && !defined(linux) && (defined (__sgi) || defined(__sparc) || defined(__sparc__))
+ /* WARNING - This may not be supported by geeneric unix os's - Campbell */
+ if (statfs(name, &disk, sizeof(struct statfs), 0)) return(-1);
#endif
return ( ((double) disk.f_bsize) * ((double) disk.f_bfree));
@@ -326,11 +333,11 @@ void BLI_adddirstrings()
char size[250];
static char * types[8] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
int num, mode;
- int num1, num2, num3, num4;
+ off_t num1, num2, num3, num4, num5;
#ifdef WIN32
__int64 st_size;
#else
- long long st_size;
+ off_t st_size;
#endif
struct direntry * file;
@@ -392,7 +399,7 @@ void BLI_adddirstrings()
* will buy us some time until files get bigger than 4GB or until
* everyone starts using __USE_FILE_OFFSET64 or equivalent.
*/
- st_size= (unsigned int)files[num].s.st_size;
+ st_size= (off_t)files[num].s.st_size;
num1= st_size % 1000;
num2= st_size/1000;
@@ -401,11 +408,15 @@ void BLI_adddirstrings()
num3= num3 % 1000;
num4= st_size/(1000*1000*1000);
num4= num4 % 1000;
-
- if(num4) sprintf(files[num].size, "%3d %03d %03d %03d", num4, num3, num2, num1);
- else if(num3) sprintf(files[num].size, "%7d %03d %03d", num3, num2, num1);
- else if(num2) sprintf(files[num].size, "%11d %03d", num2, num1);
- else if(num1) sprintf(files[num].size, "%15d", num1);
+ num5= st_size/(1000000000000LL);
+ num5= num5 % 1000;
+
+ if(num5)
+ sprintf(files[num].size, "%1d %03d %03d %03d K", (int)num5, (int)num4, (int)num3, (int)num2);
+ else if(num4) sprintf(files[num].size, "%3d %03d %03d %03d", (int)num4, (int)num3, (int)num2, (int)num1);
+ else if(num3) sprintf(files[num].size, "%7d %03d %03d", (int)num3, (int)num2, (int)num1);
+ else if(num2) sprintf(files[num].size, "%11d %03d", (int)num2, (int)num1);
+ else if(num1) sprintf(files[num].size, "%15d", (int)num1);
else sprintf(files[num].size, "0");
strftime(datum, 32, "%d-%b-%y %H:%M", tm);
@@ -469,6 +480,17 @@ int BLI_filesize(int file)
return (buf.st_size);
}
+int BLI_filepathsize(const char *path)
+{
+ int size, file = open(path, O_BINARY|O_RDONLY);
+
+ if (file <= 0)
+ return -1;
+
+ size = BLI_filesize(file);
+ close(file);
+ return size;
+}
int BLI_exist(char *name)
diff --git a/source/blender/blenlib/intern/threads.c b/source/blender/blenlib/intern/threads.c
index 1f05070b034..9df8bbc81e3 100644
--- a/source/blender/blenlib/intern/threads.c
+++ b/source/blender/blenlib/intern/threads.c
@@ -1,6 +1,6 @@
/**
*
- * $Id:
+ * $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -38,6 +38,17 @@
#include "BLI_blenlib.h"
#include "BLI_threads.h"
+#include "PIL_time.h"
+
+/* for checking system threads - BLI_system_thread_count */
+#ifdef WIN32
+#include "Windows.h"
+#elif defined(__APPLE__)
+#include <sys/types.h>
+#include <sys/sysctl.h>
+#else
+#include <unistd.h>
+#endif
/* ********** basic thread control API ************
@@ -190,6 +201,34 @@ void BLI_remove_thread(ListBase *threadbase, void *callerdata)
}
}
+void BLI_remove_thread_index(ListBase *threadbase, int index)
+{
+ ThreadSlot *tslot;
+ int counter=0;
+
+ for(tslot = threadbase->first; tslot; tslot = tslot->next, counter++) {
+ if (counter == index && tslot->avail == 0) {
+ tslot->callerdata = NULL;
+ pthread_join(tslot->pthread, NULL);
+ tslot->avail = 1;
+ break;
+ }
+ }
+}
+
+void BLI_remove_threads(ListBase *threadbase)
+{
+ ThreadSlot *tslot;
+
+ for(tslot = threadbase->first; tslot; tslot = tslot->next) {
+ if (tslot->avail == 0) {
+ tslot->callerdata = NULL;
+ pthread_join(tslot->pthread, NULL);
+ tslot->avail = 1;
+ }
+ }
+}
+
void BLI_end_threads(ListBase *threadbase)
{
ThreadSlot *tslot;
@@ -224,4 +263,136 @@ void BLI_unlock_thread(int type)
pthread_mutex_unlock(&_custom1_lock);
}
+/* how many threads are native on this system? */
+int BLI_system_thread_count( void )
+{
+ int t;
+#ifdef WIN32
+ SYSTEM_INFO info;
+ GetSystemInfo(&info);
+ t = (int) info.dwNumberOfProcessors;
+#else
+# ifdef __APPLE__
+ int mib[2];
+ size_t len;
+
+ mib[0] = CTL_HW;
+ mib[1] = HW_NCPU;
+ len = sizeof(t);
+ sysctl(mib, 2, &t, &len, NULL, 0);
+# elif defined(__sgi)
+ t = sysconf(_SC_NPROC_ONLN);
+# else
+ t = (int)sysconf(_SC_NPROCESSORS_ONLN);
+# endif
+#endif
+
+ if (t>RE_MAX_THREAD)
+ return RE_MAX_THREAD;
+ if (t<1)
+ return 1;
+
+ return t;
+}
+
+/* ************************************************ */
+
+typedef struct ThreadedWorker {
+ ListBase threadbase;
+ void *(*work_fnct)(void *);
+ char busy[RE_MAX_THREAD];
+ int total;
+ int sleep_time;
+} ThreadedWorker;
+
+typedef struct WorkParam {
+ ThreadedWorker *worker;
+ void *param;
+ int index;
+} WorkParam;
+
+void *exec_work_fnct(void *v_param)
+{
+ WorkParam *p = (WorkParam*)v_param;
+ void *value;
+
+ value = p->worker->work_fnct(p->param);
+
+ p->worker->busy[p->index] = 0;
+ MEM_freeN(p);
+
+ return value;
+}
+
+ThreadedWorker *BLI_create_worker(void *(*do_thread)(void *), int tot, int sleep_time)
+{
+ ThreadedWorker *worker;
+
+ worker = MEM_callocN(sizeof(ThreadedWorker), "threadedworker");
+
+ if (tot > RE_MAX_THREAD)
+ {
+ tot = RE_MAX_THREAD;
+ }
+ else if (tot < 1)
+ {
+ tot= 1;
+ }
+
+ worker->total = tot;
+ worker->work_fnct = do_thread;
+
+ BLI_init_threads(&worker->threadbase, exec_work_fnct, tot);
+
+ return worker;
+}
+
+void BLI_end_worker(ThreadedWorker *worker)
+{
+ BLI_remove_threads(&worker->threadbase);
+}
+
+void BLI_destroy_worker(ThreadedWorker *worker)
+{
+ BLI_end_worker(worker);
+ BLI_freelistN(&worker->threadbase);
+ MEM_freeN(worker);
+}
+
+void BLI_insert_work(ThreadedWorker *worker, void *param)
+{
+ WorkParam *p = MEM_callocN(sizeof(WorkParam), "workparam");
+ int index;
+
+ if (BLI_available_threads(&worker->threadbase) == 0)
+ {
+ index = worker->total;
+ while(index == worker->total)
+ {
+ PIL_sleep_ms(worker->sleep_time);
+
+ for (index = 0; index < worker->total; index++)
+ {
+ if (worker->busy[index] == 0)
+ {
+ BLI_remove_thread_index(&worker->threadbase, index);
+ break;
+ }
+ }
+ }
+ }
+ else
+ {
+ index = BLI_available_thread_index(&worker->threadbase);
+ }
+
+ worker->busy[index] = 1;
+
+ p->param = param;
+ p->index = index;
+ p->worker = worker;
+
+ BLI_insert_thread(&worker->threadbase, p);
+}
+
/* eof */
diff --git a/source/blender/blenlib/intern/util.c b/source/blender/blenlib/intern/util.c
index 97ed881fcc8..d3cfdf6417c 100644
--- a/source/blender/blenlib/intern/util.c
+++ b/source/blender/blenlib/intern/util.c
@@ -38,11 +38,14 @@
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
+#include <math.h> /* for log10 */
#include "MEM_guardedalloc.h"
-#include "BLI_blenlib.h"
#include "DNA_listBase.h"
+#include "DNA_userdef_types.h"
+
+#include "BLI_blenlib.h"
#include "BLI_storage.h"
#include "BLI_storage_types.h"
#include "BLI_dynamiclist.h"
@@ -62,6 +65,14 @@
#endif
#ifdef WIN32
+
+#ifdef _WIN32_IE
+#undef _WIN32_IE
+#endif
+#define _WIN32_IE 0x0501
+#include <windows.h>
+#include <shlobj.h>
+
#include "BLI_winstuff.h"
/* for duplicate_defgroup */
@@ -81,6 +92,10 @@
#include <CoreFoundation/CoreFoundation.h>
#endif
+#ifdef __linux__
+#include "binreloc.h"
+#endif
+
/* local */
static int add_win32_extension(char *name);
@@ -213,6 +228,79 @@ void BLI_newname(char *name, int add)
BLI_stringenc(name, head, tail, digits, pic);
}
+/* little helper macro for BLI_uniquename */
+#ifndef GIVE_STRADDR
+ #define GIVE_STRADDR(data, offset) ( ((char *)data) + offset )
+#endif
+
+/* Generic function to set a unique name. It is only designed to be used in situations
+ * where the name is part of the struct, and also that the name is at most 128 chars long.
+ *
+ * For places where this is used, see constraint.c for example...
+ *
+ * name_offs: should be calculated using offsetof(structname, membername) macro from stddef.h
+ * len: maximum length of string (to prevent overflows, etc.)
+ * defname: the name that should be used by default if none is specified already
+ */
+void BLI_uniquename(ListBase *list, void *vlink, char defname[], short name_offs, short len)
+{
+ Link *link;
+ char tempname[128];
+ int number = 1, exists = 0;
+ char *dot;
+
+ /* Make sure length can be handled */
+ if ((len < 0) || (len > 128))
+ return;
+
+ /* See if we are given an empty string */
+ if (ELEM(NULL, vlink, defname))
+ return;
+
+ if (GIVE_STRADDR(vlink, name_offs) == '\0') {
+ /* give it default name first */
+ BLI_strncpy(GIVE_STRADDR(vlink, name_offs), defname, len);
+ }
+
+ /* See if we even need to do this */
+ if (list == NULL)
+ return;
+
+ for (link = list->first; link; link= link->next) {
+ if (link != vlink) {
+ if (!strcmp(GIVE_STRADDR(link, name_offs), GIVE_STRADDR(vlink, name_offs))) {
+ exists = 1;
+ break;
+ }
+ }
+ }
+ if (exists == 0)
+ return;
+
+ /* Strip off the suffix */
+ dot = strchr(GIVE_STRADDR(vlink, name_offs), '.');
+ if (dot)
+ *dot=0;
+
+ for (number = 1; number <= 999; number++) {
+ BLI_snprintf(tempname, 128, "%s.%03d", GIVE_STRADDR(vlink, name_offs), number);
+
+ exists = 0;
+ for (link= list->first; link; link= link->next) {
+ if (vlink != link) {
+ if (!strcmp(GIVE_STRADDR(link, name_offs), tempname)) {
+ exists = 1;
+ break;
+ }
+ }
+ }
+ if (exists == 0) {
+ BLI_strncpy(GIVE_STRADDR(vlink, name_offs), tempname, len);
+ return;
+ }
+ }
+}
+
void BLI_addhead(ListBase *listbase, void *vlink)
{
@@ -787,17 +875,45 @@ int BLI_strcaseeq(char *a, char *b) {
* take the dir name, make it absolute, and clean it up, replacing
* excess file entry stuff (like /tmp/../tmp/../)
* note that dir isn't protected for max string names...
+ *
+ * If relbase is NULL then its ignored
*/
void BLI_cleanup_dir(const char *relabase, char *dir)
{
+ BLI_cleanup_file(relabase, dir);
+ BLI_add_slash(dir);
+
+}
+
+void BLI_cleanup_file(const char *relabase, char *dir)
+{
short a;
char *start, *eind;
+ if (relabase) {
+ BLI_convertstringcode(dir, relabase);
+ } else {
+ if (dir[0]=='/' && dir[1]=='/') {
+ if (dir[2]== '\0') {
+ return; /* path is "//" - cant clean it */
+ }
+ dir = dir+2; /* skip the first // */
+ }
+ }
- BLI_convertstringcode(dir, relabase, 0);
+ /* Note
+ * memmove( start, eind, strlen(eind)+1 );
+ * is the same as
+ * strcpy( start, eind );
+ * except strcpy should not be used because there is overlap,
+ * so use memmove's slightly more obscure syntax - Campbell
+ */
#ifdef WIN32
- if(dir[0]=='.') { /* happens for example in FILE_MAIN */
+
+ /* Note, this should really be moved to the file selector,
+ * since this function is used in many areas */
+ if(strcmp(dir, ".")==0) { /* happens for example in FILE_MAIN */
get_default_root(dir);
return;
}
@@ -809,17 +925,21 @@ void BLI_cleanup_dir(const char *relabase, char *dir)
if (dir[a] == '\\') break;
a--;
}
- strcpy(dir+a,eind);
+ if (a<0) {
+ break;
+ } else {
+ memmove( dir+a, eind, strlen(eind)+1 );
+ }
}
while ( (start = strstr(dir,"\\.\\")) ){
eind = start + strlen("\\.\\") - 1;
- strcpy(start,eind);
+ memmove( start, eind, strlen(eind)+1 );
}
while ( (start = strstr(dir,"\\\\" )) ){
eind = start + strlen("\\\\") - 1;
- strcpy(start,eind);
+ memmove( start, eind, strlen(eind)+1 );
}
if((a = strlen(dir))){ /* remove the '\\' at the end */
@@ -828,9 +948,7 @@ void BLI_cleanup_dir(const char *relabase, char *dir)
dir[a] = 0;
}
}
-
- strcat(dir, "\\");
-#else
+#else
if(dir[0]=='.') { /* happens, for example in FILE_MAIN */
dir[0]= '/';
dir[1]= 0;
@@ -844,17 +962,21 @@ void BLI_cleanup_dir(const char *relabase, char *dir)
if (dir[a] == '/') break;
a--;
}
- strcpy(dir+a,eind);
+ if (a<0) {
+ break;
+ } else {
+ memmove( dir+a, eind, strlen(eind)+1 );
+ }
}
while ( (start = strstr(dir,"/./")) ){
eind = start + strlen("/./") - 1;
- strcpy(start,eind);
+ memmove( start, eind, strlen(eind)+1 );
}
while ( (start = strstr(dir,"//" )) ){
eind = start + strlen("//") - 1;
- strcpy(start,eind);
+ memmove( start, eind, strlen(eind)+1 );
}
if( (a = strlen(dir)) ){ /* remove all '/' at the end */
@@ -864,8 +986,6 @@ void BLI_cleanup_dir(const char *relabase, char *dir)
if (a<=0) break;
}
}
-
- strcat(dir, "/");
#endif
}
@@ -877,7 +997,7 @@ void BLI_makestringcode(const char *relfile, char *file)
char * lslash;
char temp[FILE_MAXDIR+FILE_MAXFILE];
char res[FILE_MAXDIR+FILE_MAXFILE];
-
+
/* if file is already relative, bail out */
if(file[0]=='/' && file[1]=='/') return;
@@ -909,7 +1029,11 @@ void BLI_makestringcode(const char *relfile, char *file)
BLI_char_switch(temp, '\\', '/');
BLI_char_switch(file, '\\', '/');
-
+
+ /* remove /./ which confuse the following slash counting... */
+ BLI_cleanup_file(NULL, file);
+ BLI_cleanup_file(NULL, temp);
+
/* the last slash in the file indicates where the path part ends */
lslash = BLI_last_slash(temp);
@@ -954,17 +1078,104 @@ void BLI_makestringcode(const char *relfile, char *file)
}
}
-int BLI_convertstringcode(char *path, const char *basepath, int framenum)
+int BLI_parent_dir(char *path)
{
- int len, wasrelative;
- char tmp[FILE_MAXDIR+FILE_MAXFILE];
- char base[FILE_MAXDIR];
- char vol[3] = {'\0', '\0', '\0'};
+#ifdef WIN32
+ static char *parent_dir="..\\";
+#else
+ static char *parent_dir="../";
+#endif
+ char tmp[FILE_MAXDIR+FILE_MAXFILE+4];
+ BLI_strncpy(tmp, path, sizeof(tmp));
+ BLI_add_slash(tmp);
+ strcat(tmp, parent_dir);
+ BLI_cleanup_dir(NULL, tmp);
+
+ if (!BLI_testextensie(tmp, parent_dir)) {
+ BLI_strncpy(path, tmp, sizeof(tmp));
+ return 1;
+ } else {
+ return 0;
+ }
+}
+
+int BLI_convertstringframe(char *path, int frame)
+{
+ int ch_sta, ch_end, i;
+ /* Insert current frame: file### -> file001 */
+ ch_sta = ch_end = 0;
+ for (i = 0; path[i] != '\0'; i++) {
+ if (path[i] == '\\' || path[i] == '/') {
+ ch_end = 0; /* this is a directory name, dont use any hashes we found */
+ } else if (path[i] == '#') {
+ ch_sta = i;
+ ch_end = ch_sta+1;
+ while (path[ch_end] == '#') {
+ ch_end++;
+ }
+ i = ch_end-1; /* keep searching */
+
+ /* dont break, there may be a slash after this that invalidates the previous #'s */
+ }
+ }
+ if (ch_end) { /* warning, ch_end is the last # +1 */
+ /* Add the frame number? */
+ short numlen, hashlen;
+ char tmp[FILE_MAX];
+
+ char format[16]; /* 6 is realistically the maxframe (300000), so 8 should be enough, but 16 to be safe. */
+ if (((ch_end-1)-ch_sta) >= 16) {
+ ch_end = ch_sta+15; /* disallow values longer then 'format' can hold */
+ }
+
+ strcpy(tmp, path);
+
+ numlen = 1 + (int)log10((double)frame); /* this is the number of chars in the number */
+ hashlen = ch_end - ch_sta;
+
+ sprintf(format, "%d", frame);
+
+ if (numlen==hashlen) { /* simple case */
+ memcpy(tmp+ch_sta, format, numlen);
+ } else if (numlen < hashlen) {
+ memcpy(tmp+ch_sta + (hashlen-numlen), format, numlen); /*dont copy the string terminator */
+ memset(tmp+ch_sta, '0', hashlen-numlen);
+ } else {
+ /* number is longer then number of #'s */
+ if (tmp[ch_end] == '\0') { /* hashes are last, no need to move any string*/
+ /* bad juju - not testing string length here :/ */
+ memcpy(tmp+ch_sta, format, numlen+1); /* add 1 to get the string terminator \0 */
+ } else {
+ /* we need to move the end characters, reuse i */
+ int j;
+
+ i = strlen(tmp); /* +1 to copy the string terminator */
+ j = i + (numlen-hashlen); /* from/to */
+
+ while (i >= ch_end) {
+ tmp[j] = tmp[i];
+ i--;
+ j--;
+ }
+ memcpy(tmp + ch_sta, format, numlen);
+ }
+ }
+ strcpy(path, tmp);
+ return 1;
+ }
+ return 0;
+}
- BLI_strncpy(vol, path, 3);
- wasrelative= (strncmp(vol, "//", 2)==0);
+int BLI_convertstringcode(char *path, const char *basepath)
+{
+ int wasrelative = (strncmp(path, "//", 2)==0);
+ char tmp[FILE_MAX];
+ char base[FILE_MAX];
#ifdef WIN32
+ char vol[3] = {'\0', '\0', '\0'};
+
+ BLI_strncpy(vol, path, 3);
/* we are checking here if we have an absolute path that is not in the current
blend file as a lib main - we are basically checking for the case that a
UNIX root '/' is passed.
@@ -979,13 +1190,29 @@ int BLI_convertstringcode(char *path, const char *basepath, int framenum)
strcat(tmp, p);
}
else {
- strcpy(tmp, path);
+ BLI_strncpy(tmp, path, FILE_MAX);
}
#else
- strcpy(tmp, path);
+ BLI_strncpy(tmp, path, FILE_MAX);
+
+ /* Check for loading a windows path on a posix system
+ * in this case, there is no use in trying C:/ since it
+ * will never exist on a unix os.
+ *
+ * Add a / prefix and lowercase the driveletter, remove the :
+ * C:\foo.JPG -> /c/foo.JPG */
+
+ if (isalpha(tmp[0]) && tmp[1] == ':' && (tmp[2]=='\\' || tmp[2]=='/') ) {
+ tmp[1] = tolower(tmp[0]); /* replace ':' with driveletter */
+ tmp[0] = '/';
+ /* '\' the slash will be converted later */
+ }
+
#endif
- strcpy(base, basepath);
+ BLI_strncpy(base, basepath, FILE_MAX);
+
+ BLI_cleanup_file(NULL, base);
/* push slashes into unix mode - strings entering this part are
potentially messed up: having both back- and forward slashes.
@@ -996,28 +1223,33 @@ int BLI_convertstringcode(char *path, const char *basepath, int framenum)
BLI_char_switch(tmp, '\\', '/');
BLI_char_switch(base, '\\', '/');
- if (tmp[0] == '/' && tmp[1] == '/') {
- char *filepart= BLI_strdup(tmp+2); /* skip code */
+ /* Paths starting with // will get the blend file as their base,
+ * this isnt standard in any os but is uesed in blender all over the place */
+ if (wasrelative) {
char *lslash= BLI_last_slash(base);
-
if (lslash) {
int baselen= (int) (lslash-base) + 1;
-
+ /* use path for for temp storage here, we copy back over it right away */
+ BLI_strncpy(path, tmp+2, FILE_MAX);
+
memcpy(tmp, base, baselen);
- strcpy(tmp+baselen, filepart);
+ strcpy(tmp+baselen, path);
+ strcpy(path, tmp);
} else {
- strcpy(tmp, filepart);
+ strcpy(path, tmp+2);
}
-
- MEM_freeN(filepart);
+ } else {
+ strcpy(path, tmp);
}
-
- len= strlen(tmp);
- if(len && tmp[len-1]=='#') {
- sprintf(tmp+len-1, "%04d", framenum);
+
+ if (path[0]!='\0') {
+ if ( path[strlen(path)-1]=='/') {
+ BLI_cleanup_dir(NULL, path);
+ } else {
+ BLI_cleanup_file(NULL, path);
+ }
}
-
- strcpy(path, tmp);
+
#ifdef WIN32
/* skip first two chars, which in case of
absolute path will be drive:/blabla and
@@ -1027,11 +1259,54 @@ int BLI_convertstringcode(char *path, const char *basepath, int framenum)
*/
BLI_char_switch(path+2, '/', '\\');
#endif
+
+ return wasrelative;
+}
+
+/*
+ * Should only be done with command line paths.
+ * this is NOT somthing blenders internal paths support like the // prefix
+ */
+int BLI_convertstringcwd(char *path)
+{
+ int wasrelative = 1;
+ int filelen = strlen(path);
+
+#ifdef WIN32
+ if (filelen >= 3 && path[1] == ':' && (path[2] == '\\' || path[2] == '/'))
+ wasrelative = 0;
+#else
+ if (filelen >= 2 && path[0] == '/')
+ wasrelative = 0;
+#endif
+
+ if (wasrelative==1) {
+ char cwd[FILE_MAXDIR + FILE_MAXFILE];
+ BLI_getwdN(cwd); /* incase the full path to the blend isnt used */
+
+ if (cwd[0] == '\0') {
+ printf( "Could not get the current working directory - $PWD for an unknown reason.");
+ } else {
+ /* uses the blend path relative to cwd important for loading relative linked files.
+ *
+ * cwd should contain c:\ etc on win32 so the relbase can be NULL
+ * relbase being NULL also prevents // being misunderstood as relative to the current
+ * blend file which isnt a feature we want to use in this case since were dealing
+ * with a path from the command line, rather then from inside Blender */
+
+ char origpath[FILE_MAXDIR + FILE_MAXFILE];
+ BLI_strncpy(origpath, path, FILE_MAXDIR + FILE_MAXFILE);
+
+ BLI_make_file_string(NULL, path, cwd, origpath);
+ }
+ }
+
return wasrelative;
}
-/* copy di to fi without directory only */
+
+/* copy di to fi, filename only */
void BLI_splitdirstring(char *di, char *fi)
{
char *lslash= BLI_last_slash(di);
@@ -1055,6 +1330,8 @@ char *BLI_gethome(void) {
#else /* Windows */
char * ret;
static char dir[512];
+ static char appdatapath[MAXPATHLEN];
+ HRESULT hResult;
/* Check for %HOME% env var */
@@ -1076,9 +1353,36 @@ char *BLI_gethome(void) {
/* add user profile support for WIN 2K / NT */
+ hResult = SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, appdatapath);
+
+ if (hResult == S_OK)
+ {
+ if (BLI_exists(appdatapath)) { /* from fop, also below... */
+ sprintf(dir, "%s\\Blender Foundation\\Blender", appdatapath);
+ BLI_recurdir_fileops(dir);
+ if (BLI_exists(dir)) {
+ strcat(dir,"\\.blender");
+ if(BLI_exists(dir)) return(dir);
+ }
+ }
+ hResult = SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, appdatapath);
+ if (hResult == S_OK)
+ {
+ if (BLI_exists(appdatapath))
+ { /* from fop, also below... */
+ sprintf(dir, "%s\\Blender Foundation\\Blender", appdatapath);
+ BLI_recurdir_fileops(dir);
+ if (BLI_exists(dir)) {
+ strcat(dir,"\\.blender");
+ if(BLI_exists(dir)) return(dir);
+ }
+ }
+ }
+ }
+#if 0
ret = getenv("USERPROFILE");
if (ret) {
- if (BLI_exists(ret)) { /* from fop, also below... */
+ if (BLI_exists(ret)) { /* from fop, also below... */
sprintf(dir, "%s\\Application Data\\Blender Foundation\\Blender", ret);
BLI_recurdir_fileops(dir);
if (BLI_exists(dir)) {
@@ -1087,6 +1391,7 @@ char *BLI_gethome(void) {
}
}
}
+#endif
/*
Saving in the Windows dir is less than desirable.
@@ -1276,9 +1581,42 @@ int BLI_testextensie(const char *str, const char *ext)
return (retval);
}
+/*
+ * This is a simple version of BLI_split_dirfile that has the following advantages...
+ *
+ * Converts "/foo/bar.txt" to "/foo/" and "bar.txt"
+ * - wont change 'string'
+ * - wont create any directories
+ * - dosnt use CWD, or deal with relative paths.
+ * - Only fill's in *dir and *file when they are non NULL
+ * */
+void BLI_split_dirfile_basic(const char *string, char *dir, char *file)
+{
+ int lslash=0, i = 0;
+ for (i=0; string[i]!='\0'; i++) {
+ if (string[i]=='\\' || string[i]=='/')
+ lslash = i+1;
+ }
+ if (dir) {
+ if (lslash) {
+ BLI_strncpy( dir, string, lslash+1); /* +1 to include the slash and the last char */
+ } else {
+ dir[0] = '\0';
+ }
+ }
+
+ if (file) {
+ strcpy( file, string+lslash);
+ }
+}
-void BLI_split_dirfile(const char *string, char *dir, char *file)
+/* Warning,
+ * - May modify 'string' variable
+ * - May create the directory if it dosnt exist
+ * if this is not needed use BLI_split_dirfile_basic(...)
+ */
+void BLI_split_dirfile(char *string, char *dir, char *file)
{
int a;
#ifdef WIN32
@@ -1400,12 +1738,20 @@ void BLI_join_dirfile(char *string, const char *dir, const char *file)
int sl_dir = strlen(dir);
BLI_strncpy(string, dir, FILE_MAX);
if (sl_dir > FILE_MAX-1) sl_dir = FILE_MAX-1;
+
+ /* only add seperator if needed */
#ifdef WIN32
- string[sl_dir] = '\\';
+ if (string[sl_dir-1] != '\\') {
+ string[sl_dir] = '\\';
+ sl_dir++;
+ }
#else
- string[sl_dir] = '/';
+ if (string[sl_dir-1] != '/') {
+ string[sl_dir] = '/';
+ sl_dir++;
+ }
#endif
- sl_dir++;
+
if (sl_dir <FILE_MAX) {
BLI_strncpy(string + sl_dir, file, FILE_MAX-sl_dir);
}
@@ -1452,10 +1798,10 @@ static int add_win32_extension(char *name)
return (retval);
}
-void BLI_where_am_i(char *fullname, char *name)
+void BLI_where_am_i(char *fullname, const char *name)
{
char filename[FILE_MAXDIR+FILE_MAXFILE];
- char *path, *temp;
+ char *path = NULL, *temp;
int len;
#ifdef _WIN32
char *seperator = ";";
@@ -1465,6 +1811,18 @@ void BLI_where_am_i(char *fullname, char *name)
char *slash = "/";
#endif
+
+#ifdef __linux__
+ /* linux uses binreloc since argv[0] is not relyable, call br_init( NULL ) first */
+ path = br_find_exe( NULL );
+ if (path) {
+ strcpy(fullname, path);
+ free(path);
+ return;
+ }
+#endif
+
+ /* unix and non linux */
if (name && fullname && strlen(name)) {
strcpy(fullname, name);
if (name[0] == '.') {
@@ -1525,6 +1883,47 @@ void BLI_where_am_i(char *fullname, char *name)
}
}
+void BLI_where_is_temp(char *fullname, int usertemp)
+{
+ fullname[0] = '\0';
+
+ if (usertemp && BLI_exists(U.tempdir)) {
+ strcpy(fullname, U.tempdir);
+ }
+
+
+#ifdef WIN32
+ if (fullname[0] == '\0') {
+ char *tmp = getenv("TEMP"); /* Windows */
+ if (tmp && BLI_exists(tmp)) {
+ strcpy(fullname, tmp);
+ }
+ }
+#else
+ /* Other OS's - Try TMP and TMPDIR */
+ if (fullname[0] == '\0') {
+ char *tmp = getenv("TMP");
+ if (tmp && BLI_exists(tmp)) {
+ strcpy(fullname, tmp);
+ }
+ }
+
+ if (fullname[0] == '\0') {
+ char *tmp = getenv("TMPDIR");
+ if (tmp && BLI_exists(tmp)) {
+ strcpy(fullname, tmp);
+ }
+ }
+#endif
+
+ if (fullname[0] == '\0') {
+ strcpy(fullname, "/tmp/");
+ } else {
+ /* add a trailing slash if needed */
+ BLI_add_slash(fullname);
+ }
+}
+
/*
* returns absolute path to the app bundle
* only useful on OS X
@@ -1608,7 +2007,7 @@ int BLI_strncasecmp(const char *s1, const char *s2, int n) {
#include "iconv.h"
#include "localcharset.h"
-void BLI_string_to_utf8(char *original, char *utf_8, char *code)
+void BLI_string_to_utf8(char *original, char *utf_8, const char *code)
{
size_t inbytesleft=strlen(original);
size_t outbytesleft=512;
@@ -1666,7 +2065,7 @@ void BLI_timestr(double _time, char *str)
int BLI_int_from_pointer(void *poin)
{
- long lval= (long)poin;
+ intptr_t lval= (intptr_t)poin;
return (int)(lval>>3);
}
@@ -1674,17 +2073,17 @@ int BLI_int_from_pointer(void *poin)
void *BLI_pointer_from_int(int val)
{
static int firsttime= 1;
- static long basevalue= 0;
+ static intptr_t basevalue= 0;
if(firsttime) {
void *poin= malloc(10000);
- basevalue= (long)poin;
+ basevalue= (intptr_t)poin;
basevalue &= ~PMASK;
printf("base: %d pointer %p\n", basevalue, poin); /* debug */
firsttime= 0;
free(poin);
}
- return (void *)(basevalue | (((long)val)<<3));
+ return (void *)(basevalue | (((intptr_t)val)<<3));
}
#else
diff --git a/source/blender/blenlib/intern/winstuff.c b/source/blender/blenlib/intern/winstuff.c
index ace677e6045..666a54b54cc 100644
--- a/source/blender/blenlib/intern/winstuff.c
+++ b/source/blender/blenlib/intern/winstuff.c
@@ -196,6 +196,27 @@ void get_default_root(char* root) {
}
}
+int check_file_chars(char *filename)
+{
+ char *p = filename;
+ while (*p) {
+ switch (*p) {
+ case ':':
+ case '?':
+ case '*':
+ case '|':
+ case '\\':
+ case '/':
+ case '\"':
+ return 0;
+ break;
+ }
+
+ p++;
+ }
+ return 1;
+}
+
#else
static void BLI_WINSTUFF_C_IS_EMPTY_FOR_UNIX(void)
diff --git a/source/blender/blenloader/BLO_readfile.h b/source/blender/blenloader/BLO_readfile.h
index 9cf300ea460..1219b1ba0c5 100644
--- a/source/blender/blenloader/BLO_readfile.h
+++ b/source/blender/blenloader/BLO_readfile.h
@@ -237,9 +237,9 @@ int BLO_has_bfile_extension(char *str);
void BLO_library_append(struct SpaceFile *sfile, char *dir, int idcode, struct Scene *scene);
void BLO_library_append_(BlendHandle **libfiledata, struct direntry* filelist, int totfile,
char *dir, char* file, short flag, int idcode, struct Scene *scene);
-void BLO_script_library_append(BlendHandle *bh, char *dir, char *name, int idcode, short flag, struct Scene *scene);
+void BLO_script_library_append(BlendHandle **bh, char *dir, char *name, int idcode, short flag, struct Scene *scene);
-BlendFileData* blo_read_blendafterruntime(int file, int actualsize, BlendReadError *error_r);
+BlendFileData* blo_read_blendafterruntime(int file, char *name, int actualsize, BlendReadError *error_r);
#ifdef __cplusplus
}
diff --git a/source/blender/blenloader/BLO_soundfile.h b/source/blender/blenloader/BLO_soundfile.h
index 3d133b2d3bd..a239c7d8965 100644
--- a/source/blender/blenloader/BLO_soundfile.h
+++ b/source/blender/blenloader/BLO_soundfile.h
@@ -35,7 +35,5 @@
struct bSound;
struct PackedFile;
-//void sound_read_wav_data(bSound * sound, PackedFile * pf);
-
#endif
diff --git a/source/blender/blenloader/BLO_sys_types.h b/source/blender/blenloader/BLO_sys_types.h
index a1885894fe3..49155260b31 100644
--- a/source/blender/blenloader/BLO_sys_types.h
+++ b/source/blender/blenloader/BLO_sys_types.h
@@ -43,17 +43,13 @@
#ifdef __cplusplus
extern "C" {
#endif
-
-#ifdef FREE_WINDOWS
-typedef unsigned char uint8_t;
-typedef unsigned int uint32_t;
-#endif
#if defined(_WIN32) && !defined(FREE_WINDOWS)
/* The __intXX are built-in types of the visual complier! So we don't
* need to include anything else here. */
+
typedef signed __int8 int8_t;
typedef signed __int16 int16_t;
typedef signed __int32 int32_t;
@@ -64,6 +60,24 @@ typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
+#ifndef _INTPTR_T_DEFINED
+#ifdef _WIN64
+typedef __int64 intptr_t;
+#else
+typedef long intptr_t;
+#endif
+#define _INTPTR_T_DEFINED
+#endif
+
+#ifndef _UINTPTR_T_DEFINED
+#ifdef _WIN64
+typedef unsigned __int64 uintptr_t;
+#else
+typedef unsigned long uintptr_t;
+#endif
+#define _UINTPTR_T_DEFINED
+#endif
+
#elif defined(__linux__)
/* Linux-i386, Linux-Alpha, Linux-ppc */
@@ -73,6 +87,10 @@ typedef unsigned __int64 uint64_t;
#include <inttypes.h>
+#elif defined(FREE_WINDOWS)
+
+#include <stdint.h>
+
#else
/* FreeBSD, Irix, Solaris */
@@ -80,6 +98,7 @@ typedef unsigned __int64 uint64_t;
#endif /* ifdef platform for types */
+
#ifdef _WIN32
#define htonl(x) correctByteOrder(x)
#define ntohl(x) correctByteOrder(x)
diff --git a/source/blender/blenloader/SConscript b/source/blender/blenloader/SConscript
index 37d5f5381fa..ac3b1262cb7 100644
--- a/source/blender/blenloader/SConscript
+++ b/source/blender/blenloader/SConscript
@@ -5,7 +5,6 @@ sources = env.Glob('intern/*.c')
incs = '. #/intern/guardedalloc ../blenlib ../blenkernel'
incs += ' ../makesdna ../readblenfile ../editors/include'
-incs += ' ../python ../../kernel/gen_messaging'
incs += ' ../render/extern/include'
incs += ' ' + env['BF_ZLIB_INC']
@@ -15,4 +14,4 @@ if env['WITH_BF_VERSE']:
defs += ' WITH_VERSE'
incs += ' ' + env['BF_VERSE_INCLUDE']
-env.BlenderLib ( 'bf_blenloader', sources, Split(incs), Split(defs), libtype=['core','player'], priority = [85, 25] )
+env.BlenderLib ( 'bf_blenloader', sources, Split(incs), Split(defs), libtype=['core','player'], priority = [70, 30] )
diff --git a/source/blender/blenloader/intern/readblenentry.c b/source/blender/blenloader/intern/readblenentry.c
index 24239b3e088..d5f5bb663ab 100644
--- a/source/blender/blenloader/intern/readblenentry.c
+++ b/source/blender/blenloader/intern/readblenentry.c
@@ -63,6 +63,8 @@
#include "BLO_readblenfile.h"
+#include "BLO_sys_types.h" // needed for intptr_t
+
/**
* IDType stuff, I plan to move this
* out into its own file + prefix, and
@@ -193,7 +195,7 @@ void BLO_blendhandle_print_sizes(BlendHandle *bh, void *fp)
buf[2]= buf[2]?buf[2]:' ';
buf[3]= buf[3]?buf[3]:' ';
- fprintf(fp, "['%.4s', '%s', %d, %ld ], \n", buf, name, bhead->nr, (long)bhead->len+sizeof(BHead));
+ fprintf(fp, "['%.4s', '%s', %d, %ld ], \n", buf, name, bhead->nr, (intptr_t)bhead->len+sizeof(BHead));
}
}
fprintf(fp, "]\n");
@@ -362,6 +364,9 @@ BlendFileData *BLO_read_from_memfile(const char *filename, MemFile *memfile, Ble
if (fd) {
strcpy(fd->filename, filename);
+ /* clear ob->proxy_from pointers in G.main */
+ blo_clear_proxy_pointers_from_lib(fd);
+
/* separate libraries from G.main */
blo_split_main(&mainlist, G.main);
/* add the library pointers in oldmap lookup */
diff --git a/source/blender/blenloader/intern/readfile.c b/source/blender/blenloader/intern/readfile.c
index 5c8583cd5ee..1ecd402bd56 100644
--- a/source/blender/blenloader/intern/readfile.c
+++ b/source/blender/blenloader/intern/readfile.c
@@ -34,6 +34,7 @@
#include "BLI_winstuff.h"
#endif
+#include <limits.h>
#include <stdio.h> // for printf fopen fwrite fclose sprintf FILE
#include <stdlib.h> // for getenv atoi
#include <fcntl.h> // for open
@@ -53,6 +54,7 @@
#include "DNA_actuator_types.h"
#include "DNA_brush_types.h"
#include "DNA_camera_types.h"
+#include "DNA_cloth_types.h"
#include "DNA_color_types.h"
#include "DNA_controller_types.h"
#include "DNA_constraint_types.h"
@@ -62,6 +64,7 @@
#include "DNA_fileglobal_types.h"
#include "DNA_genfile.h"
#include "DNA_group_types.h"
+#include "DNA_gpencil_types.h"
#include "DNA_ipo_types.h"
#include "DNA_image_types.h"
#include "DNA_key_types.h"
@@ -104,13 +107,14 @@
#include "BKE_action.h"
#include "BKE_armature.h"
+#include "BKE_cloth.h"
#include "BKE_colortools.h"
#include "BKE_constraint.h"
#include "BKE_curve.h"
#include "BKE_customdata.h"
#include "BKE_deform.h"
#include "BKE_depsgraph.h"
-#include "BKE_effect.h" // for give_parteff
+#include "BKE_effect.h" /* give_parteff */
#include "BKE_global.h" // for G
#include "BKE_group.h"
#include "BKE_image.h"
@@ -123,10 +127,13 @@
#include "BKE_node.h" // for tree type defines
#include "BKE_object.h"
#include "BKE_particle.h"
-#include "BKE_property.h" // for get_property
+#include "BKE_pointcache.h"
+#include "BKE_property.h" // for get_ob_property
#include "BKE_sca.h" // for init_actuator
#include "BKE_scene.h"
#include "BKE_softbody.h" // sbNew()
+#include "BKE_bullet.h" // bsbNew()
+#include "BKE_sculpt.h"
#include "BKE_texture.h" // for open_plugin_tex
#include "BKE_utildefines.h" // SWITCH_INT DATA ENDB DNA1 O_BINARY GLOB USER TEST REND
#include "BKE_idprop.h"
@@ -704,7 +711,7 @@ BHead *blo_firstbhead(FileData *fd)
BHead *blo_prevbhead(FileData *fd, BHead *thisblock)
{
- BHeadN *bheadn= (BHeadN *) (((char *) thisblock) - (int) (&((BHeadN*)0)->bhead));
+ BHeadN *bheadn= (BHeadN *) (((char *) thisblock) - GET_INT_FROM_POINTER( &((BHeadN*)0)->bhead) );
BHeadN *prev= bheadn->prev;
return prev?&prev->bhead:NULL;
@@ -712,13 +719,13 @@ BHead *blo_prevbhead(FileData *fd, BHead *thisblock)
BHead *blo_nextbhead(FileData *fd, BHead *thisblock)
{
- BHeadN *new_bhead = 0;
- BHead *bhead = 0;
+ BHeadN *new_bhead = NULL;
+ BHead *bhead = NULL;
if (thisblock) {
// bhead is actually a sub part of BHeadN
// We calculate the BHeadN pointer from the BHead pointer below
- new_bhead = (BHeadN *) (((char *) thisblock) - (int) (&((BHeadN*)0)->bhead));
+ new_bhead = (BHeadN *) (((char *) thisblock) - GET_INT_FROM_POINTER( &((BHeadN*)0)->bhead) );
// get the next BHeadN. If it doesn't exist we read in the next one
new_bhead = new_bhead->next;
@@ -843,6 +850,7 @@ static int fd_read_from_memfile(FileData *filedata, void *buffer, int size)
static unsigned int seek= 1<<30; /* the current position */
static unsigned int offset= 0; /* size of previous chunks */
static MemFileChunk *chunk=NULL;
+ unsigned int chunkoffset, readsize, totread;
if(size==0) return 0;
@@ -860,29 +868,39 @@ static int fd_read_from_memfile(FileData *filedata, void *buffer, int size)
}
if(chunk) {
- /* first check if it's on the end if current chunk */
- if( seek-offset == chunk->size) {
- offset+= chunk->size;
- chunk= chunk->next;
- }
-
- /* debug, should never happen */
- if(chunk==NULL) {
- printf("illegal read, chunk zero\n");
- return 0;
- }
- else if( (seek-offset)+size > chunk->size) {
- size= chunk->size - (seek-offset);
- printf("chunk too large, clipped to %d\n", size);
- }
-
- memcpy(buffer, chunk->buf + (seek-offset), size);
- filedata->seek += size;
- seek+= size;
-
- return (size);
+ totread= 0;
+
+ do {
+ /* first check if it's on the end if current chunk */
+ if(seek-offset == chunk->size) {
+ offset+= chunk->size;
+ chunk= chunk->next;
+ }
+
+ /* debug, should never happen */
+ if(chunk==NULL) {
+ printf("illegal read, chunk zero\n");
+ return 0;
+ }
+
+ chunkoffset= seek-offset;
+ readsize= size-totread;
+
+ /* data can be spread over multiple chunks, so clamp size
+ * to within this chunk, and then it will read further in
+ * the next chunk */
+ if(chunkoffset+readsize > chunk->size)
+ readsize= chunk->size-chunkoffset;
+
+ memcpy((char*)buffer+totread, chunk->buf+chunkoffset, readsize);
+ totread += readsize;
+ filedata->seek += readsize;
+ seek += readsize;
+ } while(totread < size);
+ return totread;
}
+
return 0;
}
@@ -940,9 +958,11 @@ FileData *blo_openblenderfile(char *name, BlendReadError *error_r)
} else {
FileData *fd = filedata_new();
fd->gzfiledes = gzfile;
- BLI_strncpy(fd->filename, name, sizeof(fd->filename)); // now only in use by library append
fd->read = fd_read_gzip_from_file;
+ /* needed for library_append and read_libraries */
+ BLI_strncpy(fd->filename, name, sizeof(fd->filename));
+
return blo_decode_and_check(fd, error_r);
}
}
@@ -1016,7 +1036,9 @@ void blo_freefiledata(FileData *fd)
oldnewmap_free(fd->imamap);
if (fd->libmap && !(fd->flags & FD_FLAGS_NOT_MY_LIBMAP))
oldnewmap_free(fd->libmap);
-
+ if (fd->bheadmap)
+ MEM_freeN(fd->bheadmap);
+
MEM_freeN(fd);
}
}
@@ -1094,6 +1116,19 @@ static void change_idid_adr(ListBase *mainlist, FileData *basefd, void *old, voi
}
}
+/* lib linked proxy objects point to our local data, we need
+ * to clear that pointer before reading the undo memfile since
+ * the object might be removed, it is set again in reading
+ * if the local object still exists */
+void blo_clear_proxy_pointers_from_lib(FileData *fd)
+{
+ Object *ob= G.main->object.first;
+
+ for(;ob; ob= ob->id.next)
+ if(ob->id.lib)
+ ob->proxy_from= NULL;
+}
+
/* assumed; G.main still exists */
void blo_make_image_pointer_map(FileData *fd)
{
@@ -1106,6 +1141,8 @@ void blo_make_image_pointer_map(FileData *fd)
Link *ibuf= ima->ibufs.first;
for(; ibuf; ibuf= ibuf->next)
oldnewmap_insert(fd->imamap, ibuf, ibuf, 0);
+ if(ima->gputexture)
+ oldnewmap_insert(fd->imamap, ima->gputexture, ima->gputexture, 0);
}
for(; sce; sce= sce->id.next) {
if(sce->nodetree) {
@@ -1140,8 +1177,11 @@ void blo_end_image_pointer_map(FileData *fd)
if(NULL==newimaadr(fd, ibuf)) { /* so was restored */
BLI_remlink(&ima->ibufs, ibuf);
ima->bindcode= 0;
+ ima->gputexture= NULL;
}
}
+
+ ima->gputexture= newimaadr(fd, ima->gputexture);
}
for(; sce; sce= sce->id.next) {
if(sce->nodetree) {
@@ -1306,7 +1346,7 @@ static void test_pointer_array(FileData *fd, void **mat)
void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, void *fd);
void IDP_LibLinkProperty(IDProperty *prop, int switch_endian, void *fd);
-void IDP_DirectLinkArray(IDProperty *prop, int switch_endian, void *fd)
+static void IDP_DirectLinkArray(IDProperty *prop, int switch_endian, void *fd)
{
int i;
@@ -1315,20 +1355,26 @@ void IDP_DirectLinkArray(IDProperty *prop, int switch_endian, void *fd)
prop->data.pointer = newdataadr(fd, prop->data.pointer);
if (switch_endian) {
- for (i=0; i<prop->len; i++) {
- SWITCH_INT(((int*)prop->data.pointer)[i]);
+ if (prop->subtype != IDP_DOUBLE) {
+ for (i=0; i<prop->len; i++) {
+ SWITCH_INT(((int*)prop->data.pointer)[i]);
+ }
+ } else {
+ for (i=0; i<prop->len; i++) {
+ SWITCH_LONGINT(((double*)prop->data.pointer)[i]);
+ }
}
}
}
-void IDP_DirectLinkString(IDProperty *prop, int switch_endian, void *fd)
+static void IDP_DirectLinkString(IDProperty *prop, int switch_endian, void *fd)
{
/*since we didn't save the extra string buffer, set totallen to len.*/
prop->totallen = prop->len;
prop->data.pointer = newdataadr(fd, prop->data.pointer);
}
-void IDP_DirectLinkGroup(IDProperty *prop, int switch_endian, void *fd)
+static void IDP_DirectLinkGroup(IDProperty *prop, int switch_endian, void *fd)
{
ListBase *lb = &prop->data.group;
IDProperty *loop;
@@ -1353,6 +1399,24 @@ void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, void *fd)
case IDP_ARRAY:
IDP_DirectLinkArray(prop, switch_endian, fd);
break;
+ case IDP_DOUBLE:
+ /*erg, stupid doubles. since I'm storing them
+ in the same field as int val; val2 in the
+ IDPropertyData struct, they have to deal with
+ endianness specifically
+
+ in theory, val and val2 would've already been swapped
+ if switch_endian is true, so we have to first unswap
+ them then reswap them as a single 64-bit entity.
+ */
+
+ if (switch_endian) {
+ SWITCH_INT(prop->data.val);
+ SWITCH_INT(prop->data.val2);
+ SWITCH_LONGINT(prop->data.val);
+ }
+
+ break;
}
}
@@ -1392,6 +1456,12 @@ static void direct_link_brush(FileData *fd, Brush *brush)
brush->mtex[a]= newdataadr(fd, brush->mtex[a]);
}
+static void direct_link_script(FileData *fd, Script *script)
+{
+ script->id.us = 1;
+ SCRIPT_SET_NULL(script)
+}
+
/* ************ READ CurveMapping *************** */
/* cuma itself has been read! */
@@ -1434,11 +1504,18 @@ static void lib_link_nodetree(FileData *fd, Main *main)
}
/* verify types for nodes and groups, all data has to be read */
-static void lib_verify_nodetree(Main *main)
+/* open = 0: appending/linking, open = 1: open new file (need to clean out dynamic
+ * typedefs*/
+static void lib_verify_nodetree(Main *main, int open)
{
Scene *sce;
Material *ma;
bNodeTree *ntree;
+
+ /* this crashes blender on undo/redo
+ if(open==1) {
+ reinit_nodesystem();
+ }*/
/* now create the own typeinfo structs an verify nodes */
/* here we still assume no groups in groups */
@@ -1475,6 +1552,12 @@ static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
link_list(fd, &ntree->nodes);
for(node= ntree->nodes.first; node; node= node->next) {
+ if(node->type == NODE_DYNAMIC) {
+ node->custom1= 0;
+ node->custom1= BSET(node->custom1, NODE_DYNAMIC_LOADED);
+ node->typeinfo= NULL;
+ }
+
node->storage= newdataadr(fd, node->storage);
if(node->storage) {
@@ -1509,6 +1592,22 @@ static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
link->tosock= newdataadr(fd, link->tosock);
}
+ /* set selin and selout */
+ for(node= ntree->nodes.first; node; node= node->next) {
+ for(sock= node->inputs.first; sock; sock= sock->next) {
+ if(sock->flag & SOCK_SEL) {
+ ntree->selin= sock;
+ break;
+ }
+ }
+ for(sock= node->outputs.first; sock; sock= sock->next) {
+ if(sock->flag & SOCK_SEL) {
+ ntree->selout= sock;
+ break;
+ }
+ }
+ }
+
/* type verification is in lib-link */
}
@@ -1721,6 +1820,13 @@ static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
data->tar = newlibadr(fd, id->lib, data->tar);
}
break;
+ case CONSTRAINT_TYPE_DISTLIMIT:
+ {
+ bDistLimitConstraint *data;
+ data= ((bDistLimitConstraint*)con->data);
+ data->tar = newlibadr(fd, id->lib, data->tar);
+ }
+ break;
case CONSTRAINT_TYPE_NULL:
break;
}
@@ -1734,6 +1840,7 @@ static void direct_link_constraints(FileData *fd, ListBase *lb)
link_list(fd, lb);
for (cons=lb->first; cons; cons=cons->next) {
cons->data = newdataadr(fd, cons->data);
+
if (cons->type == CONSTRAINT_TYPE_PYTHON) {
bPythonConstraint *data= cons->data;
link_list(fd, &data->targets);
@@ -1800,12 +1907,12 @@ static void lib_link_action(FileData *fd, Main *main)
while(act) {
if(act->id.flag & LIB_NEEDLINK) {
act->id.flag -= LIB_NEEDLINK;
-
+
for (chan=act->chanbase.first; chan; chan=chan->next) {
chan->ipo= newlibadr_us(fd, act->id.lib, chan->ipo);
lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
}
-
+
}
act= act->id.next;
}
@@ -1828,12 +1935,24 @@ static void direct_link_bones(FileData *fd, Bone* bone)
static void direct_link_action(FileData *fd, bAction *act)
{
bActionChannel *achan;
+ bActionGroup *agrp;
link_list(fd, &act->chanbase);
+ link_list(fd, &act->groups);
+ link_list(fd, &act->markers);
- for (achan = act->chanbase.first; achan; achan=achan->next)
+ for (achan = act->chanbase.first; achan; achan=achan->next) {
+ achan->grp= newdataadr(fd, achan->grp);
+
link_list(fd, &achan->constraintChannels);
-
+ }
+
+ for (agrp = act->groups.first; agrp; agrp= agrp->next) {
+ if (agrp->channels.first) {
+ agrp->channels.first= newdataadr(fd, agrp->channels.first);
+ agrp->channels.last= newdataadr(fd, agrp->channels.last);
+ }
+ }
}
static void direct_link_armature(FileData *fd, bArmature *arm)
@@ -2162,6 +2281,7 @@ static void direct_link_text(FileData *fd, Text *text)
*/
link_list(fd, &text->lines);
+ link_list(fd, &text->markers);
text->curl= newdataadr(fd, text->curl);
text->sell= newdataadr(fd, text->sell);
@@ -2228,8 +2348,10 @@ static void direct_link_image(FileData *fd, Image *ima)
ima->ibufs.first= ima->ibufs.last= NULL;
/* if not restored, we keep the binded opengl index */
- if(ima->ibufs.first==NULL)
+ if(ima->ibufs.first==NULL) {
ima->bindcode= 0;
+ ima->gputexture= NULL;
+ }
ima->anim= NULL;
ima->rr= NULL;
@@ -2440,10 +2562,17 @@ static void direct_link_material(FileData *fd, Material *ma)
direct_link_nodetree(fd, ma->nodetree);
ma->preview = direct_link_preview_image(fd, ma->preview);
+ ma->gpumaterial.first = ma->gpumaterial.last = NULL;
}
/* ************ READ PARTICLE SETTINGS ***************** */
+static void direct_link_pointcache(FileData *fd, PointCache *cache)
+{
+ cache->flag &= ~(PTCACHE_SIMULATION_VALID|PTCACHE_BAKE_EDIT_ACTIVE);
+ cache->simframe= 0;
+}
+
static void lib_link_particlesettings(FileData *fd, Main *main)
{
ParticleSettings *part;
@@ -2465,21 +2594,36 @@ static void lib_link_particlesettings(FileData *fd, Main *main)
static void direct_link_particlesettings(FileData *fd, ParticleSettings *part)
{
part->pd= newdataadr(fd, part->pd);
+ part->pd2= newdataadr(fd, part->pd2);
}
-static void lib_link_particlesystems(FileData *fd, ID *id, ListBase *particles)
+static void lib_link_particlesystems(FileData *fd, Object *ob, ID *id, ListBase *particles)
{
- ParticleSystem *psys;
+ ParticleSystem *psys, *psysnext;
int a;
- for(psys=particles->first; psys; psys=psys->next){
+ for(psys=particles->first; psys; psys=psysnext){
ParticleData *pa;
+
+ psysnext= psys->next;
+
psys->part = newlibadr_us(fd, id->lib, psys->part);
- psys->target_ob = newlibadr(fd, id->lib, psys->target_ob);
- psys->keyed_ob = newlibadr(fd, id->lib, psys->keyed_ob);
+ if(psys->part) {
+ psys->target_ob = newlibadr(fd, id->lib, psys->target_ob);
+ psys->keyed_ob = newlibadr(fd, id->lib, psys->keyed_ob);
+
+ for(a=0,pa=psys->particles; a<psys->totpart; a++,pa++){
+ pa->stick_ob=newlibadr(fd, id->lib, pa->stick_ob);
+ }
+ }
+ else {
+ /* particle modifier must be removed before particle system */
+ ParticleSystemModifierData *psmd= psys_get_modifier(ob,psys);
+ BLI_remlink(&ob->modifiers, psmd);
+ modifier_free((ModifierData *)psmd);
- for(a=0,pa=psys->particles; a<psys->totpart; a++,pa++){
- pa->stick_ob=newlibadr(fd, id->lib, pa->stick_ob);
+ BLI_remlink(particles, psys);
+ MEM_freeN(psys);
}
}
}
@@ -2495,6 +2639,15 @@ static void direct_link_particlesystems(FileData *fd, ListBase *particles)
for(a=0; a<psys->totpart; a++, pa++)
pa->hair=newdataadr(fd,pa->hair);
}
+ if(psys->particles && psys->particles->keys){
+ ParticleData *pa = psys->particles;
+ for(a=0; a<psys->totpart; a++, pa++) {
+ pa->keys= NULL;
+ pa->totkey= 0;
+ }
+
+ psys->flag &= ~PSYS_KEYED;
+ }
psys->child=newdataadr(fd,psys->child);
psys->effectors.first=psys->effectors.last=0;
@@ -2505,12 +2658,22 @@ static void direct_link_particlesystems(FileData *fd, ListBase *particles)
sb->bpoint= NULL; // init pointers so it gets rebuilt nicely
sb->bspring= NULL;
sb->scratch= NULL;
+
+ sb->pointcache= newdataadr(fd, sb->pointcache);
+ if(sb->pointcache)
+ direct_link_pointcache(fd, sb->pointcache);
}
psys->edit = 0;
psys->pathcache = 0;
psys->childcache = 0;
+ psys->pathcachebufs.first = psys->pathcachebufs.last = 0;
+ psys->childcachebufs.first = psys->childcachebufs.last = 0;
psys->reactevents.first = psys->reactevents.last = 0;
+
+ psys->pointcache= newdataadr(fd, psys->pointcache);
+ if(psys->pointcache)
+ direct_link_pointcache(fd, psys->pointcache);
}
return;
}
@@ -2753,6 +2916,7 @@ static void lib_link_object(FileData *fd, Main *main)
ob->track= newlibadr(fd, ob->id.lib, ob->track);
ob->ipo= newlibadr_us(fd, ob->id.lib, ob->ipo);
ob->action = newlibadr_us(fd, ob->id.lib, ob->action);
+ ob->poselib= newlibadr_us(fd, ob->id.lib, ob->poselib);
ob->dup_group= newlibadr_us(fd, ob->id.lib, ob->dup_group);
ob->proxy= newlibadr_us(fd, ob->id.lib, ob->proxy);
@@ -2781,8 +2945,7 @@ static void lib_link_object(FileData *fd, Main *main)
else printf("Object %s lost data.", ob->id.name+2);
if(ob->pose) {
- free_pose_channels(ob->pose);
- MEM_freeN(ob->pose);
+ free_pose(ob->pose);
ob->pose= NULL;
ob->flag &= ~OB_POSEMODE;
}
@@ -2806,11 +2969,9 @@ static void lib_link_object(FileData *fd, Main *main)
sens= ob->sensors.first;
while(sens) {
- if(ob->id.lib==NULL) { // done in expand_main
- for(a=0; a<sens->totlinks; a++) {
- sens->links[a]= newglobadr(fd, sens->links[a]);
- }
- }
+ for(a=0; a<sens->totlinks; a++)
+ sens->links[a]= newglobadr(fd, sens->links[a]);
+
if(sens->type==SENS_TOUCH) {
bTouchSensor *ts= sens->data;
ts->ma= newlibadr(fd, ob->id.lib, ts->ma);
@@ -2825,11 +2986,9 @@ static void lib_link_object(FileData *fd, Main *main)
cont= ob->controllers.first;
while(cont) {
- if(ob->id.lib==NULL) { // done in expand_main
- for(a=0; a<cont->totlinks; a++) {
- cont->links[a]= newglobadr(fd, cont->links[a]);
- }
- }
+ for(a=0; a<cont->totlinks; a++)
+ cont->links[a]= newglobadr(fd, cont->links[a]);
+
if(cont->type==CONT_PYTHON) {
bPythonCont *pc= cont->data;
pc->text= newlibadr(fd, ob->id.lib, pc->text);
@@ -2880,6 +3039,10 @@ static void lib_link_object(FileData *fd, Main *main)
bActionActuator *aa= act->data;
aa->act= newlibadr(fd, ob->id.lib, aa->act);
}
+ else if(act->type==ACT_SHAPEACTION) {
+ bActionActuator *aa= act->data;
+ aa->act= newlibadr(fd, ob->id.lib, aa->act);
+ }
else if(act->type==ACT_PROPERTY) {
bPropertyActuator *pa= act->data;
pa->ob= newlibadr(fd, ob->id.lib, pa->ob);
@@ -2888,11 +3051,25 @@ static void lib_link_object(FileData *fd, Main *main)
bMessageActuator *ma= act->data;
ma->toObject= newlibadr(fd, ob->id.lib, ma->toObject);
}
+ else if(act->type==ACT_2DFILTER){
+ bTwoDFilterActuator *_2dfa = act->data;
+ _2dfa->text= newlibadr(fd, ob->id.lib, _2dfa->text);
+ }
+ else if(act->type==ACT_PARENT) {
+ bParentActuator *parenta = act->data;
+ parenta->ob = newlibadr(fd, ob->id.lib, parenta->ob);
+ }
+ else if(act->type==ACT_STATE) {
+ /* bStateActuator *statea = act->data; */
+ }
act= act->next;
}
-
- if(ob->fluidsimSettings) {
- ob->fluidsimSettings->ipo = newlibadr_us(fd, ob->id.lib, ob->fluidsimSettings->ipo);
+
+ {
+ FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
+
+ if(fluidmd && fluidmd->fss)
+ fluidmd->fss->ipo = newlibadr_us(fd, ob->id.lib, fluidmd->fss->ipo);
}
/* texture field */
@@ -2901,7 +3078,7 @@ static void lib_link_object(FileData *fd, Main *main)
ob->pd->tex=newlibadr_us(fd, ob->id.lib, ob->pd->tex);
lib_link_scriptlink(fd, &ob->id, &ob->scriptlink);
- lib_link_particlesystems(fd, &ob->id, &ob->particlesystem);
+ lib_link_particlesystems(fd, ob, &ob->id, &ob->particlesystem);
lib_link_modifiers(fd, ob);
}
ob= ob->id.next;
@@ -2911,14 +3088,15 @@ static void lib_link_object(FileData *fd, Main *main)
}
-static void direct_link_pose(FileData *fd, bPose *pose) {
-
+static void direct_link_pose(FileData *fd, bPose *pose)
+{
bPoseChannel *pchan;
if (!pose)
return;
link_list(fd, &pose->chanbase);
+ link_list(fd, &pose->agroups);
for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
pchan->bone= NULL;
@@ -2928,7 +3106,6 @@ static void direct_link_pose(FileData *fd, bPose *pose) {
pchan->iktree.first= pchan->iktree.last= NULL;
pchan->path= NULL;
}
-
}
static void direct_link_modifiers(FileData *fd, ListBase *lb)
@@ -2948,7 +3125,57 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb)
SubsurfModifierData *smd = (SubsurfModifierData*) md;
smd->emCache = smd->mCache = 0;
- } else if (md->type==eModifierType_Hook) {
+ }
+ else if (md->type==eModifierType_Cloth) {
+ ClothModifierData *clmd = (ClothModifierData*) md;
+
+ clmd->clothObject = NULL;
+
+ clmd->sim_parms= newdataadr(fd, clmd->sim_parms);
+ clmd->coll_parms= newdataadr(fd, clmd->coll_parms);
+ clmd->point_cache= newdataadr(fd, clmd->point_cache);
+
+ if(clmd->point_cache)
+ direct_link_pointcache(fd, clmd->point_cache);
+
+ if(clmd->sim_parms) {
+ if(clmd->sim_parms->presets > 10)
+ clmd->sim_parms->presets = 0;
+ }
+
+ }
+ else if (md->type==eModifierType_Fluidsim) {
+ FluidsimModifierData *fluidmd = (FluidsimModifierData*) md;
+
+ fluidmd->fss= newdataadr(fd, fluidmd->fss);
+ }
+ else if (md->type==eModifierType_Collision) {
+
+ CollisionModifierData *collmd = (CollisionModifierData*) md;
+ /*
+ // TODO: CollisionModifier should use pointcache
+ // + have proper reset events before enabling this
+ collmd->x = newdataadr(fd, collmd->x);
+ collmd->xnew = newdataadr(fd, collmd->xnew);
+ collmd->mfaces = newdataadr(fd, collmd->mfaces);
+
+ collmd->current_x = MEM_callocN(sizeof(MVert)*collmd->numverts,"current_x");
+ collmd->current_xnew = MEM_callocN(sizeof(MVert)*collmd->numverts,"current_xnew");
+ collmd->current_v = MEM_callocN(sizeof(MVert)*collmd->numverts,"current_v");
+ */
+
+ collmd->x = NULL;
+ collmd->xnew = NULL;
+ collmd->current_x = NULL;
+ collmd->current_xnew = NULL;
+ collmd->current_v = NULL;
+ collmd->time = -1;
+ collmd->numverts = 0;
+ collmd->bvhtree = NULL;
+ collmd->mfaces = NULL;
+
+ }
+ else if (md->type==eModifierType_Hook) {
HookModifierData *hmd = (HookModifierData*) md;
hmd->indexar= newdataadr(fd, hmd->indexar);
@@ -3093,7 +3320,6 @@ static void direct_link_object(FileData *fd, Object *ob)
sb->bpoint= NULL; // init pointers so it gets rebuilt nicely
sb->bspring= NULL;
sb->scratch= NULL;
-
/* although not used anymore */
/* still have to be loaded to be compatible with old files */
sb->keys= newdataadr(fd, sb->keys);
@@ -3103,15 +3329,13 @@ static void direct_link_object(FileData *fd, Object *ob)
sb->keys[a]= newdataadr(fd, sb->keys[a]);
}
}
+
+ sb->pointcache= newdataadr(fd, sb->pointcache);
+ if(sb->pointcache)
+ direct_link_pointcache(fd, sb->pointcache);
}
+ ob->bsoft= newdataadr(fd, ob->bsoft);
ob->fluidsimSettings= newdataadr(fd, ob->fluidsimSettings); /* NT */
- if(ob->fluidsimSettings) {
- // reinit mesh pointers
- ob->fluidsimSettings->orgMesh = NULL; //ob->data;
- ob->fluidsimSettings->meshSurface = NULL;
- ob->fluidsimSettings->meshBB = NULL;
- ob->fluidsimSettings->meshSurfNormals = NULL;
- }
link_list(fd, &ob->particlesystem);
direct_link_particlesystems(fd,&ob->particlesystem);
@@ -3136,11 +3360,19 @@ static void direct_link_object(FileData *fd, Object *ob)
direct_link_constraints(fd, &ob->constraints);
link_glob_list(fd, &ob->controllers);
+ if (ob->init_state) {
+ /* if a known first state is specified, set it so that the game will start ok */
+ ob->state = ob->init_state;
+ } else if (!ob->state) {
+ ob->state = 1;
+ }
cont= ob->controllers.first;
while(cont) {
cont->data= newdataadr(fd, cont->data);
cont->links= newdataadr(fd, cont->links);
test_pointer_array(fd, (void **)&cont->links);
+ if (cont->state_mask == 0)
+ cont->state_mask = 1;
cont= cont->next;
}
@@ -3185,6 +3417,7 @@ static void direct_link_object(FileData *fd, Object *ob)
ob->bb= NULL;
ob->derivedDeform= NULL;
ob->derivedFinal= NULL;
+ ob->gpulamp.first= ob->gpulamp.last= NULL;
}
/* ************ READ SCENE ***************** */
@@ -3340,6 +3573,10 @@ static void direct_link_scene(FileData *fd, Scene *sce)
if(seq->strip && seq->strip->done==0) {
seq->strip->done= 1;
seq->strip->tstripdata = 0;
+ seq->strip->tstripdata_startstill = 0;
+ seq->strip->tstripdata_endstill = 0;
+ seq->strip->ibuf_startstill = 0;
+ seq->strip->ibuf_endstill = 0;
if(seq->type == SEQ_IMAGE ||
seq->type == SEQ_MOVIE ||
@@ -3350,6 +3587,30 @@ static void direct_link_scene(FileData *fd, Scene *sce)
} else {
seq->strip->stripdata = 0;
}
+ if (seq->flag & SEQ_USE_CROP) {
+ seq->strip->crop = newdataadr(
+ fd, seq->strip->crop);
+ } else {
+ seq->strip->crop = 0;
+ }
+ if (seq->flag & SEQ_USE_TRANSFORM) {
+ seq->strip->transform = newdataadr(
+ fd, seq->strip->transform);
+ } else {
+ seq->strip->transform = 0;
+ }
+ if (seq->flag & SEQ_USE_PROXY) {
+ seq->strip->proxy = newdataadr(
+ fd, seq->strip->proxy);
+ } else {
+ seq->strip->proxy = 0;
+ }
+ if (seq->flag & SEQ_USE_COLOR_BALANCE) {
+ seq->strip->color_balance = newdataadr(
+ fd, seq->strip->color_balance);
+ } else {
+ seq->strip->color_balance = 0;
+ }
}
}
END_SEQ
@@ -3358,9 +3619,9 @@ static void direct_link_scene(FileData *fd, Scene *sce)
{
Sequence temp;
char *poin;
- long offset;
+ intptr_t offset;
- offset= ((long)&(temp.seqbase)) - ((long)&temp);
+ offset= ((intptr_t)&(temp.seqbase)) - ((intptr_t)&temp);
/* root pointer */
if(ed->seqbasep == old_seqbasep) {
@@ -3406,8 +3667,18 @@ static void direct_link_scene(FileData *fd, Scene *sce)
if (sce->r.qtcodecdata) {
sce->r.qtcodecdata->cdParms = newdataadr(fd, sce->r.qtcodecdata->cdParms);
}
-
+ if (sce->r.ffcodecdata.properties) {
+ sce->r.ffcodecdata.properties = newdataadr(
+ fd, sce->r.ffcodecdata.properties);
+ if (sce->r.ffcodecdata.properties) {
+ IDP_DirectLinkProperty(
+ sce->r.ffcodecdata.properties,
+ (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
+ }
+ }
+
link_list(fd, &(sce->markers));
+ link_list(fd, &(sce->transform_spaces));
link_list(fd, &(sce->r.layers));
sce->nodetree= newdataadr(fd, sce->nodetree);
@@ -3521,6 +3792,32 @@ static void lib_link_windowmanager(FileData *fd, Main *main)
/* ************ READ SCREEN ***************** */
+/* relinks grease-pencil data for 3d-view(s) - used for direct_link */
+static void link_gpencil(FileData *fd, bGPdata *gpd)
+{
+ bGPDlayer *gpl;
+ bGPDframe *gpf;
+ bGPDstroke *gps;
+
+ /* relink layers */
+ link_list(fd, &gpd->layers);
+
+ for (gpl= gpd->layers.first; gpl; gpl= gpl->next) {
+ /* relink frames */
+ link_list(fd, &gpl->frames);
+ gpl->actframe= newdataadr(fd, gpl->actframe);
+
+ for (gpf= gpl->frames.first; gpf; gpf= gpf->next) {
+ /* relink strokes (and their points) */
+ link_list(fd, &gpf->strokes);
+
+ for (gps= gpf->strokes.first; gps; gps= gps->next) {
+ gps->points= newdataadr(fd, gps->points);
+ }
+ }
+ }
+}
+
/* note: file read without screens option G_FILE_NO_UI;
check lib pointers in call below */
static void lib_link_screen(FileData *fd, Main *main)
@@ -3532,23 +3829,23 @@ static void lib_link_screen(FileData *fd, Main *main)
if(sc->id.flag & LIB_NEEDLINK) {
sc->id.us= 1;
sc->scene= newlibadr(fd, sc->id.lib, sc->scene);
-
+
sa= sc->areabase.first;
while(sa) {
SpaceLink *sl;
-
+
sa->full= newlibadr(fd, sc->id.lib, sa->full);
-
+
/* space handler scriptlinks */
lib_link_scriptlink(fd, &sc->id, &sa->scriptlink);
-
+
for (sl= sa->spacedata.first; sl; sl= sl->next) {
if(sl->spacetype==SPACE_VIEW3D) {
View3D *v3d= (View3D*) sl;
-
+
v3d->camera= newlibadr(fd, sc->id.lib, v3d->camera);
v3d->ob_centre= newlibadr(fd, sc->id.lib, v3d->ob_centre);
-
+
if(v3d->bgpic) {
v3d->bgpic->ima= newlibadr_us(fd, sc->id.lib, v3d->bgpic->ima);
}
@@ -3611,9 +3908,15 @@ static void lib_link_screen(FileData *fd, Main *main)
}
else if(sl->spacetype==SPACE_SCRIPT) {
- SpaceScript *sc= (SpaceScript *)sl;
- sc->script = NULL;
+ SpaceScript *scpt= (SpaceScript *)sl;
+ /*scpt->script = NULL; - 2.45 set to null, better re-run the script */
+ if (scpt->script) {
+ scpt->script= newlibadr(fd, sc->id.lib, scpt->script);
+ if (scpt->script) {
+ SCRIPT_SET_NULL(scpt->script)
+ }
+ }
}
else if(sl->spacetype==SPACE_OOPS) {
SpaceOops *so= (SpaceOops *)sl;
@@ -3686,7 +3989,9 @@ void lib_link_screen_restore(Main *newmain, Scene *curscene)
for(sc= newmain->screen.first; sc; sc= sc->id.next) {
- sc->scene= curscene;
+ sc->scene= restore_pointer_by_name(newmain, (ID *)sc->scene, 1);
+ if(sc->scene==NULL)
+ sc->scene= curscene;
sa= sc->areabase.first;
while(sa) {
@@ -3784,9 +4089,14 @@ void lib_link_screen_restore(Main *newmain, Scene *curscene)
if(st->text==NULL) st->text= newmain->text.first;
}
else if(sl->spacetype==SPACE_SCRIPT) {
- SpaceScript *sc= (SpaceScript *)sl;
-
- sc->script = NULL;
+ SpaceScript *scpt= (SpaceScript *)sl;
+
+ scpt->script= restore_pointer_by_name(newmain, (ID *)scpt->script, 1);
+
+ /*sc->script = NULL; - 2.45 set to null, better re-run the script */
+ if (scpt->script) {
+ SCRIPT_SET_NULL(scpt->script)
+ }
}
else if(sl->spacetype==SPACE_OOPS) {
SpaceOops *so= (SpaceOops *)sl;
@@ -3854,7 +4164,7 @@ static void direct_link_screen(FileData *fd, bScreen *sc)
for(se= sc->edgebase.first; se; se= se->next) {
se->v1= newdataadr(fd, se->v1);
se->v2= newdataadr(fd, se->v2);
- if( (long)se->v1 > (long)se->v2) {
+ if( (intptr_t)se->v1 > (intptr_t)se->v2) {
sv= se->v1;
se->v1= se->v2;
se->v2= sv;
@@ -3897,6 +4207,10 @@ static void direct_link_screen(FileData *fd, bScreen *sc)
v3d->bgpic= newdataadr(fd, v3d->bgpic);
if(v3d->bgpic)
v3d->bgpic->iuser.ok= 1;
+ if(v3d->gpd) {
+ v3d->gpd= newdataadr(fd, v3d->gpd);
+ link_gpencil(fd, v3d->gpd);
+ }
v3d->localvd= newdataadr(fd, v3d->localvd);
v3d->afterdraw.first= v3d->afterdraw.last= NULL;
v3d->clipbb= newdataadr(fd, v3d->clipbb);
@@ -3927,15 +4241,28 @@ static void direct_link_screen(FileData *fd, bScreen *sc)
sima->cumap= newdataadr(fd, sima->cumap);
if(sima->cumap)
direct_link_curvemapping(fd, sima->cumap);
- sima->info_str= sima->info_spare= NULL;
- sima->spare= NULL;
+ sima->gpd= newdataadr(fd, sima->gpd);
+ if (sima->gpd)
+ link_gpencil(fd, sima->gpd);
sima->iuser.ok= 1;
}
else if(sl->spacetype==SPACE_NODE) {
SpaceNode *snode= (SpaceNode *)sl;
+
+ if(snode->gpd) {
+ snode->gpd= newdataadr(fd, snode->gpd);
+ link_gpencil(fd, snode->gpd);
+ }
snode->nodetree= snode->edittree= NULL;
snode->flag |= SNODE_DO_PREVIEW;
}
+ else if(sl->spacetype==SPACE_SEQ) {
+ SpaceSeq *sseq= (SpaceSeq *)sl;
+ if(sseq->gpd) {
+ sseq->gpd= newdataadr(fd, sseq->gpd);
+ link_gpencil(fd, sseq->gpd);
+ }
+ }
}
for(ar= sa->regionbase.first; ar; ar= ar->next) {
@@ -4000,11 +4327,26 @@ static void direct_link_library(FileData *fd, Library *lib, Main *main)
static void lib_link_library(FileData *fd, Main *main)
{
Library *lib;
-
- lib= main->library.first;
- while(lib) {
+ for(lib= main->library.first; lib; lib= lib->id.next) {
lib->id.us= 1;
- lib= lib->id.next;
+ }
+}
+
+/* Always call this once you havbe loaded new library data to set the relative paths correctly in relation to the blend file */
+static void fix_relpaths_library(const char *basepath, Main *main)
+{
+ Library *lib;
+ /* BLO_read_from_memory uses a blank filename */
+ if (basepath==NULL || basepath[0] == '\0')
+ return;
+
+ for(lib= main->library.first; lib; lib= lib->id.next) {
+ /* Libraries store both relative and abs paths, recreate relative paths,
+ * relative to the blend file since indirectly linked libs will be relative to their direct linked library */
+ if (strncmp(lib->name, "//", 2)==0) { /* if this is relative to begin with? */
+ strncpy(lib->name, lib->filename, sizeof(lib->name));
+ BLI_makestringcode(basepath, lib->name);
+ }
}
}
@@ -4245,12 +4587,17 @@ static BHead *read_libblock(FileData *fd, Main *main, BHead *bhead, int flag, ID
case ID_PA:
direct_link_particlesettings(fd, (ParticleSettings*)id);
break;
+ case ID_SCRIPT:
+ direct_link_script(fd, (Script*)id);
+ break;
}
/*link direct data of ID properties*/
if (id->properties) {
id->properties = newdataadr(fd, id->properties);
- IDP_DirectLinkProperty(id->properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
+ if (id->properties) { /* this case means the data was written incorrectly, it should not happen */
+ IDP_DirectLinkProperty(id->properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
+ }
}
oldnewmap_free_unused(fd->datamap);
@@ -4566,6 +4913,118 @@ static void do_version_ntree_242_2(bNodeTree *ntree)
}
}
+static void ntree_version_245(FileData *fd, Library *lib, bNodeTree *ntree)
+{
+ bNode *node;
+ NodeTwoFloats *ntf;
+ ID *nodeid;
+ Image *image;
+ ImageUser *iuser;
+
+ if(ntree->type==NTREE_COMPOSIT) {
+ for(node= ntree->nodes.first; node; node= node->next) {
+ if(node->type == CMP_NODE_ALPHAOVER) {
+ if(!node->storage) {
+ ntf= MEM_callocN(sizeof(NodeTwoFloats), "NodeTwoFloats");
+ node->storage= ntf;
+ if(node->custom1)
+ ntf->x= 1.0f;
+ }
+ }
+
+ /* fix for temporary flag changes during 245 cycle */
+ nodeid= newlibadr(fd, lib, node->id);
+ if(node->storage && nodeid && GS(nodeid->name) == ID_IM) {
+ image= (Image*)nodeid;
+ iuser= node->storage;
+ if(iuser->flag & IMA_OLD_PREMUL) {
+ iuser->flag &= ~IMA_OLD_PREMUL;
+ iuser->flag |= IMA_DO_PREMUL;
+ }
+ if(iuser->flag & IMA_DO_PREMUL) {
+ image->flag &= ~IMA_OLD_PREMUL;
+ image->flag |= IMA_DO_PREMUL;
+ }
+ }
+ }
+ }
+}
+
+static void idproperties_fix_groups_lengths_recurse(IDProperty *prop)
+{
+ IDProperty *loop;
+ int i;
+
+ for (loop=prop->data.group.first, i=0; loop; loop=loop->next, i++) {
+ if (loop->type == IDP_GROUP) idproperties_fix_groups_lengths_recurse(loop);
+ }
+
+ if (prop->len != i) {
+ printf("Found and fixed bad id property group length.\n");
+ prop->len = i;
+ }
+}
+
+static void idproperties_fix_group_lengths(ListBase idlist)
+{
+ ID *id;
+
+ for (id=idlist.first; id; id=id->next) {
+ if (id->properties) {
+ idproperties_fix_groups_lengths_recurse(id->properties);
+ }
+ }
+}
+
+static void alphasort_version_246(FileData *fd, Library *lib, Mesh *me)
+{
+ Material *ma;
+ MFace *mf;
+ MTFace *tf;
+ int a, b, texalpha;
+
+ /* verify we have a tface layer */
+ for(b=0; b<me->fdata.totlayer; b++)
+ if(me->fdata.layers[b].type == CD_MTFACE)
+ break;
+
+ if(b == me->fdata.totlayer)
+ return;
+
+ /* if we do, set alpha sort if the game engine did it before */
+ for(a=0, mf=me->mface; a<me->totface; a++, mf++) {
+ if(mf->mat_nr < me->totcol) {
+ ma= newlibadr(fd, lib, me->mat[mf->mat_nr]);
+ texalpha = 0;
+
+ /* we can't read from this if it comes from a library,
+ * because direct_link might not have happened on it,
+ * so ma->mtex is not pointing to valid memory yet */
+ if(ma && ma->id.lib)
+ ma= NULL;
+
+ for(b=0; ma && b<MAX_MTEX; b++)
+ if(ma->mtex && ma->mtex[b] && ma->mtex[b]->mapto & MAP_ALPHA)
+ texalpha = 1;
+ }
+ else {
+ ma= NULL;
+ texalpha = 0;
+ }
+
+ for(b=0; b<me->fdata.totlayer; b++) {
+ if(me->fdata.layers[b].type == CD_MTFACE) {
+ tf = ((MTFace*)me->fdata.layers[b].data) + a;
+
+ tf->mode &= ~TF_ALPHASORT;
+ if(ma && (ma->mode & MA_ZTRA))
+ if(ELEM(tf->transp, TF_ALPHA, TF_ADD) || (texalpha && (tf->transp != TF_CLIP)))
+ tf->mode |= TF_ALPHASORT;
+ }
+ }
+ }
+}
+
static void do_versions_windowmanager_2_50(bScreen *screen)
{
struct ScrArea *sa;
@@ -4908,7 +5367,7 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
while(ob) {
ob->mass= 1.0f;
ob->damping= 0.1f;
- ob->quat[1]= 1.0f;
+ /*ob->quat[1]= 1.0f;*/ /* quats arnt used yet */
ob= ob->id.next;
}
@@ -4978,7 +5437,7 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
while (act) {
if(act->type==ACT_IPO) {
ia= act->data;
- prop= get_property(ob, ia->name);
+ prop= get_ob_property(ob, ia->name);
if(prop) {
ia->type= ACT_IPO_FROM_PROP;
}
@@ -6282,7 +6741,7 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
sce->toolsettings->uvcalc_cubesize = 1.0f;
sce->toolsettings->uvcalc_mapdir = 1;
sce->toolsettings->uvcalc_mapalign = 1;
- sce->toolsettings->uvcalc_flag = 1;
+ sce->toolsettings->uvcalc_flag = UVCALC_FILLHOLES;
sce->toolsettings->unwrapper = 1;
}
@@ -6746,7 +7205,12 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
Lamp *la;
Material *ma;
ParticleSettings *part;
+ World *wrld;
Mesh *me;
+ bNodeTree *ntree;
+ Tex *tex;
+ ModifierData *md;
+ ParticleSystem *psys;
/* unless the file was created 2.44.3 but not 2.45, update the constraints */
if ( !(main->versionfile==244 && main->subversionfile==3) &&
@@ -6776,14 +7240,6 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
curcon->ownspace = CONSTRAINT_SPACE_LOCAL;
}
break;
- case CONSTRAINT_TYPE_STRETCHTO:
- {
- bStretchToConstraint *data= (bStretchToConstraint *)curcon->data;
-
- /* force recalc of rest-length */
- data->orglength = 0;
- }
- break;
}
}
}
@@ -6815,14 +7271,6 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
curcon->tarspace = CONSTRAINT_SPACE_LOCAL;
}
break;
- case CONSTRAINT_TYPE_STRETCHTO:
- {
- bStretchToConstraint *data= (bStretchToConstraint *)curcon->data;
-
- /* force recalc of rest-length */
- data->orglength = 0;
- }
- break;
}
}
@@ -6887,6 +7335,27 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
}
}
+ /* add point caches */
+ for(ob=main->object.first; ob; ob=ob->id.next) {
+ if(ob->soft && !ob->soft->pointcache)
+ ob->soft->pointcache= BKE_ptcache_add();
+
+ for(psys=ob->particlesystem.first; psys; psys=psys->next) {
+ if(psys->soft && !psys->soft->pointcache)
+ psys->soft->pointcache= BKE_ptcache_add();
+ if(!psys->pointcache)
+ psys->pointcache= BKE_ptcache_add();
+ }
+
+ for(md=ob->modifiers.first; md; md=md->next) {
+ if(md->type==eModifierType_Cloth) {
+ ClothModifierData *clmd = (ClothModifierData*) md;
+ if(!clmd->point_cache)
+ clmd->point_cache= BKE_ptcache_add();
+ }
+ }
+ }
+
/* Copy over old per-level multires vertex data
into a single vertex array in struct Multires */
for(me = main->mesh.first; me; me=me->id.next) {
@@ -6942,6 +7411,54 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
}
}
+ for(wrld=main->world.first; wrld; wrld= wrld->id.next) {
+ if(wrld->ao_approx_error == 0.0f)
+ wrld->ao_approx_error= 0.25f;
+ }
+
+ for(sce= main->scene.first; sce; sce= sce->id.next) {
+ if(sce->nodetree)
+ ntree_version_245(fd, lib, sce->nodetree);
+
+ if(sce->r.simplify_shadowsamples == 0) {
+ sce->r.simplify_subsurf= 6;
+ sce->r.simplify_particles= 1.0f;
+ sce->r.simplify_shadowsamples= 16;
+ sce->r.simplify_aosss= 1.0f;
+ }
+
+ if(sce->r.cineongamma == 0) {
+ sce->r.cineonblack= 95;
+ sce->r.cineonwhite= 685;
+ sce->r.cineongamma= 1.7f;
+ }
+ }
+
+ for(ntree=main->nodetree.first; ntree; ntree= ntree->id.next)
+ ntree_version_245(fd, lib, ntree);
+
+ /* fix for temporary flag changes during 245 cycle */
+ for(ima= main->image.first; ima; ima= ima->id.next) {
+ if(ima->flag & IMA_OLD_PREMUL) {
+ ima->flag &= ~IMA_OLD_PREMUL;
+ ima->flag |= IMA_DO_PREMUL;
+ }
+ }
+
+ for(tex=main->tex.first; tex; tex=tex->id.next) {
+ if(tex->iuser.flag & IMA_OLD_PREMUL) {
+ tex->iuser.flag &= ~IMA_OLD_PREMUL;
+ tex->iuser.flag |= IMA_DO_PREMUL;
+
+ }
+
+ ima= newlibadr(fd, lib, tex->ima);
+ if(ima && (tex->iuser.flag & IMA_DO_PREMUL)) {
+ ima->flag &= ~IMA_OLD_PREMUL;
+ ima->flag |= IMA_DO_PREMUL;
+ }
+ }
+
if (main->versionfile < 245 || main->subversionfile < 12)
{
/* initialize skeleton generation toolsettings */
@@ -6964,6 +7481,24 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
}
}
}
+
+ /* sanity check for skgen
+ * */
+ {
+ Scene *sce;
+ for(sce=main->scene.first; sce; sce = sce->id.next)
+ {
+ if (sce->toolsettings->skgen_subdivisions[0] == sce->toolsettings->skgen_subdivisions[1] ||
+ sce->toolsettings->skgen_subdivisions[0] == sce->toolsettings->skgen_subdivisions[2] ||
+ sce->toolsettings->skgen_subdivisions[1] == sce->toolsettings->skgen_subdivisions[2])
+ {
+ sce->toolsettings->skgen_subdivisions[0] = SKGEN_SUB_CORRELATION;
+ sce->toolsettings->skgen_subdivisions[1] = SKGEN_SUB_LENGTH;
+ sce->toolsettings->skgen_subdivisions[2] = SKGEN_SUB_ANGLE;
+ }
+ }
+ }
+
if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 2)) {
Image *ima;
@@ -7092,62 +7627,6 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
sb->keys = NULL;
sb->totkey = 0;
- ob->softflag &= ~OB_SB_BAKESET;
- }
- }
- }
-
- if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 7)) {
- Object *ob;
- bPoseChannel *pchan;
- bConstraint *con;
- bConstraintTarget *ct;
-
- for(ob = main->object.first; ob; ob= ob->id.next) {
- if(ob->pose) {
- for(pchan=ob->pose->chanbase.first; pchan; pchan=pchan->next) {
- for(con=pchan->constraints.first; con; con=con->next) {
- if(con->type==CONSTRAINT_TYPE_PYTHON) {
- bPythonConstraint *data= (bPythonConstraint *)con->data;
- if (data->tar) {
- /* version patching needs to be done */
- ct= MEM_callocN(sizeof(bConstraintTarget), "PyConTarget");
-
- ct->tar = data->tar;
- strcpy(ct->subtarget, data->subtarget);
- ct->space = con->tarspace;
-
- BLI_addtail(&data->targets, ct);
- data->tarnum++;
-
- /* clear old targets to avoid problems */
- data->tar = NULL;
- strcpy(data->subtarget, "");
- }
- }
- }
- }
- }
-
- for(con=ob->constraints.first; con; con=con->next) {
- if(con->type==CONSTRAINT_TYPE_PYTHON) {
- bPythonConstraint *data= (bPythonConstraint *)con->data;
- if (data->tar) {
- /* version patching needs to be done */
- ct= MEM_callocN(sizeof(bConstraintTarget), "PyConTarget");
-
- ct->tar = data->tar;
- strcpy(ct->subtarget, data->subtarget);
- ct->space = con->tarspace;
-
- BLI_addtail(&data->targets, ct);
- data->tarnum++;
-
- /* clear old targets to avoid problems */
- data->tar = NULL;
- strcpy(data->subtarget, "");
- }
- }
}
}
}
@@ -7171,7 +7650,6 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
sb->keys = NULL;
sb->totkey = 0;
- ob->softflag &= ~OB_SB_BAKESET;
}
/* convert old particles to new system */
@@ -7183,17 +7661,19 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
/* create new particle system */
psys = MEM_callocN(sizeof(ParticleSystem), "particle_system");
+ psys->pointcache = BKE_ptcache_add();
part = psys->part = psys_new_settings("PSys", main);
/* needed for proper libdata lookup */
oldnewmap_insert(fd->libmap, psys->part, psys->part, 0);
+ part->id.lib= ob->id.lib;
part->id.us--;
part->id.flag |= (ob->id.flag & LIB_NEEDLINK);
psys->totpart=0;
- psys->flag=PSYS_ENABLED|PSYS_CURRENT;
+ psys->flag= PSYS_ENABLED|PSYS_CURRENT;
BLI_addtail(&ob->particlesystem, psys);
@@ -7217,6 +7697,9 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
part->eff_group = paf->group;
+ /* old system didn't interpolate between keypoints at render time */
+ part->draw_step = part->ren_step = 0;
+
/* physics */
part->normfac = paf->normfac * 25.0f;
part->obfac = paf->obfac;
@@ -7269,10 +7752,20 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
ob->transflag &= ~OB_DUPLIVERTS;
part->draw_as = PART_DRAW_OB;
+
+ /* needed for proper libdata lookup */
+ oldnewmap_insert(fd->libmap, dup, dup, 0);
}
}
}
+
+ {
+ FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
+ if(fluidmd && fluidmd->fss && fluidmd->fss->type == OB_FLUIDSIM_PARTICLE)
+ part->type = PART_FLUID;
+ }
+
free_effects(&ob->effect);
printf("Old particle system converted to new system.\n");
@@ -7340,17 +7833,259 @@ static void do_versions(FileData *fd, Library *lib, Main *main)
strip->scale = length / (repeat * actlength);
if (strip->scale == 0.0f) strip->scale= 1.0f;
}
+ if(ob->soft){
+ ob->soft->inpush = ob->soft->inspring;
+ ob->soft->shearstiff = 1.0f;
+ }
}
}
+
+ if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 14)) {
+ Scene *sce= main->scene.first;
+ Sequence *seq;
+ Editing *ed;
+ while(sce) {
+ ed= sce->ed;
+ if(ed) {
+ WHILE_SEQ(&ed->seqbase) {
+ if (seq->blend_mode == 0) {
+ seq->blend_opacity = 100.0;
+ }
+ }
+ END_SEQ
+ }
+
+ sce= sce->id.next;
+ }
+ }
+
+ /*fix broken group lengths in id properties*/
+ if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 15)) {
+ idproperties_fix_group_lengths(main->scene);
+ idproperties_fix_group_lengths(main->library);
+ idproperties_fix_group_lengths(main->object);
+ idproperties_fix_group_lengths(main->mesh);
+ idproperties_fix_group_lengths(main->curve);
+ idproperties_fix_group_lengths(main->mball);
+ idproperties_fix_group_lengths(main->mat);
+ idproperties_fix_group_lengths(main->tex);
+ idproperties_fix_group_lengths(main->image);
+ idproperties_fix_group_lengths(main->wave);
+ idproperties_fix_group_lengths(main->latt);
+ idproperties_fix_group_lengths(main->lamp);
+ idproperties_fix_group_lengths(main->camera);
+ idproperties_fix_group_lengths(main->ipo);
+ idproperties_fix_group_lengths(main->key);
+ idproperties_fix_group_lengths(main->world);
+ idproperties_fix_group_lengths(main->screen);
+ idproperties_fix_group_lengths(main->script);
+ idproperties_fix_group_lengths(main->vfont);
+ idproperties_fix_group_lengths(main->text);
+ idproperties_fix_group_lengths(main->sound);
+ idproperties_fix_group_lengths(main->group);
+ idproperties_fix_group_lengths(main->armature);
+ idproperties_fix_group_lengths(main->action);
+ idproperties_fix_group_lengths(main->nodetree);
+ idproperties_fix_group_lengths(main->brush);
+ idproperties_fix_group_lengths(main->particle);
+ }
+
+ /* sun/sky */
+ if(main->versionfile < 246) {
+ Object *ob;
+ bActuator *act;
+
+ /* dRot actuator change direction in 2.46 */
+ for(ob = main->object.first; ob; ob= ob->id.next) {
+ for(act= ob->actuators.first; act; act= act->next) {
+ if (act->type == ACT_OBJECT) {
+ bObjectActuator *ba= act->data;
+
+ ba->drot[0] = -ba->drot[0];
+ ba->drot[1] = -ba->drot[1];
+ ba->drot[2] = -ba->drot[2];
+ }
+ }
+ }
+ }
+
+ // convert fluids to modifier
+ if(main->versionfile < 246 || (main->versionfile == 246 && main->subversionfile < 1))
+ {
+ Object *ob;
+ for(ob = main->object.first; ob; ob= ob->id.next) {
+ if(ob->fluidsimSettings)
+ {
+ FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifier_new(eModifierType_Fluidsim);
+ BLI_addhead(&ob->modifiers, (ModifierData *)fluidmd);
+
+ MEM_freeN(fluidmd->fss);
+ fluidmd->fss = MEM_dupallocN(ob->fluidsimSettings);
+ fluidmd->fss->ipo = newlibadr_us(fd, ob->id.lib, ob->fluidsimSettings->ipo);
+ MEM_freeN(ob->fluidsimSettings);
+
+ fluidmd->fss->lastgoodframe = INT_MAX;
+ fluidmd->fss->flag = 0;
+ }
+ }
+ }
+
+
+ if(main->versionfile < 246 || (main->versionfile == 246 && main->subversionfile < 1)) {
+ Mesh *me;
+
+ for(me=main->mesh.first; me; me= me->id.next)
+ alphasort_version_246(fd, lib, me);
+ }
+
+ if(main->versionfile < 246 || (main->versionfile == 246 && main->subversionfile < 1)){
+ Object *ob;
+ for(ob = main->object.first; ob; ob= ob->id.next) {
+ if(ob->pd && (ob->pd->forcefield == PFIELD_WIND))
+ ob->pd->f_noise = 0.0;
+ }
+ }
+
+ if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 2)){
+ Object *ob;
+ for(ob = main->object.first; ob; ob= ob->id.next) {
+ ob->gameflag |= OB_COLLISION;
+ ob->margin = 0.06;
+ }
+ }
+
+ if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 3)){
+ Object *ob;
+ for(ob = main->object.first; ob; ob= ob->id.next) {
+ // Starting from subversion 3, ACTOR is a separate feature.
+ // Before it was conditioning all the other dynamic flags
+ if (!(ob->gameflag & OB_ACTOR))
+ ob->gameflag &= ~(OB_GHOST|OB_DYNAMIC|OB_RIGID_BODY|OB_SOFT_BODY|OB_COLLISION_RESPONSE);
+ /* suitable default for older files */
+ }
+ }
+
+ if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 4)){
+ Scene *sce= main->scene.first;
+ while(sce) {
+ if(sce->frame_step==0)
+ sce->frame_step= 1;
+ sce= sce->id.next;
+ }
+ }
+
+ if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 5)) {
+ Lamp *la= main->lamp.first;
+ for(; la; la= la->id.next) {
+ la->skyblendtype= MA_RAMP_ADD;
+ la->skyblendfac= 1.0f;
+ }
+ }
+
+ /* set the curve radius interpolation to 2.47 default - easy */
+ if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 6)) {
+ Curve *cu;
+ Nurb *nu;
+
+ for(cu= main->curve.first; cu; cu= cu->id.next) {
+ for(nu= cu->nurb.first; nu; nu= nu->next) {
+ if (nu) {
+ nu->radius_interp = 3;
+
+ /* resolu and resolv are now used differently for surfaces
+ * rather then using the resolution to define the entire number of divisions,
+ * use it for the number of divisions per segment
+ */
+ if (nu->pntsv > 1) {
+ nu->resolu = MAX2( 1, (int)(((float)nu->resolu / (float)nu->pntsu)+0.5f) );
+ nu->resolv = MAX2( 1, (int)(((float)nu->resolv / (float)nu->pntsv)+0.5f) );
+ }
+ }
+ }
+ }
+ }
+ /* direction constraint actuators were always local in previous version */
+ if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 7)) {
+ bActuator *act;
+ Object *ob;
+
+ for(ob = main->object.first; ob; ob= ob->id.next) {
+ for(act= ob->actuators.first; act; act= act->next) {
+ if (act->type == ACT_CONSTRAINT) {
+ bConstraintActuator *coa = act->data;
+ if (coa->type == ACT_CONST_TYPE_DIST) {
+ coa->flag |= ACT_CONST_LOCAL;
+ }
+ }
+ }
+ }
+ }
+ /* autokey mode settings now used from scene, but need to be initialised off userprefs */
+ if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 8)) {
+ Scene *sce;
+
+ for (sce= main->scene.first; sce; sce= sce->id.next) {
+ if (sce->autokey_mode == 0)
+ sce->autokey_mode= U.autokey_mode;
+ }
+ }
+
+ if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 9)) {
+ Lamp *la= main->lamp.first;
+ for(; la; la= la->id.next) {
+ la->sky_exposure= 1.0f;
+ }
+ }
+
+ /* BGE message actuators needed OB prefix, very confusing */
+ if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 10)) {
+ bActuator *act;
+ Object *ob;
+
+ for(ob = main->object.first; ob; ob= ob->id.next) {
+ for(act= ob->actuators.first; act; act= act->next) {
+ if (act->type == ACT_MESSAGE) {
+ bMessageActuator *msgAct = (bMessageActuator *) act->data;
+ if (strlen(msgAct->toPropName) > 2) {
+ /* strip first 2 chars, would have only worked if these were OB anyway */
+ memmove( msgAct->toPropName, msgAct->toPropName+2, sizeof(msgAct->toPropName)-2 );
+ } else {
+ msgAct->toPropName[0] = '\0';
+ }
+ }
+ }
+ }
+ }
+
+ if (main->versionfile < 248) {
+ Lamp *la;
+
+ for(la=main->lamp.first; la; la= la->id.next) {
+ if(la->atm_turbidity == 0.0) {
+ la->sun_effect_type = 0;
+ la->horizon_brightness = 1.0;
+ la->spread = 1.0;
+ la->sun_brightness = 1.0;
+ la->sun_size = 1.0;
+ la->backscattered_light = 1.0;
+ la->atm_turbidity = 2.0;
+ la->atm_inscattering_factor = 1.0;
+ la->atm_extinction_factor = 1.0;
+ la->atm_distance_factor = 1.0;
+ la->sun_intensity = 1.0;
+ }
+ }
+ }
+
if (main->versionfile < 250) {
bScreen *screen;
for(screen= main->screen.first; screen; screen= screen->id.next)
do_versions_windowmanager_2_50(screen);
}
-
+
/* WATCH IT!!!: pointers from libdata have not been converted yet here! */
/* WATCH IT 2!: Userdef struct init has to be in src/usiblender.c! */
@@ -7461,13 +8196,14 @@ BlendFileData *blo_read_file_internal(FileData *fd, BlendReadError *error_r)
/* do before read_libraries, but skip undo case */
// if(fd->memfile==NULL) (the mesh shuffle hacks don't work yet? ton)
do_versions(fd, NULL, bfd->main);
-
+
read_libraries(fd, &fd->mainlist);
blo_join_main(&fd->mainlist);
lib_link_all(fd, bfd->main);
- lib_verify_nodetree(bfd->main);
+ lib_verify_nodetree(bfd->main, 1);
+ fix_relpaths_library(fd->filename, bfd->main); /* make all relative paths, relative to the open blend file */
link_global(fd, bfd); /* as last */
@@ -7476,6 +8212,43 @@ BlendFileData *blo_read_file_internal(FileData *fd, BlendReadError *error_r)
/* ************* APPEND LIBRARY ************** */
+struct bheadsort {
+ BHead *bhead;
+ void *old;
+};
+
+static int verg_bheadsort(const void *v1, const void *v2)
+{
+ const struct bheadsort *x1=v1, *x2=v2;
+
+ if( x1->old > x2->old) return 1;
+ else if( x1->old < x2->old) return -1;
+ return 0;
+}
+
+static void sort_bhead_old_map(FileData *fd)
+{
+ BHead *bhead;
+ struct bheadsort *bhs;
+ int tot= 0;
+
+ for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead))
+ tot++;
+
+ fd->tot_bheadmap= tot;
+ if(tot==0) return;
+
+ bhs= fd->bheadmap= MEM_mallocN(tot*sizeof(struct bheadsort), "bheadsort");
+
+ for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead), bhs++) {
+ bhs->bhead= bhead;
+ bhs->old= bhead->old;
+ }
+
+ qsort(fd->bheadmap, tot, sizeof(struct bheadsort), verg_bheadsort);
+
+}
+
static BHead *find_previous_lib(FileData *fd, BHead *bhead)
{
for (; bhead; bhead= blo_prevbhead(fd, bhead))
@@ -7487,14 +8260,28 @@ static BHead *find_previous_lib(FileData *fd, BHead *bhead)
static BHead *find_bhead(FileData *fd, void *old)
{
+#if 0
BHead *bhead;
-
+#endif
+ struct bheadsort *bhs, bhs_s;
+
if (!old)
return NULL;
+ if (fd->bheadmap==NULL)
+ sort_bhead_old_map(fd);
+
+ bhs_s.old= old;
+ bhs= bsearch(&bhs_s, fd->bheadmap, fd->tot_bheadmap, sizeof(struct bheadsort), verg_bheadsort);
+
+ if(bhs)
+ return bhs->bhead;
+
+#if 0
for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead))
if (bhead->old==old)
return bhead;
+#endif
return NULL;
}
@@ -7547,7 +8334,13 @@ static void expand_doit(FileData *fd, Main *mainvar, void *old)
ptr->curlib->parent= mainvar->curlib;
}
else {
- //oldnewmap_insert(fd->libmap, bhead->old, id, 1);
+ /* The line below was commented by Ton (I assume), when Hos did the merge from the orange branch. rev 6568
+ * This line is NEEDED, the case is that you have 3 blend files...
+ * user.blend, lib.blend and lib_indirect.blend - if user.blend alredy references a "tree" from
+ * lib_indirect.blend but lib.blend does too, linking in a Scene or Group from lib.blend can result in an
+ * empty without the dupli group referenced. Once you save and reload the group would appier. - Campbell */
+ /* This crashes files, must look further into it */
+ /*oldnewmap_insert(fd->libmap, bhead->old, id, 1);*/
change_idid_adr_fd(fd, bhead->old, id);
if(G.f & G_DEBUG) printf("expand_doit: already linked: %s lib: %s\n", id->name, lib->name);
@@ -7571,6 +8364,14 @@ static void expand_doit(FileData *fd, Main *mainvar, void *old)
}
}
+static void expand_particlesettings(FileData *fd, Main *mainvar, ParticleSettings *part)
+{
+ expand_doit(fd, mainvar, part->dup_ob);
+ expand_doit(fd, mainvar, part->dup_group);
+ expand_doit(fd, mainvar, part->eff_group);
+ expand_doit(fd, mainvar, part->bb_ob);
+}
+
static void expand_ipo(FileData *fd, Main *mainvar, Ipo *ipo)
{
IpoCurve *icu;
@@ -7841,6 +8642,12 @@ static void expand_constraints(FileData *fd, Main *mainvar, ListBase *lb)
expand_doit(fd, mainvar, data->tar);
}
break;
+ case CONSTRAINT_TYPE_DISTLIMIT:
+ {
+ bDistLimitConstraint *data = (bDistLimitConstraint*)curcon->data;
+ expand_doit(fd, mainvar, data->tar);
+ }
+ break;
default:
break;
}
@@ -7919,6 +8726,12 @@ static void expand_modifier(FileData *fd, Main *mainvar, ModifierData *md)
expand_doit(fd, mainvar, mmd->mirror_ob);
}
+ else if (md->type==eModifierType_Displace) {
+ DisplaceModifierData *dmd = (DisplaceModifierData*) md;
+
+ expand_doit(fd, mainvar, dmd->map_object);
+ expand_doit(fd, mainvar, dmd->texture);
+ }
}
static void expand_scriptlink(FileData *fd, Main *mainvar, ScriptLink *slink)
@@ -7945,6 +8758,7 @@ static void expand_object(FileData *fd, Main *mainvar, Object *ob)
expand_doit(fd, mainvar, ob->data);
expand_doit(fd, mainvar, ob->ipo);
expand_doit(fd, mainvar, ob->action);
+ expand_doit(fd, mainvar, ob->poselib);
for (md=ob->modifiers.first; md; md=md->next) {
expand_modifier(fd, mainvar, md);
@@ -7981,9 +8795,6 @@ static void expand_object(FileData *fd, Main *mainvar, Object *ob)
sens= ob->sensors.first;
while(sens) {
- for(a=0; a<sens->totlinks; a++) {
- sens->links[a]= newglobadr(fd, sens->links[a]);
- }
if(sens->type==SENS_TOUCH) {
bTouchSensor *ts= sens->data;
expand_doit(fd, mainvar, ts->ma);
@@ -7997,9 +8808,6 @@ static void expand_object(FileData *fd, Main *mainvar, Object *ob)
cont= ob->controllers.first;
while(cont) {
- for(a=0; a<cont->totlinks; a++) {
- cont->links[a]= newglobadr(fd, cont->links[a]);
- }
if(cont->type==CONT_PYTHON) {
bPythonCont *pc= cont->data;
expand_doit(fd, mainvar, pc->text);
@@ -8033,6 +8841,10 @@ static void expand_object(FileData *fd, Main *mainvar, Object *ob)
bActionActuator *aa= act->data;
expand_doit(fd, mainvar, aa->act);
}
+ else if(act->type==ACT_SHAPEACTION) {
+ bActionActuator *aa= act->data;
+ expand_doit(fd, mainvar, aa->act);
+ }
else if(act->type==ACT_PROPERTY) {
bPropertyActuator *pa= act->data;
expand_doit(fd, mainvar, pa->ob);
@@ -8043,6 +8855,9 @@ static void expand_object(FileData *fd, Main *mainvar, Object *ob)
}
act= act->next;
}
+
+ if(ob->pd && ob->pd->tex)
+ expand_doit(fd, mainvar, ob->pd->tex);
expand_scriptlink(fd, mainvar, &ob->scriptlink);
}
@@ -8156,6 +8971,8 @@ static void expand_main(FileData *fd, Main *mainvar)
case ID_IP:
expand_ipo(fd, mainvar, (Ipo *)id);
break;
+ case ID_PA:
+ expand_particlesettings(fd, mainvar, (ParticleSettings *)id);
}
doit= 1;
@@ -8179,34 +8996,42 @@ static int object_in_any_scene(Object *ob)
}
/* when *lib set, it also does objects that were in the appended group */
-static void give_base_to_objects(Scene *sce, ListBase *lb, Library *lib)
+static void give_base_to_objects(Scene *sce, ListBase *lb, Library *lib, int is_group_append)
{
Object *ob;
Base *base;
/* give all objects which are LIB_INDIRECT a base, or for a group when *lib has been set */
for(ob= lb->first; ob; ob= ob->id.next) {
-
+
if( ob->id.flag & LIB_INDIRECT ) {
- int do_it= 0;
- if(ob->id.us==0)
- do_it= 1;
- else if(ob->id.us==1 && lib)
- if(ob->id.lib==lib && (ob->flag & OB_FROMGROUP) && object_in_any_scene(ob)==0)
+ /* IF below is quite confusing!
+ if we are appending, but this object wasnt just added allong with a group,
+ then this is alredy used indirectly in the scene somewhere else and we didnt just append it.
+
+ (ob->id.flag & LIB_APPEND_TAG)==0 means that this is a newly appended object - Campbell */
+ if (is_group_append==0 || (ob->id.flag & LIB_APPEND_TAG)==0) {
+
+ int do_it= 0;
+
+ if(ob->id.us==0)
do_it= 1;
+ else if(ob->id.us==1 && lib)
+ if(ob->id.lib==lib && (ob->flag & OB_FROMGROUP) && object_in_any_scene(ob)==0)
+ do_it= 1;
+
+ if(do_it) {
+ base= MEM_callocN( sizeof(Base), "add_ext_base");
+ BLI_addtail(&(sce->base), base);
+ base->lay= ob->lay;
+ base->object= ob;
+ base->flag= ob->flag;
+ ob->id.us= 1;
- if(do_it) {
- base= MEM_callocN( sizeof(Base), "add_ext_base");
- BLI_addtail(&(sce->base), base);
- base->lay= ob->lay;
- base->object= ob;
- base->flag= ob->flag;
- ob->id.us= 1;
-
- ob->id.flag -= LIB_INDIRECT;
- ob->id.flag |= LIB_EXTERN;
-
+ ob->id.flag -= LIB_INDIRECT;
+ ob->id.flag |= LIB_EXTERN;
+ }
}
}
}
@@ -8295,38 +9120,38 @@ static void append_id_part(FileData *fd, Main *mainvar, ID *id, ID **id_r)
/* common routine to append/link something from a library */
static Library* library_append(Scene *scene, char* file, char *dir, int idcode,
- int totsel, FileData *fd, struct direntry* filelist, int totfile, short flag)
+ int totsel, FileData **fd, struct direntry* filelist, int totfile, short flag)
{
Main *mainl;
Library *curlib;
/* make mains */
- blo_split_main(&fd->mainlist, G.main);
+ blo_split_main(&(*fd)->mainlist, G.main);
/* which one do we need? */
- mainl = blo_find_main(fd, &fd->mainlist, dir, G.sce);
+ mainl = blo_find_main(*fd, &(*fd)->mainlist, dir, G.sce);
- mainl->versionfile= fd->fileversion; /* needed for do_version */
+ mainl->versionfile= (*fd)->fileversion; /* needed for do_version */
curlib= mainl->curlib;
if(totsel==0) {
- append_named_part(fd, mainl, scene, file, idcode, flag);
+ append_named_part(*fd, mainl, scene, file, idcode, flag);
}
else {
int a;
for(a=0; a<totfile; a++) {
if(filelist[a].flags & ACTIVE) {
- append_named_part(fd, mainl, scene, filelist[a].relname, idcode, flag);
+ append_named_part(*fd, mainl, scene, filelist[a].relname, idcode, flag);
}
}
}
/* make main consistant */
- expand_main(fd, mainl);
+ expand_main(*fd, mainl);
/* do this when expand found other libs */
- read_libraries(fd, &fd->mainlist);
+ read_libraries(*fd, &(*fd)->mainlist);
if(flag & FILE_STRINGCODE) {
@@ -8337,25 +9162,31 @@ static Library* library_append(Scene *scene, char* file, char *dir, int idcode,
BLI_makestringcode(G.sce, mainl->curlib->name);
}
- blo_join_main(&fd->mainlist);
- G.main= fd->mainlist.first;
+ blo_join_main(&(*fd)->mainlist);
+ G.main= (*fd)->mainlist.first;
- lib_link_all(fd, G.main);
- lib_verify_nodetree(G.main);
+ lib_link_all(*fd, G.main);
+ lib_verify_nodetree(G.main, 0);
+ fix_relpaths_library(G.sce, G.main); /* make all relative paths, relative to the open blend file */
/* give a base to loose objects. If group append, do it for objects too */
- if(idcode==ID_GR)
- give_base_to_objects(scene, &(G.main->object), (flag & FILE_LINK)?NULL:curlib);
- else
- give_base_to_objects(scene, &(G.main->object), NULL);
-
+ if(idcode==ID_GR) {
+ if (flag & FILE_LINK) {
+ give_base_to_objects(scene, &(G.main->object), NULL, 0);
+ } else {
+ give_base_to_objects(scene, &(G.main->object), curlib, 1);
+ }
+ } else {
+ give_base_to_objects(scene, &(G.main->object), NULL, 0);
+ }
/* has been removed... erm, why? s..ton) */
/* 20040907: looks like they are give base already in append_named_part(); -Nathan L */
/* 20041208: put back. It only linked direct, not indirect objects (ton) */
/* patch to prevent switch_endian happens twice */
- if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
- blo_freefiledata( fd );
+ if((*fd)->flags & FD_FLAGS_SWITCH_ENDIAN) {
+ blo_freefiledata( *fd );
+ *fd = NULL;
}
return curlib;
@@ -8366,11 +9197,11 @@ static Library* library_append(Scene *scene, char* file, char *dir, int idcode,
/* append to scene */
/* this should probably be moved into the Python code anyway */
-void BLO_script_library_append(BlendHandle *bh, char *dir, char *name,
+void BLO_script_library_append(BlendHandle **bh, char *dir, char *name,
int idcode, short flag, Scene *scene )
{
/* try to append the requested object */
- library_append(scene, name, dir, idcode, 0, (FileData *)bh, NULL, 0, flag );
+ library_append(scene, name, dir, idcode, 0, (FileData **)bh, NULL, 0, flag );
/* do we need to do this? */
DAG_scene_sort(scene);
@@ -8387,7 +9218,6 @@ void BLO_library_append(SpaceFile *sfile, char *dir, int idcode, Scene *scene)
void BLO_library_append_(BlendHandle** libfiledata, struct direntry* filelist, int totfile,
char *dir, char* file, short flag, int idcode, Scene *scene)
{
- FileData *fd= (FileData*) (*libfiledata);
Library *curlib;
Base *centerbase;
Object *ob;
@@ -8420,12 +9250,7 @@ void BLO_library_append_(BlendHandle** libfiledata, struct direntry* filelist, i
if(flag & FILE_AUTOSELECT) scene_deselect_all(scene);
- curlib = library_append(scene, file, dir, idcode, totsel, fd, filelist, totfile,flag );
-
- /* patch to prevent switch_endian happens twice */
- if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
- (*libfiledata)= 0;
- }
+ curlib = library_append(scene, file, dir, idcode, totsel, (FileData**) libfiledata, filelist, totfile,flag );
/* when not linking (appending)... */
if((flag & FILE_LINK)==0) {
@@ -8599,13 +9424,13 @@ static void read_libraries(FileData *basefd, ListBase *mainlist)
if(mainptr->curlib->filedata) blo_freefiledata(mainptr->curlib->filedata);
mainptr->curlib->filedata= NULL;
-
}
}
+
/* reading runtime */
-BlendFileData *blo_read_blendafterruntime(int file, int actualsize, BlendReadError *error_r)
+BlendFileData *blo_read_blendafterruntime(int file, char *name, int actualsize, BlendReadError *error_r)
{
BlendFileData *bfd = NULL;
FileData *fd = filedata_new();
@@ -8613,6 +9438,9 @@ BlendFileData *blo_read_blendafterruntime(int file, int actualsize, BlendReadErr
fd->buffersize = actualsize;
fd->read = fd_read_from_file;
+ /* needed for library_append and read_libraries */
+ BLI_strncpy(fd->filename, name, sizeof(fd->filename));
+
fd = blo_decode_and_check(fd, error_r);
if (!fd)
return NULL;
diff --git a/source/blender/blenloader/intern/readfile.h b/source/blender/blenloader/intern/readfile.h
index 51160a179fb..8547a4d9652 100644
--- a/source/blender/blenloader/intern/readfile.h
+++ b/source/blender/blenloader/intern/readfile.h
@@ -34,6 +34,7 @@
struct OldNewMap;
struct MemFile;
+struct bheadsort;
typedef struct FileData {
// linked list of BHeadN's
@@ -73,6 +74,9 @@ typedef struct FileData {
struct OldNewMap *libmap;
struct OldNewMap *imamap;
+ struct bheadsort *bheadmap;
+ int tot_bheadmap;
+
ListBase mainlist;
/* ick ick, used to return
@@ -108,6 +112,7 @@ FileData *blo_openblenderfile( char *name, BlendReadError *error_r);
FileData *blo_openblendermemory( void *buffer, int buffersize, BlendReadError *error_r);
FileData *blo_openblendermemfile(struct MemFile *memfile, BlendReadError *error_r);
+void blo_clear_proxy_pointers_from_lib(FileData *fd);
void blo_make_image_pointer_map(FileData *fd);
void blo_end_image_pointer_map(FileData *fd);
void blo_add_library_pointer_map(ListBase *mainlist, FileData *fd);
diff --git a/source/blender/blenloader/intern/writefile.c b/source/blender/blenloader/intern/writefile.c
index 383a732fbca..a4883087cfa 100644
--- a/source/blender/blenloader/intern/writefile.c
+++ b/source/blender/blenloader/intern/writefile.c
@@ -6,7 +6,7 @@
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
+ * of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -23,7 +23,7 @@
*
* Contributor(s): Blender Foundation
*
- * ***** END GPL/BL DUAL LICENSE BLOCK *****
+ * ***** END GPL LICENSE BLOCK *****
*/
/*
@@ -94,6 +94,7 @@ Any case: direct data is ALWAYS after the lib block
#include "DNA_actuator_types.h"
#include "DNA_brush_types.h"
#include "DNA_camera_types.h"
+#include "DNA_cloth_types.h"
#include "DNA_color_types.h"
#include "DNA_constraint_types.h"
#include "DNA_controller_types.h"
@@ -102,6 +103,7 @@ Any case: direct data is ALWAYS after the lib block
#include "DNA_effect_types.h"
#include "DNA_genfile.h"
#include "DNA_group_types.h"
+#include "DNA_gpencil_types.h"
#include "DNA_image_types.h"
#include "DNA_ipo_types.h"
#include "DNA_fileglobal_types.h"
@@ -143,6 +145,7 @@ Any case: direct data is ALWAYS after the lib block
#include "BKE_action.h"
#include "BKE_blender.h"
+#include "BKE_cloth.h"
#include "BKE_curve.h"
#include "BKE_customdata.h"
#include "BKE_constraint.h"
@@ -162,8 +165,6 @@ Any case: direct data is ALWAYS after the lib block
//XXX #include "BIF_verse.h"
#endif
-#include "GEN_messaging.h"
-
#include "BLO_writefile.h"
#include "BLO_readfile.h"
#include "BLO_undofile.h"
@@ -172,7 +173,10 @@ Any case: direct data is ALWAYS after the lib block
#include <errno.h>
-/* ********* my write, buffered writing with minimum 50k chunks ************ */
+/* ********* my write, buffered writing with minimum size chunks ************ */
+
+#define MYWRITE_BUFFER_SIZE 100000
+#define MYWRITE_MAX_CHUNK 32768
typedef struct {
struct SDNA *sdna;
@@ -198,7 +202,7 @@ static WriteData *writedata_new(int file)
wd->file= file;
- wd->buf= MEM_mallocN(100000, "wd->buf");
+ wd->buf= MEM_mallocN(MYWRITE_BUFFER_SIZE, "wd->buf");
return wd;
}
@@ -238,12 +242,13 @@ int mywfile;
* @warning Talks to other functions with global parameters
*/
-#define MYWRITE_FLUSH NULL
+#define MYWRITE_FLUSH NULL
static void mywrite( WriteData *wd, void *adr, int len)
{
if (wd->error) return;
+ /* flush helps compression for undo-save */
if(adr==MYWRITE_FLUSH) {
if(wd->count) {
writedata_do_write(wd, wd->buf, wd->count);
@@ -254,21 +259,33 @@ static void mywrite( WriteData *wd, void *adr, int len)
wd->tot+= len;
- if(len>50000) {
+ /* if we have a single big chunk, write existing data in
+ * buffer and write out big chunk in smaller pieces */
+ if(len>MYWRITE_MAX_CHUNK) {
if(wd->count) {
writedata_do_write(wd, wd->buf, wd->count);
wd->count= 0;
}
- writedata_do_write(wd, adr, len);
+
+ do {
+ int writelen= MIN2(len, MYWRITE_MAX_CHUNK);
+ writedata_do_write(wd, adr, writelen);
+ adr = (char*)adr + writelen;
+ len -= writelen;
+ } while(len > 0);
+
return;
}
- if(len+wd->count>99999) {
+
+ /* if data would overflow buffer, write out the buffer */
+ if(len+wd->count>MYWRITE_BUFFER_SIZE-1) {
writedata_do_write(wd, wd->buf, wd->count);
wd->count= 0;
}
+
+ /* append data at end of buffer */
memcpy(&wd->buf[wd->count], adr, len);
wd->count+= len;
-
}
/**
@@ -367,7 +384,7 @@ static void writedata(WriteData *wd, int filecode, int len, void *adr) /* do not
void IDP_WriteProperty_OnlyData(IDProperty *prop, void *wd);
void IDP_WriteProperty(IDProperty *prop, void *wd);
-void IDP_WriteArray(IDProperty *prop, void *wd)
+static void IDP_WriteArray(IDProperty *prop, void *wd)
{
/*REMEMBER to set totalen to len in the linking code!!*/
if (prop->data.pointer) {
@@ -375,13 +392,13 @@ void IDP_WriteArray(IDProperty *prop, void *wd)
}
}
-void IDP_WriteString(IDProperty *prop, void *wd)
+static void IDP_WriteString(IDProperty *prop, void *wd)
{
/*REMEMBER to set totalen to len in the linking code!!*/
writedata(wd, DATA, prop->len+1, prop->data.pointer);
}
-void IDP_WriteGroup(IDProperty *prop, void *wd)
+static void IDP_WriteGroup(IDProperty *prop, void *wd)
{
IDProperty *loop;
@@ -434,7 +451,7 @@ static void write_nodetree(WriteData *wd, bNodeTree *ntree)
writestruct(wd, DATA, "bNode", 1, node);
for(node= ntree->nodes.first; node; node= node->next) {
- if(node->storage) {
+ if(node->storage && node->type!=NODE_DYNAMIC) {
/* could be handlerized at some point, now only 1 exception still */
if(ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
write_curvemapping(wd, node->storage);
@@ -492,25 +509,6 @@ static void write_userdef(WriteData *wd)
}
}
-static void write_effects(WriteData *wd, ListBase *lb)
-{
- Effect *eff;
-
- eff= lb->first;
- while(eff) {
-
- switch(eff->type) {
- case EFF_PARTICLE:
- writestruct(wd, DATA, "PartEff", 1, eff);
- break;
- default:
- writedata(wd, DATA, MEM_allocN_len(eff), eff);
- }
-
- eff= eff->next;
- }
-}
-
static void write_particlesettings(WriteData *wd, ListBase *idbase)
{
ParticleSettings *part;
@@ -520,7 +518,9 @@ static void write_particlesettings(WriteData *wd, ListBase *idbase)
if(part->id.us>0 || wd->current) {
/* write LibData */
writestruct(wd, ID_PA, "ParticleSettings", 1, part);
+ if (part->id.properties) IDP_WriteProperty(part->id.properties, wd);
writestruct(wd, DATA, "PartDeflect", 1, part->pd);
+ writestruct(wd, DATA, "PartDeflect", 1, part->pd2);
}
part= part->id.next;
}
@@ -540,11 +540,13 @@ static void write_particlesystems(WriteData *wd, ListBase *particles)
ParticleData *pa = psys->particles;
for(a=0; a<psys->totpart; a++, pa++)
- writedata(wd, DATA, MEM_allocN_len(pa->hair),pa->hair);
+ writestruct(wd, DATA, "HairKey", pa->totkey, pa->hair);
}
}
if(psys->child) writestruct(wd, DATA, "ChildParticle", psys->totchild ,psys->child);
writestruct(wd, DATA, "SoftBody", 1, psys->soft);
+ if(psys->soft) writestruct(wd, DATA, "PointCache", 1, psys->soft->pointcache);
+ writestruct(wd, DATA, "PointCache", 1, psys->pointcache);
}
}
@@ -589,6 +591,12 @@ static void write_sensors(WriteData *wd, ListBase *lb)
case SENS_PROPERTY:
writestruct(wd, DATA, "bPropertySensor", 1, sens->data);
break;
+ case SENS_ACTUATOR:
+ writestruct(wd, DATA, "bActuatorSensor", 1, sens->data);
+ break;
+ case SENS_DELAY:
+ writestruct(wd, DATA, "bDelaySensor", 1, sens->data);
+ break;
case SENS_COLLISION:
writestruct(wd, DATA, "bCollisionSensor", 1, sens->data);
break;
@@ -650,6 +658,7 @@ static void write_actuators(WriteData *wd, ListBase *lb)
switch(act->type) {
case ACT_ACTION:
+ case ACT_SHAPEACTION:
writestruct(wd, DATA, "bActionActuator", 1, act->data);
break;
case ACT_SOUND:
@@ -694,6 +703,15 @@ static void write_actuators(WriteData *wd, ListBase *lb)
case ACT_VISIBILITY:
writestruct(wd, DATA, "bVisibilityActuator", 1, act->data);
break;
+ case ACT_2DFILTER:
+ writestruct(wd, DATA, "bTwoDFilterActuator", 1, act->data);
+ break;
+ case ACT_PARENT:
+ writestruct(wd, DATA, "bParentActuator", 1, act->data);
+ break;
+ case ACT_STATE:
+ writestruct(wd, DATA, "bStateActuator", 1, act->data);
+ break;
default:
; /* error: don't know how to write this file */
}
@@ -754,6 +772,7 @@ static void write_constraints(WriteData *wd, ListBase *conlist)
static void write_pose(WriteData *wd, bPose *pose)
{
bPoseChannel *chan;
+ bActionGroup *grp;
/* Write each channel */
if (!pose)
@@ -769,6 +788,10 @@ static void write_pose(WriteData *wd, bPose *pose)
writestruct(wd, DATA, "bPoseChannel", 1, chan);
}
+
+ /* Write groups */
+ for (grp=pose->agroups.first; grp; grp=grp->next)
+ writestruct(wd, DATA, "bActionGroup", 1, grp);
/* Write this pose */
writestruct(wd, DATA, "bPose", 1, pose);
@@ -807,6 +830,29 @@ static void write_modifiers(WriteData *wd, ListBase *modbase)
writedata(wd, DATA, sizeof(int)*hmd->totindex, hmd->indexar);
}
+ else if(md->type==eModifierType_Cloth) {
+ ClothModifierData *clmd = (ClothModifierData*) md;
+
+ writestruct(wd, DATA, "ClothSimSettings", 1, clmd->sim_parms);
+ writestruct(wd, DATA, "ClothCollSettings", 1, clmd->coll_parms);
+ writestruct(wd, DATA, "PointCache", 1, clmd->point_cache);
+ }
+ else if(md->type==eModifierType_Fluidsim) {
+ FluidsimModifierData *fluidmd = (FluidsimModifierData*) md;
+
+ writestruct(wd, DATA, "FluidsimSettings", 1, fluidmd->fss);
+ }
+ else if (md->type==eModifierType_Collision) {
+
+ /*
+ CollisionModifierData *collmd = (CollisionModifierData*) md;
+ // TODO: CollisionModifier should use pointcache
+ // + have proper reset events before enabling this
+ writestruct(wd, DATA, "MVert", collmd->numverts, collmd->x);
+ writestruct(wd, DATA, "MVert", collmd->numverts, collmd->xnew);
+ writestruct(wd, DATA, "MFace", collmd->numfaces, collmd->mfaces);
+ */
+ }
else if (md->type==eModifierType_MeshDeform) {
MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
int size = mmd->dyngridsize;
@@ -846,7 +892,7 @@ static void write_objects(WriteData *wd, ListBase *idbase)
/* direct data */
writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
- write_effects(wd, &ob->effect);
+ /* write_effects(wd, &ob->effect); */ /* not used anymore */
write_properties(wd, &ob->prop);
write_sensors(wd, &ob->sensors);
write_controllers(wd, &ob->controllers);
@@ -860,7 +906,8 @@ static void write_objects(WriteData *wd, ListBase *idbase)
writestruct(wd, DATA, "PartDeflect", 1, ob->pd);
writestruct(wd, DATA, "SoftBody", 1, ob->soft);
- writestruct(wd, DATA, "FluidsimSettings", 1, ob->fluidsimSettings); // NT
+ if(ob->soft) writestruct(wd, DATA, "PointCache", 1, ob->soft->pointcache);
+ writestruct(wd, DATA, "BulletSoftBody", 1, ob->bsoft);
write_particlesystems(wd, &ob->particlesystem);
write_modifiers(wd, &ob->modifiers);
@@ -1004,7 +1051,7 @@ static void write_mballs(WriteData *wd, ListBase *idbase)
}
}
-int amount_of_chars(char *str)
+static int amount_of_chars(char *str)
{
// Since the data is saved as UTF-8 to the cu->str
// The cu->len is not same as the strlen(cu->str)
@@ -1385,6 +1432,7 @@ static void write_scenes(WriteData *wd, ListBase *scebase)
MetaStack *ms;
Strip *strip;
TimeMarker *marker;
+ TransformOrientation *ts;
SceneRenderLayer *srl;
int a;
@@ -1448,9 +1496,20 @@ static void write_scenes(WriteData *wd, ListBase *scebase)
strip= seq->strip;
writestruct(wd, DATA, "Strip", 1, strip);
-
+ if(seq->flag & SEQ_USE_CROP && strip->crop) {
+ writestruct(wd, DATA, "StripCrop", 1, strip->crop);
+ }
+ if(seq->flag & SEQ_USE_TRANSFORM && strip->transform) {
+ writestruct(wd, DATA, "StripTransform", 1, strip->transform);
+ }
+ if(seq->flag & SEQ_USE_PROXY && strip->proxy) {
+ writestruct(wd, DATA, "StripProxy", 1, strip->proxy);
+ }
+ if(seq->flag & SEQ_USE_COLOR_BALANCE && strip->color_balance) {
+ writestruct(wd, DATA, "StripColorBalance", 1, strip->color_balance);
+ }
if(seq->type==SEQ_IMAGE)
- writestruct(wd, DATA, "StripElem", strip->len, strip->stripdata);
+ writestruct(wd, DATA, "StripElem", MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem), strip->stripdata);
else if(seq->type==SEQ_MOVIE || seq->type==SEQ_RAM_SOUND || seq->type == SEQ_HD_SOUND)
writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
@@ -1477,11 +1536,18 @@ static void write_scenes(WriteData *wd, ListBase *scebase)
writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
}
+ if (sce->r.ffcodecdata.properties) {
+ IDP_WriteProperty(sce->r.ffcodecdata.properties, wd);
+ }
/* writing dynamic list of TimeMarkers to the blend file */
for(marker= sce->markers.first; marker; marker= marker->next)
writestruct(wd, DATA, "TimeMarker", 1, marker);
+ /* writing dynamic list of TransformOrientations to the blend file */
+ for(ts = sce->transform_spaces.first; ts; ts = ts->next)
+ writestruct(wd, DATA, "TransformOrientation", 1, ts);
+
for(srl= sce->r.layers.first; srl; srl= srl->next)
writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
@@ -1496,6 +1562,32 @@ static void write_scenes(WriteData *wd, ListBase *scebase)
mywrite(wd, MYWRITE_FLUSH, 0);
}
+static void write_gpencil(WriteData *wd, bGPdata *gpd)
+{
+ bGPDlayer *gpl;
+ bGPDframe *gpf;
+ bGPDstroke *gps;
+
+ /* write gpd data block to file */
+ writestruct(wd, DATA, "bGPdata", 1, gpd);
+
+ /* write grease-pencil layers to file */
+ for (gpl= gpd->layers.first; gpl; gpl= gpl->next) {
+ writestruct(wd, DATA, "bGPDlayer", 1, gpl);
+
+ /* write this layer's frames to file */
+ for (gpf= gpl->frames.first; gpf; gpf= gpf->next) {
+ writestruct(wd, DATA, "bGPDframe", 1, gpf);
+
+ /* write strokes */
+ for (gps= gpf->strokes.first; gps; gps= gps->next) {
+ writestruct(wd, DATA, "bGPDstroke", 1, gps);
+ writestruct(wd, DATA, "bGPDspoint", gps->totpoints, gps->points);
+ }
+ }
+ }
+}
+
static void write_windowmanagers(WriteData *wd, ListBase *lb)
{
wmWindowManager *wm;
@@ -1550,11 +1642,12 @@ static void write_screens(WriteData *wd, ListBase *scrbase)
sl= sa->spacedata.first;
while(sl) {
if(sl->spacetype==SPACE_VIEW3D) {
- View3D *v3d= (View3D*) sl;
+ View3D *v3d= (View3D *) sl;
writestruct(wd, DATA, "View3D", 1, v3d);
if(v3d->bgpic) writestruct(wd, DATA, "BGpic", 1, v3d->bgpic);
if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
if(v3d->clipbb) writestruct(wd, DATA, "BoundBox", 1, v3d->clipbb);
+ if(v3d->gpd) write_gpencil(wd, v3d->gpd);
}
else if(sl->spacetype==SPACE_IPO) {
writestruct(wd, DATA, "SpaceIpo", 1, sl);
@@ -1566,7 +1659,9 @@ static void write_screens(WriteData *wd, ListBase *scrbase)
writestruct(wd, DATA, "SpaceFile", 1, sl);
}
else if(sl->spacetype==SPACE_SEQ) {
+ SpaceSeq *sseq= (SpaceSeq *)sl;
writestruct(wd, DATA, "SpaceSeq", 1, sl);
+ if(sseq->gpd) write_gpencil(wd, sseq->gpd);
}
else if(sl->spacetype==SPACE_OOPS) {
SpaceOops *so= (SpaceOops *)sl;
@@ -1603,7 +1698,9 @@ static void write_screens(WriteData *wd, ListBase *scrbase)
writestruct(wd, DATA, "SpaceImage", 1, sl);
if(sima->cumap)
- write_curvemapping(wd, sima->cumap);
+ write_curvemapping(wd, sima->cumap);
+ if(sima->gpd)
+ write_gpencil(wd, sima->gpd);
}
else if(sl->spacetype==SPACE_IMASEL) {
writestruct(wd, DATA, "SpaceImaSel", 1, sl);
@@ -1629,7 +1726,9 @@ static void write_screens(WriteData *wd, ListBase *scrbase)
writestruct(wd, DATA, "SpaceTime", 1, sl);
}
else if(sl->spacetype==SPACE_NODE){
+ SpaceNode *snode= (SpaceNode *)sl;
writestruct(wd, DATA, "SpaceNode", 1, sl);
+ if(snode->gpd) write_gpencil(wd, snode->gpd);
}
sl= sl->next;
}
@@ -1722,16 +1821,26 @@ static void write_actions(WriteData *wd, ListBase *idbase)
{
bAction *act;
bActionChannel *chan;
+ bActionGroup *grp;
+ TimeMarker *marker;
for(act=idbase->first; act; act= act->id.next) {
if (act->id.us>0 || wd->current) {
writestruct(wd, ID_AC, "bAction", 1, act);
if (act->id.properties) IDP_WriteProperty(act->id.properties, wd);
-
+
for (chan=act->chanbase.first; chan; chan=chan->next) {
writestruct(wd, DATA, "bActionChannel", 1, chan);
write_constraint_channels(wd, &chan->constraintChannels);
}
+
+ for (grp=act->groups.first; grp; grp=grp->next) {
+ writestruct(wd, DATA, "bActionGroup", 1, grp);
+ }
+
+ for (marker=act->markers.first; marker; marker=marker->next) {
+ writestruct(wd, DATA, "TimeMarker", 1, marker);
+ }
}
}
}
@@ -1740,6 +1849,7 @@ static void write_texts(WriteData *wd, ListBase *idbase)
{
Text *text;
TextLine *tmp;
+ TextMarker *mrk;
text= idbase->first;
while(text) {
@@ -1763,7 +1873,16 @@ static void write_texts(WriteData *wd, ListBase *idbase)
writedata(wd, DATA, tmp->len+1, tmp->line);
tmp= tmp->next;
}
+
+ /* write markers */
+ mrk= text->markers.first;
+ while (mrk) {
+ writestruct(wd, DATA, "TextMarker", 1, mrk);
+ mrk= mrk->next;
+ }
}
+
+
text= text->id.next;
}
@@ -1870,9 +1989,21 @@ static void write_brushes(WriteData *wd, ListBase *idbase)
}
}
+static void write_scripts(WriteData *wd, ListBase *idbase)
+{
+ Script *script;
+
+ for(script=idbase->first; script; script= script->id.next) {
+ if(script->id.us>0 || wd->current) {
+ writestruct(wd, ID_SCRIPT, "Script", 1, script);
+ if (script->id.properties) IDP_WriteProperty(script->id.properties, wd);
+ }
+ }
+}
+
/* context is usually defined by WM, two cases where no WM is available:
-/* - for forward compatibility, curscreen has to be saved */
-/* - for undofile, curscene needs to be saved */
+ * - for forward compatibility, curscreen has to be saved
+ * - for undofile, curscene needs to be saved */
/* XXX still remap G */
static void write_global(bContext *C, WriteData *wd)
{
@@ -1943,6 +2074,7 @@ static int write_file_handle(bContext *C, int handle, MemFile *compare, MemFile
write_particlesettings(wd, &G.main->particle);
write_nodetrees(wd, &G.main->nodetree);
write_brushes (wd, &G.main->brush);
+ write_scripts (wd, &G.main->script);
if(current==NULL)
write_libraries(wd, G.main->next); /* no library save in undo */
@@ -2003,7 +2135,7 @@ int BLO_write_file(bContext *C, char *dir, int write_flags, char **error_r)
}
}
else
- if(BLI_rename(tempname, dir) < 0) {
+ if(BLI_rename(tempname, dir) != 0) {
*error_r= "Can't change old file. File saved with @";
return 0;
}
@@ -2039,7 +2171,7 @@ int BLO_write_file_mem(bContext *C, MemFile *compare, MemFile *current, int writ
#define PATHSEPERATOR "/"
#endif
-static char *get_install_dir(void) {
+char *get_install_dir(void) {
extern char bprogname[];
char *tmpname = BLI_strdup(bprogname);
char *cut;
@@ -2167,7 +2299,7 @@ static int handle_append_runtime(int handle, char *exename, char **cause_r)
unsigned char buf[1024];
int count, progfd= -1;
- if (!runtime) {
+ if (!BLI_exists(runtime)) {
cause= "Unable to find runtime";
goto cleanup;
}
diff --git a/source/blender/blenpluginapi/SConscript b/source/blender/blenpluginapi/SConscript
index aa6e25532b8..4cf52a50e8c 100644
--- a/source/blender/blenpluginapi/SConscript
+++ b/source/blender/blenpluginapi/SConscript
@@ -7,8 +7,8 @@ incs = '. .. #/intern/guardedalloc ../blenlib ../imbuf ../makesdna'
defs = []
-if env['WITH_BF_QUICKTIME'] == 1:
+if env['WITH_BF_QUICKTIME']:
defs.append('WITH_QUICKTIME')
incs += ' ' + env['BF_QUICKTIME_INC']
-env.BlenderLib ( libname = 'bf_blenpluginapi', sources = sources, includes = Split(incs), defines = defs, libtype=['core', 'player'], priority = [90, 30] )
+env.BlenderLib ( libname = 'bf_blenpluginapi', sources = sources, includes = Split(incs), defines = defs, libtype=['core', 'player'], priority = [75, 35] )
diff --git a/source/blender/blenpluginapi/externdef.h b/source/blender/blenpluginapi/externdef.h
index 7322841e608..14a3115ce33 100644
--- a/source/blender/blenpluginapi/externdef.h
+++ b/source/blender/blenpluginapi/externdef.h
@@ -33,11 +33,14 @@
#ifdef WIN32
#ifdef PLUGIN_INTERN
#define LIBEXPORT __declspec(dllexport)
+ #define LIBIMPORT __declspec(dllexport)
#else
- #define LIBEXPORT extern __declspec(dllimport)
+ #define LIBEXPORT __declspec(dllexport)
+ #define LIBIMPORT extern __declspec(dllimport)
#endif
#elif !defined(WIN32)
#define LIBEXPORT extern
+ #define LIBIMPORT extern
#endif
#endif /* _EXTERNDEF_H */
diff --git a/source/blender/blenpluginapi/iff.h b/source/blender/blenpluginapi/iff.h
index 5eb52158a1a..92cbd7dd093 100644
--- a/source/blender/blenpluginapi/iff.h
+++ b/source/blender/blenpluginapi/iff.h
@@ -151,7 +151,7 @@ typedef struct ImBuf {
int userflags; /**< Used to set imbuf to Dirty and other stuff */
int *zbuf; /**< z buffer data, original zbuffer */
float *zbuf_float; /**< z buffer data, camera coordinates */
- void *userdata;
+ void *userdata; /**< temporary storage, only used by baking at the moment */
unsigned char *encodedbuffer; /**< Compressed image only used with png currently */
unsigned int encodedsize; /**< Size of data written to encodedbuffer */
unsigned int encodedbuffersize; /**< Size of encodedbuffer */
@@ -161,55 +161,56 @@ typedef struct ImBuf {
float dither; /**< random dither value, for conversion from float -> byte rect */
struct MEM_CacheLimiterHandle_s * c_handle; /**< handle for cache limiter */
+ struct ImgInfo * img_info;
int refcounter; /**< Refcounter for multiple users */
int index; /**< reference index for ImBuf lists */
struct ImBuf *mipmap[IB_MIPMAP_LEVELS]; /**< MipMap levels, a series of halved images */
} ImBuf;
-LIBEXPORT struct ImBuf *allocImBuf(short,short,uchar,uint,uchar);
-LIBEXPORT struct ImBuf *dupImBuf(struct ImBuf *);
-LIBEXPORT void freeImBuf(struct ImBuf*);
+LIBIMPORT struct ImBuf *allocImBuf(short,short,uchar,uint,uchar);
+LIBIMPORT struct ImBuf *dupImBuf(struct ImBuf *);
+LIBIMPORT void freeImBuf(struct ImBuf*);
-LIBEXPORT short converttocmap(struct ImBuf* ibuf);
+LIBIMPORT short converttocmap(struct ImBuf* ibuf);
-LIBEXPORT short saveiff(struct ImBuf *,char *,int);
+LIBIMPORT short saveiff(struct ImBuf *,char *,int);
-LIBEXPORT struct ImBuf *loadiffmem(int *,int);
-LIBEXPORT struct ImBuf *loadifffile(int,int);
-LIBEXPORT struct ImBuf *loadiffname(char *,int);
-LIBEXPORT struct ImBuf *testiffname(char *,int);
+LIBIMPORT struct ImBuf *loadiffmem(int *,int);
+LIBIMPORT struct ImBuf *loadifffile(int,int);
+LIBIMPORT struct ImBuf *loadiffname(char *,int);
+LIBIMPORT struct ImBuf *testiffname(char *,int);
-LIBEXPORT struct ImBuf *onehalf(struct ImBuf *);
-LIBEXPORT struct ImBuf *onethird(struct ImBuf *);
-LIBEXPORT struct ImBuf *halflace(struct ImBuf *);
-LIBEXPORT struct ImBuf *half_x(struct ImBuf *);
-LIBEXPORT struct ImBuf *half_y(struct ImBuf *);
-LIBEXPORT struct ImBuf *double_x(struct ImBuf *);
-LIBEXPORT struct ImBuf *double_y(struct ImBuf *);
-LIBEXPORT struct ImBuf *double_fast_x(struct ImBuf *);
-LIBEXPORT struct ImBuf *double_fast_y(struct ImBuf *);
+LIBIMPORT struct ImBuf *onehalf(struct ImBuf *);
+LIBIMPORT struct ImBuf *onethird(struct ImBuf *);
+LIBIMPORT struct ImBuf *halflace(struct ImBuf *);
+LIBIMPORT struct ImBuf *half_x(struct ImBuf *);
+LIBIMPORT struct ImBuf *half_y(struct ImBuf *);
+LIBIMPORT struct ImBuf *double_x(struct ImBuf *);
+LIBIMPORT struct ImBuf *double_y(struct ImBuf *);
+LIBIMPORT struct ImBuf *double_fast_x(struct ImBuf *);
+LIBIMPORT struct ImBuf *double_fast_y(struct ImBuf *);
-LIBEXPORT int ispic(char *);
+LIBIMPORT int ispic(char *);
-LIBEXPORT void dit2(struct ImBuf *, short, short);
-LIBEXPORT void dit0(struct ImBuf *, short, short);
+LIBIMPORT void dit2(struct ImBuf *, short, short);
+LIBIMPORT void dit0(struct ImBuf *, short, short);
-LIBEXPORT struct ImBuf *scaleImBuf(struct ImBuf *, short, short);
-LIBEXPORT struct ImBuf *scalefastImBuf(struct ImBuf *, short, short);
-LIBEXPORT struct ImBuf *scalefieldImBuf(struct ImBuf *, short, short);
-LIBEXPORT struct ImBuf *scalefastfieldImBuf(struct ImBuf *, short, short);
+LIBIMPORT struct ImBuf *scaleImBuf(struct ImBuf *, short, short);
+LIBIMPORT struct ImBuf *scalefastImBuf(struct ImBuf *, short, short);
+LIBIMPORT struct ImBuf *scalefieldImBuf(struct ImBuf *, short, short);
+LIBIMPORT struct ImBuf *scalefastfieldImBuf(struct ImBuf *, short, short);
-LIBEXPORT void de_interlace(struct ImBuf *ib);
-LIBEXPORT void interlace(struct ImBuf *ib);
-LIBEXPORT void gamwarp(struct ImBuf *ibuf, double gamma);
+LIBIMPORT void de_interlace(struct ImBuf *ib);
+LIBIMPORT void interlace(struct ImBuf *ib);
+LIBIMPORT void gamwarp(struct ImBuf *ibuf, double gamma);
-LIBEXPORT void IMB_rectcpy(struct ImBuf *dbuf, struct ImBuf *sbuf,
+LIBIMPORT void IMB_rectcpy(struct ImBuf *dbuf, struct ImBuf *sbuf,
int destx, int desty, int srcx, int srcy, int width, int height);
-LIBEXPORT void IMB_rectfill(struct ImBuf *drect, float col[4]);
-LIBEXPORT void IMB_rectfill_area(struct ImBuf *ibuf, float *col, int x1, int y1, int x2, int y2);
-LIBEXPORT void buf_rectfill_area(unsigned char *rect, float *rectf, int width, int height, float *col, int x1, int y1, int x2, int y2);
+LIBIMPORT void IMB_rectfill(struct ImBuf *drect, float col[4]);
+LIBIMPORT void IMB_rectfill_area(struct ImBuf *ibuf, float *col, int x1, int y1, int x2, int y2);
+LIBIMPORT void buf_rectfill_area(unsigned char *rect, float *rectf, int width, int height, float *col, int x1, int y1, int x2, int y2);
#endif /* IFF_H */
diff --git a/source/blender/blenpluginapi/intern/pluginapi.c b/source/blender/blenpluginapi/intern/pluginapi.c
index ee1ac8f0ae2..9c08a0b2f9d 100644
--- a/source/blender/blenpluginapi/intern/pluginapi.c
+++ b/source/blender/blenpluginapi/intern/pluginapi.c
@@ -50,9 +50,12 @@
#include "plugin.h"
#include "MEM_guardedalloc.h"
+#include "BLO_sys_types.h" // needed for intptr_t
+
#include "BLI_blenlib.h" /* util and noise functions */
#include "BLI_threads.h" /* For threadsfe guardedalloc malloc/calloc/free */
#include "IMB_imbuf.h" /* image buffer stuff */
+#define GET_INT_FROM_POINTER(i) ((int)(intptr_t)(i)) /* should use BKE_utildefines.h */
/* -------------------------------------------------------------------------- */
/* stuff from util.h */
@@ -321,42 +324,43 @@ int pluginapi_force_ref(void);
int pluginapi_force_ref(void)
{
- return (int) mallocN +
- (int) callocN +
- (int) freeN +
- (int) mallocT +
- (int) callocT +
- (int) freeT +
- (int) allocImBuf +
- (int) dupImBuf +
- (int) freeImBuf +
- (int) converttocmap +
- (int) saveiff +
- (int) loadiffmem +
- (int) loadifffile +
- (int) loadiffname +
- (int) testiffname +
- (int) onehalf +
- (int) onethird +
- (int) halflace +
- (int) half_x +
- (int) half_y +
- (int) double_x +
- (int) double_y +
- (int) double_fast_x +
- (int) double_fast_y +
- (int) ispic +
- (int) dit2 +
- (int) dit0 +
- (int) scaleImBuf +
- (int) scalefastImBuf +
- (int) scalefieldImBuf +
- (int) scalefastfieldImBuf +
- (int) hnoise +
- (int) hnoisep +
- (int) turbulence +
- (int) turbulence1 +
- (int) de_interlace +
- (int) interlace +
- (int) gamwarp;
+ return
+ GET_INT_FROM_POINTER( mallocN ) +
+ GET_INT_FROM_POINTER( callocN ) +
+ GET_INT_FROM_POINTER( freeN ) +
+ GET_INT_FROM_POINTER( mallocT ) +
+ GET_INT_FROM_POINTER( callocT ) +
+ GET_INT_FROM_POINTER( freeT ) +
+ GET_INT_FROM_POINTER( allocImBuf ) +
+ GET_INT_FROM_POINTER( dupImBuf ) +
+ GET_INT_FROM_POINTER( freeImBuf ) +
+ GET_INT_FROM_POINTER( converttocmap ) +
+ GET_INT_FROM_POINTER( saveiff ) +
+ GET_INT_FROM_POINTER( loadiffmem ) +
+ GET_INT_FROM_POINTER( loadifffile ) +
+ GET_INT_FROM_POINTER( loadiffname ) +
+ GET_INT_FROM_POINTER( testiffname ) +
+ GET_INT_FROM_POINTER( onehalf ) +
+ GET_INT_FROM_POINTER( onethird ) +
+ GET_INT_FROM_POINTER( halflace ) +
+ GET_INT_FROM_POINTER( half_x ) +
+ GET_INT_FROM_POINTER( half_y ) +
+ GET_INT_FROM_POINTER( double_x ) +
+ GET_INT_FROM_POINTER( double_y ) +
+ GET_INT_FROM_POINTER( double_fast_x ) +
+ GET_INT_FROM_POINTER( double_fast_y ) +
+ GET_INT_FROM_POINTER( ispic ) +
+ GET_INT_FROM_POINTER( dit2 ) +
+ GET_INT_FROM_POINTER( dit0 ) +
+ GET_INT_FROM_POINTER( scaleImBuf ) +
+ GET_INT_FROM_POINTER( scalefastImBuf ) +
+ GET_INT_FROM_POINTER( scalefieldImBuf ) +
+ GET_INT_FROM_POINTER( scalefastfieldImBuf ) +
+ GET_INT_FROM_POINTER( hnoise ) +
+ GET_INT_FROM_POINTER( hnoisep ) +
+ GET_INT_FROM_POINTER( turbulence ) +
+ GET_INT_FROM_POINTER( turbulence1 ) +
+ GET_INT_FROM_POINTER( de_interlace ) +
+ GET_INT_FROM_POINTER( interlace ) +
+ GET_INT_FROM_POINTER( gamwarp );
}
diff --git a/source/blender/blenpluginapi/plugin.h b/source/blender/blenpluginapi/plugin.h
index 1f6140130eb..da044cf7317 100644
--- a/source/blender/blenpluginapi/plugin.h
+++ b/source/blender/blenpluginapi/plugin.h
@@ -36,9 +36,10 @@
#include "util.h"
#include "floatpatch.h"
-#define B_PLUGIN_VERSION 5
+#define B_PLUGIN_VERSION 6
-typedef int (*TexDoit)(int, void*, float*, float*, float*);
+typedef int (*TexDoit)(int, void*, float*, float*, float*, float*);
+typedef int (*TexDoitold)(int, void*, float*, float*, float*);
typedef void (*SeqDoit)(void*, float, float, int, int, ImBuf*, ImBuf*, ImBuf*, ImBuf*);
typedef struct VarStruct {
@@ -66,9 +67,9 @@ typedef struct _PluginInfo {
void (*instance_init)(void *);
} PluginInfo;
-int plugin_tex_getversion(void);
-int plugin_seq_getversion(void);
-void plugin_getinfo(PluginInfo *);
+LIBEXPORT int plugin_tex_getversion(void);
+LIBEXPORT int plugin_seq_getversion(void);
+LIBEXPORT void plugin_getinfo(PluginInfo *);
/* *************** defines for button types ************** */
@@ -90,14 +91,14 @@ void plugin_getinfo(PluginInfo *);
/* *************** API functions ******************** */
/* derived from the famous Perlin noise */
-LIBEXPORT float hnoise(float noisesize, float x, float y, float z);
+LIBIMPORT float hnoise(float noisesize, float x, float y, float z);
/* the original Perlin noise */
-LIBEXPORT float hnoisep(float noisesize, float x, float y, float z);
+LIBIMPORT float hnoisep(float noisesize, float x, float y, float z);
/* soft turbulence */
-LIBEXPORT float turbulence(float noisesize, float x, float y, float z, int depth);
+LIBIMPORT float turbulence(float noisesize, float x, float y, float z, int depth);
/* hard turbulence */
-LIBEXPORT float turbulence1(float noisesize, float x, float y, float z, int depth);
+LIBIMPORT float turbulence1(float noisesize, float x, float y, float z, int depth);
#endif /* PLUGIN_H */
diff --git a/source/blender/editors/datafiles/SConscript b/source/blender/editors/datafiles/SConscript
index 88ac37b84c9..e69c8567ca0 100644
--- a/source/blender/editors/datafiles/SConscript
+++ b/source/blender/editors/datafiles/SConscript
@@ -6,4 +6,4 @@ sources = env.Glob('*.c')
incs = '../include ../../blenlib ../../blenkernel ../../makesdna ../../imbuf'
incs += ' #/intern/guardedalloc'
-env.BlenderLib ( 'bf_editor_datafiles', sources, Split(incs), [], libtype=['core','intern'], priority=[5, 25] )
+env.BlenderLib ( 'bf_editor_datafiles', sources, Split(incs), [], libtype=['core','intern'], priority=[50, 55] )
diff --git a/source/blender/editors/include/BIF_gl.h b/source/blender/editors/include/BIF_gl.h
index 244fd3bb78b..014201648c9 100644
--- a/source/blender/editors/include/BIF_gl.h
+++ b/source/blender/editors/include/BIF_gl.h
@@ -49,19 +49,13 @@
#endif
#endif
-#ifdef __APPLE__
-#include <OpenGL/gl.h>
-#include <OpenGL/glu.h>
-#else
-#include <GL/gl.h>
-#include <GL/glu.h>
-#endif
+#include "GL/glew.h"
+
/*
* these should be phased out. cpack should be replaced in
* code with calls to glColor3ub, lrectwrite probably should
* change to a function. - zr
*/
-
/*
*
* This define converts a numerical value to the equivalent 24-bit
@@ -75,5 +69,9 @@
#define lrectwrite(a, b, c, d, rect) {glRasterPos2i(a, b);glDrawPixels((c)-(a)+1, (d)-(b)+1, GL_RGBA, GL_UNSIGNED_BYTE, rect);}
+/* glStippleDefines, defined in glutil.c */
+extern GLubyte stipple_halftone[128];
+extern GLubyte stipple_quarttone[128];
+
#endif /* #ifdef BIF_GL_H */
diff --git a/source/blender/editors/include/BIF_interface_icons.h b/source/blender/editors/include/BIF_interface_icons.h
deleted file mode 100644
index e69de29bb2d..00000000000
--- a/source/blender/editors/include/BIF_interface_icons.h
+++ /dev/null
diff --git a/source/blender/editors/include/BIF_resources.h b/source/blender/editors/include/BIF_resources.h
deleted file mode 100644
index e69de29bb2d..00000000000
--- a/source/blender/editors/include/BIF_resources.h
+++ /dev/null
diff --git a/source/blender/editors/include/BIF_view2d.h b/source/blender/editors/include/BIF_view2d.h
deleted file mode 100644
index e69de29bb2d..00000000000
--- a/source/blender/editors/include/BIF_view2d.h
+++ /dev/null
diff --git a/source/blender/editors/interface/Makefile b/source/blender/editors/interface/Makefile
index 39bb651a616..fe223fabf2a 100644
--- a/source/blender/editors/interface/Makefile
+++ b/source/blender/editors/interface/Makefile
@@ -35,6 +35,7 @@ include nan_compile.mk
CFLAGS += $(LEVEL_1_C_WARNINGS)
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
CPPFLAGS += -I$(NAN_BMFONT)/include
@@ -52,3 +53,8 @@ CPPFLAGS += -I../../ftfont
# own include
CPPFLAGS += -I../include
+
+ifeq ($(INTERNATIONAL), true)
+ CPPFLAGS += -DINTERNATIONAL
+endif
+
diff --git a/source/blender/editors/interface/SConscript b/source/blender/editors/interface/SConscript
index 0586d07d945..42e4db60edb 100644
--- a/source/blender/editors/interface/SConscript
+++ b/source/blender/editors/interface/SConscript
@@ -5,5 +5,13 @@ sources = env.Glob('*.c')
incs = '../include ../../blenlib ../../blenkernel ../../makesdna ../../imbuf'
incs += ' ../../makesrna ../../windowmanager #/intern/guardedalloc #intern/bmfont'
+incs += ' #/extern/glew/include'
-env.BlenderLib ( 'bf_editors_interface', sources, Split(incs), [], libtype=['core','intern'], priority=[40, 45] )
+defs = []
+
+if env['WITH_BF_INTERNATIONAL']:
+ incs += ' ../../ftfont'
+ defs.append('INTERNATIONAL')
+ defs.append('FTGL_STATIC_LIBRARY')
+
+env.BlenderLib ( 'bf_editors_interface', sources, Split(incs), Split(defs), libtype=['core','intern'], priority=[40, 45] )
diff --git a/source/blender/editors/screen/Makefile b/source/blender/editors/screen/Makefile
index 11cd8f264ad..b905d7c197b 100644
--- a/source/blender/editors/screen/Makefile
+++ b/source/blender/editors/screen/Makefile
@@ -35,6 +35,7 @@ include nan_compile.mk
CFLAGS += $(LEVEL_1_C_WARNINGS)
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
# not very neat....
diff --git a/source/blender/editors/screen/SConscript b/source/blender/editors/screen/SConscript
index 8ca512fedc1..04a1d7f4388 100644
--- a/source/blender/editors/screen/SConscript
+++ b/source/blender/editors/screen/SConscript
@@ -5,6 +5,6 @@ sources = env.Glob('*.c')
incs = '../include ../../blenlib ../../blenkernel ../../makesdna ../../imbuf'
incs += ' ../../blenloader ../../windowmanager ../../python'
-incs += ' #/intern/guardedalloc'
+incs += ' #/intern/guardedalloc #/extern/glew/include'
env.BlenderLib ( 'bf_editors_screen', sources, Split(incs), [], libtype=['core','intern'], priority=[30, 35] )
diff --git a/source/blender/editors/screen/glutil.c b/source/blender/editors/screen/glutil.c
index 5b776fd7f49..08587ddb9a5 100644
--- a/source/blender/editors/screen/glutil.c
+++ b/source/blender/editors/screen/glutil.c
@@ -422,7 +422,6 @@ void glaDrawPixelsTex(float x, float y, int img_w, int img_h, int format, void *
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
}
-#define FTOCHAR(val) val<=0.0f?0: (val>=1.0f?255: (char)(255.0f*val))
void glaDrawPixelsSafe_to32(float fx, float fy, int img_w, int img_h, int row_w, float *rectf)
{
float *rf;
diff --git a/source/blender/editors/space_time/Makefile b/source/blender/editors/space_time/Makefile
index 72dca174dba..c64a81695bf 100644
--- a/source/blender/editors/space_time/Makefile
+++ b/source/blender/editors/space_time/Makefile
@@ -35,6 +35,7 @@ include nan_compile.mk
CFLAGS += $(LEVEL_1_C_WARNINGS)
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
# not very neat....
diff --git a/source/blender/editors/space_time/SConscript b/source/blender/editors/space_time/SConscript
index 091218e0794..b83e79ff3e6 100644
--- a/source/blender/editors/space_time/SConscript
+++ b/source/blender/editors/space_time/SConscript
@@ -4,6 +4,6 @@ Import ('env')
sources = env.Glob('*.c')
incs = '../include ../../blenlib ../../blenkernel ../../makesdna ../../imbuf'
-incs += '../../windowmanager #/intern/guardedalloc'
+incs += '../../windowmanager #/intern/guardedalloc #/extern/glew/include'
env.BlenderLib ( 'bf_editors_space_time', sources, Split(incs), [], libtype=['core','intern'], priority=[35, 40] )
diff --git a/source/blender/editors/space_view3d/Makefile b/source/blender/editors/space_view3d/Makefile
index 0631cf010b8..45b6ca648d2 100644
--- a/source/blender/editors/space_view3d/Makefile
+++ b/source/blender/editors/space_view3d/Makefile
@@ -35,6 +35,7 @@ include nan_compile.mk
CFLAGS += $(LEVEL_1_C_WARNINGS)
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
# not very neat....
diff --git a/source/blender/editors/space_view3d/SConscript b/source/blender/editors/space_view3d/SConscript
index 6e6c9fdc29d..99b620544cd 100644
--- a/source/blender/editors/space_view3d/SConscript
+++ b/source/blender/editors/space_view3d/SConscript
@@ -4,6 +4,6 @@ Import ('env')
sources = env.Glob('*.c')
incs = '../include ../../blenlib ../../blenkernel ../../makesdna ../../imbuf'
-incs += ' #/intern/guardedalloc'
+incs += ' #/intern/guardedalloc #/extern/glew/include'
env.BlenderLib ( 'bf_editors_space_view3d', sources, Split(incs), [], libtype=['core','intern'], priority=[35, 40] )
diff --git a/source/blender/ftfont/intern/FTF_TTFont.cpp b/source/blender/ftfont/intern/FTF_TTFont.cpp
index 77bfff5bd82..e8f2b82f970 100644
--- a/source/blender/ftfont/intern/FTF_TTFont.cpp
+++ b/source/blender/ftfont/intern/FTF_TTFont.cpp
@@ -31,6 +31,7 @@
#include <locale.h>
#include "libintl.h"
#include "BLI_blenlib.h"
+#include "BKE_font.h"
#include "../FTF_Settings.h"
@@ -48,49 +49,6 @@
#define FTF_MAX_STR_SIZE 512
-
-int utf8towchar(wchar_t *w, char *c)
-{
- int len=0;
- if(w==NULL || c==NULL) return(0);
- //printf("%s\n",c);
- while(*c)
- {
- //Converts Unicode to wchar:
-
- if(*c & 0x80)
- {
- if(*c & 0x40)
- {
- if(*c & 0x20)
- {
- if(*c & 0x10)
- {
- *w=(c[0] & 0x0f)<<18 | (c[1]&0x1f)<<12 | (c[2]&0x3f)<<6 | (c[3]&0x7f);
- c++;
- }
- else
- *w=(c[0] & 0x1f)<<12 | (c[1]&0x3f)<<6 | (c[2]&0x7f);
- c++;
- }
- else
- *w=(c[0] &0x3f)<<6 | c[1]&0x7f;
- c++;
- }
- else
- *w=(c[0] & 0x7f);
- }
- else
- *w=(c[0] & 0x7f);
-
- c++;
- w++;
- len++;
- }
- return len;
-}
-
-
FTF_TTFont::FTF_TTFont(void)
{
#ifdef __APPLE__
diff --git a/source/blender/gpu/CMakeLists.txt b/source/blender/gpu/CMakeLists.txt
new file mode 100644
index 00000000000..4d376f47d91
--- /dev/null
+++ b/source/blender/gpu/CMakeLists.txt
@@ -0,0 +1,34 @@
+# $Id: CMakeLists.txt 14444 2008-04-16 22:40:48Z hos $
+# ***** BEGIN GPL LICENSE BLOCK *****
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software Foundation,
+# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# The Original Code is Copyright (C) 2006, Blender Foundation
+# All rights reserved.
+#
+# The Original Code is: all of this file.
+#
+# Contributor(s): Jacques Beaurain.
+#
+# ***** END GPL LICENSE BLOCK *****
+
+FILE(GLOB SRC intern/*.c)
+
+SET(INC
+ . ../blenlib ../blenkernel ../makesdna ../include
+ ../../../extern/glew/include ../../../intern/guardedalloc ../imbuf)
+
+BLENDERLIB(bf_gpu "${SRC}" "${INC}")
+
diff --git a/source/blender/gpu/GPU_draw.h b/source/blender/gpu/GPU_draw.h
new file mode 100644
index 00000000000..2399e7b6a8c
--- /dev/null
+++ b/source/blender/gpu/GPU_draw.h
@@ -0,0 +1,116 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This shader is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This shader is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this shader; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Brecht Van Lommel.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef GPU_GAME_H
+#define GPU_GAME_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct MTFace;
+struct Image;
+struct Scene;
+struct Object;
+
+/* OpenGL drawing functions related to shading. These are also
+ * shared with the game engine, where there were previously
+ * duplicates of some of these functions. */
+
+/* Initialize
+ * - sets the default Blender opengl state, if in doubt, check
+ * the contents of this function
+ * - this is called when starting Blender, for opengl rendering,
+ * and for switching back from the game engine for example. */
+
+void GPU_state_init(void);
+
+/* Material drawing
+ * - first the state is initialized by a particular object and
+ * it's materials
+ * - after this, materials can be quickly enabled by their number,
+ * GPU_enable_material returns 0 if drawing should be skipped
+ * - after drawing, the material must be disabled again */
+
+void GPU_set_object_materials(struct Scene *scene, struct Object *ob,
+ int glsl, int *do_alpha_pass);
+int GPU_enable_material(int nr, void *attribs);
+void GPU_disable_material(void);
+
+void GPU_set_material_blend_mode(int blendmode);
+int GPU_get_material_blend_mode(void);
+
+/* TexFace drawing
+ * - this is mutually exclusive with material drawing, a mesh should
+ * be drawn using one or the other
+ * - passing NULL clears the state again */
+
+int GPU_set_tpage(struct MTFace *tface);
+
+/* Lights
+ * - returns how many lights were enabled
+ * - this affects fixed functions materials and texface, not glsl */
+
+int GPU_default_lights(void);
+int GPU_scene_object_lights(struct Scene *scene, struct Object *ob,
+ int lay, float viewmat[][4]);
+
+/* Text render
+ * - based on moving uv coordinates */
+
+void GPU_render_text(struct MTFace *tface, int mode,
+ const char *textstr, int textlen, unsigned int *col,
+ float *v1, float *v2, float *v3, float *v4, int glattrib);
+
+/* Mipmap settings
+ * - these will free textures on changes */
+
+void GPU_set_mipmap(int mipmap);
+void GPU_set_linear_mipmap(int linear);
+void GPU_paint_set_mipmap(int mipmap);
+
+/* Image updates and free
+ * - these deal with images bound as opengl textures */
+
+void GPU_paint_update_image(struct Image *ima, int x, int y, int w, int h);
+void GPU_update_images_framechange(void);
+int GPU_update_image_time(struct Image *ima, double time);
+int GPU_verify_image(struct Image *ima, int tftile, int tfmode, int compare);
+void GPU_free_image(struct Image *ima);
+void GPU_free_images(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/source/blender/gpu/GPU_extensions.h b/source/blender/gpu/GPU_extensions.h
new file mode 100644
index 00000000000..66b19449419
--- /dev/null
+++ b/source/blender/gpu/GPU_extensions.h
@@ -0,0 +1,145 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This shader is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This shader is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this shader; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Brecht Van Lommel.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef GPU_EXTENSIONS_H
+#define GPU_EXTENSIONS_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* GPU extensions support */
+
+struct Image;
+struct ImageUser;
+
+struct GPUTexture;
+typedef struct GPUTexture GPUTexture;
+
+struct GPUFrameBuffer;
+typedef struct GPUFrameBuffer GPUFrameBuffer;
+
+struct GPUShader;
+typedef struct GPUShader GPUShader;
+
+void GPU_extensions_disable(void);
+void GPU_extensions_init(void); /* call this before running any of the functions below */
+void GPU_extensions_exit(void);
+int GPU_extensions_minimum_support(void);
+int GPU_print_error(char *str);
+
+/* GPU Texture
+ - always returns unsigned char RGBA textures
+ - if texture with non square dimensions is created, depending on the
+ graphics card capabilities the texture may actually be stored in a
+ larger texture with power of two dimensions. the actual dimensions
+ may be querd with GPU_texture_opengl_width/height. GPU_texture_coord_2f
+ calls glTexCoord2f with the coordinates adjust for this.
+ - can use reference counting:
+ - reference counter after GPU_texture_create is 1
+ - GPU_texture_ref increases by one
+ - GPU_texture_free decreases by one, and frees if 0
+ - if created with from_blender, will not free the texture
+*/
+
+GPUTexture *GPU_texture_create_1D(int w, float *pixels);
+GPUTexture *GPU_texture_create_2D(int w, int h, float *pixels);
+GPUTexture *GPU_texture_create_depth(int w, int h);
+GPUTexture *GPU_texture_from_blender(struct Image *ima,
+ struct ImageUser *iuser, double time);
+void GPU_texture_free(GPUTexture *tex);
+
+void GPU_texture_ref(GPUTexture *tex);
+
+void GPU_texture_bind(GPUTexture *tex, int number);
+void GPU_texture_unbind(GPUTexture *tex);
+
+GPUFrameBuffer *GPU_texture_framebuffer(GPUTexture *tex);
+
+int GPU_texture_target(GPUTexture *tex);
+int GPU_texture_opengl_width(GPUTexture *tex);
+int GPU_texture_opengl_height(GPUTexture *tex);
+
+/* GPU Framebuffer
+ - this is a wrapper for an OpenGL framebuffer object (FBO). in practice
+ multiple FBO's may be created, to get around limitations on the number
+ of attached textures and the dimension requirements.
+ - after any of the GPU_framebuffer_* functions, GPU_framebuffer_restore must
+ be called before rendering to the window framebuffer again */
+
+GPUFrameBuffer *GPU_framebuffer_create();
+int GPU_framebuffer_texture_attach(GPUFrameBuffer *fb, GPUTexture *tex);
+void GPU_framebuffer_texture_detach(GPUFrameBuffer *fb, GPUTexture *tex);
+void GPU_framebuffer_texture_bind(GPUFrameBuffer *fb, GPUTexture *tex);
+void GPU_framebuffer_texture_unbind(GPUFrameBuffer *fb, GPUTexture *tex);
+void GPU_framebuffer_free(GPUFrameBuffer *fb);
+
+void GPU_framebuffer_restore();
+
+/* GPU Shader
+ - only for fragment shaders now
+ - must call texture bind before setting a texture as uniform! */
+
+GPUShader *GPU_shader_create(const char *vertexcode, const char *fragcode, const char *libcode); /*GPUShader *lib);*/
+/*GPUShader *GPU_shader_create_lib(const char *code);*/
+void GPU_shader_free(GPUShader *shader);
+
+void GPU_shader_bind(GPUShader *shader);
+void GPU_shader_unbind();
+
+int GPU_shader_get_uniform(GPUShader *shader, char *name);
+void GPU_shader_uniform_vector(GPUShader *shader, int location, int length,
+ int arraysize, float *value);
+void GPU_shader_uniform_texture(GPUShader *shader, int location, GPUTexture *tex);
+
+int GPU_shader_get_attribute(GPUShader *shader, char *name);
+
+/* Vertex attributes for shaders */
+
+#define GPU_MAX_ATTRIB 32
+
+typedef struct GPUVertexAttribs {
+ struct {
+ int type;
+ int glindex;
+ char name[32];
+ } layer[GPU_MAX_ATTRIB];
+
+ int totlayer;
+} GPUVertexAttribs;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/source/blender/gpu/GPU_material.h b/source/blender/gpu/GPU_material.h
new file mode 100644
index 00000000000..ccc687858f4
--- /dev/null
+++ b/source/blender/gpu/GPU_material.h
@@ -0,0 +1,169 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This shader is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This shader is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this shader; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Brecht Van Lommel.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __GPU_MATERIAL__
+#define __GPU_MATERIAL__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct Image;
+struct ImageUser;
+struct Material;
+struct Object;
+struct Lamp;
+struct bNode;
+struct LinkNode;
+struct Scene;
+struct GPUVertexAttribs;
+struct GPUNode;
+struct GPUNodeLink;
+struct GPUNodeStack;
+struct GPUMaterial;
+struct GPUTexture;
+struct GPULamp;
+
+typedef struct GPUNode GPUNode;
+typedef struct GPUNodeLink GPUNodeLink;
+typedef struct GPUMaterial GPUMaterial;
+typedef struct GPULamp GPULamp;
+
+/* Functions to create GPU Materials nodes */
+
+typedef enum GPUType {
+ GPU_NONE = 0,
+ GPU_FLOAT = 1,
+ GPU_VEC2 = 2,
+ GPU_VEC3 = 3,
+ GPU_VEC4 = 4,
+ GPU_MAT3 = 9,
+ GPU_MAT4 = 16,
+ GPU_TEX1D = 1001,
+ GPU_TEX2D = 1002,
+ GPU_SHADOW2D = 1003,
+ GPU_ATTRIB = 3001
+} GPUType;
+
+typedef enum GPUBuiltin {
+ GPU_VIEW_MATRIX = 1,
+ GPU_OBJECT_MATRIX = 2,
+ GPU_INVERSE_VIEW_MATRIX = 4,
+ GPU_INVERSE_OBJECT_MATRIX = 8,
+ GPU_VIEW_POSITION = 16,
+ GPU_VIEW_NORMAL = 32,
+ GPU_OBCOLOR = 64
+} GPUBuiltin;
+
+typedef enum GPUBlendMode {
+ GPU_BLEND_SOLID = 0,
+ GPU_BLEND_ADD = 1,
+ GPU_BLEND_ALPHA = 2,
+ GPU_BLEND_CLIP = 4
+} GPUBlendMode;
+
+typedef struct GPUNodeStack {
+ GPUType type;
+ char *name;
+ float vec[4];
+ struct GPUNodeLink *link;
+ short hasinput;
+ short hasoutput;
+ short sockettype;
+} GPUNodeStack;
+
+GPUNodeLink *GPU_attribute(int type, char *name);
+GPUNodeLink *GPU_uniform(float *num);
+GPUNodeLink *GPU_dynamic_uniform(float *num);
+GPUNodeLink *GPU_image(struct Image *ima, struct ImageUser *iuser);
+GPUNodeLink *GPU_texture(int size, float *pixels);
+GPUNodeLink *GPU_dynamic_texture(struct GPUTexture *tex);
+GPUNodeLink *GPU_socket(GPUNodeStack *sock);
+GPUNodeLink *GPU_builtin(GPUBuiltin builtin);
+
+int GPU_link(GPUMaterial *mat, char *name, ...);
+int GPU_stack_link(GPUMaterial *mat, char *name, GPUNodeStack *in, GPUNodeStack *out, ...);
+
+void GPU_material_output_link(GPUMaterial *material, GPUNodeLink *link);
+void GPU_material_enable_alpha(GPUMaterial *material);
+GPUBlendMode GPU_material_blend_mode(GPUMaterial *material, float obcol[4]);
+
+/* High level functions to create and use GPU materials */
+
+GPUMaterial *GPU_material_from_blender(struct Scene *scene, struct Material *ma);
+void GPU_material_free(struct Material *ma);
+
+void GPU_materials_free();
+
+void GPU_material_bind(GPUMaterial *material, int oblay, int viewlay, double time);
+void GPU_material_bind_uniforms(GPUMaterial *material, float obmat[][4], float viewmat[][4], float viewinv[][4], float obcol[4]);
+void GPU_material_unbind(GPUMaterial *material);
+int GPU_material_bound(GPUMaterial *material);
+
+void GPU_material_vertex_attributes(GPUMaterial *material,
+ struct GPUVertexAttribs *attrib);
+
+/* Exported shading */
+
+typedef struct GPUShadeInput {
+ GPUMaterial *gpumat;
+ struct Material *mat;
+
+ GPUNodeLink *rgb, *specrgb, *vn, *view, *vcol, *ref;
+ GPUNodeLink *alpha, *refl, *spec, *emit, *har, *amb;
+} GPUShadeInput;
+
+typedef struct GPUShadeResult {
+ GPUNodeLink *diff, *spec, *combined, *alpha;
+} GPUShadeResult;
+
+void GPU_shadeinput_set(GPUMaterial *mat, struct Material *ma, GPUShadeInput *shi);
+void GPU_shaderesult_set(GPUShadeInput *shi, GPUShadeResult *shr);
+
+/* Lamps */
+
+GPULamp *GPU_lamp_from_blender(struct Scene *scene, struct Object *ob, struct Object *par);
+void GPU_lamp_free(struct Object *ob);
+
+int GPU_lamp_has_shadow_buffer(GPULamp *lamp);
+void GPU_lamp_shadow_buffer_bind(GPULamp *lamp, float viewmat[][4], int *winsize, float winmat[][4]);
+void GPU_lamp_shadow_buffer_unbind(GPULamp *lamp);
+
+void GPU_lamp_update(GPULamp *lamp, int lay, float obmat[][4]);
+int GPU_lamp_shadow_layer(GPULamp *lamp);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /*__GPU_MATERIAL__*/
+
diff --git a/source/blender/gpu/Makefile b/source/blender/gpu/Makefile
new file mode 100644
index 00000000000..b9bde147115
--- /dev/null
+++ b/source/blender/gpu/Makefile
@@ -0,0 +1,37 @@
+#
+# $Id$
+#
+# ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version. The Blender
+# Foundation also sells licenses for use in proprietary software under
+# the Blender License. See http://www.blender.org/BL/ for information
+# about this.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software Foundation,
+# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+# All rights reserved.
+#
+# The Original Code is: all of this file.
+#
+# Contributor(s): none yet.
+#
+# ***** END GPL/BL DUAL LICENSE BLOCK *****
+#
+# Makes module object directory and bounces make to subdirectories.
+
+SOURCEDIR = source/blender/gpu
+DIRS = intern
+
+include nan_subdirs.mk
diff --git a/source/blender/gpu/SConscript b/source/blender/gpu/SConscript
new file mode 100644
index 00000000000..8ccd4b7b24c
--- /dev/null
+++ b/source/blender/gpu/SConscript
@@ -0,0 +1,11 @@
+#!/usr/bin/python
+Import ('env')
+
+sources = env.Glob('intern/*.c')
+
+incs = '../blenlib ../blenkernel ../makesdna ../include'
+incs += ' #/extern/glew/include #intern/guardedalloc ../imbuf .'
+
+incs += ' ' + env['BF_OPENGL_INC']
+
+env.BlenderLib ( 'bf_gpu', sources, Split(incs), [], libtype=['core', 'player'], priority=[65, 20] )
diff --git a/source/blender/gpu/intern/Makefile b/source/blender/gpu/intern/Makefile
new file mode 100644
index 00000000000..733ee3f764c
--- /dev/null
+++ b/source/blender/gpu/intern/Makefile
@@ -0,0 +1,53 @@
+#
+# $Id$
+#
+# ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version. The Blender
+# Foundation also sells licenses for use in proprietary software under
+# the Blender License. See http://www.blender.org/BL/ for information
+# about this.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software Foundation,
+# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+# All rights reserved.
+#
+# The Original Code is: all of this file.
+#
+# Contributor(s): none yet.
+#
+# ***** END GPL/BL DUAL LICENSE BLOCK *****
+#
+
+LIBNAME = gpu
+DIR = $(OCGDIR)/blender/$(LIBNAME)
+
+include nan_compile.mk
+
+ifeq ($(OS),$(findstring $(OS), "beos darwin freebsd linux openbsd solaris windows"))
+ CFLAGS += -funsigned-char
+endif
+
+CFLAGS += $(LEVEL_1_C_WARNINGS)
+
+CPPFLAGS += -I$(OPENGL_HEADERS)
+
+CPPFLAGS += -I../../blenlib
+CPPFLAGS += -I../../makesdna
+CPPFLAGS += -I../../imbuf
+CPPFLAGS += -I../../blenkernel
+CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include
+CPPFLAGS += -I$(NAN_GLEW)/include
+CPPFLAGS += -I../
+
diff --git a/source/blender/gpu/intern/gpu_codegen.c b/source/blender/gpu/intern/gpu_codegen.c
new file mode 100644
index 00000000000..94c1910e3bc
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_codegen.c
@@ -0,0 +1,1445 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Brecht Van Lommel.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "GL/glew.h"
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_customdata_types.h"
+#include "DNA_image_types.h"
+#include "DNA_listBase.h"
+#include "DNA_material_types.h"
+
+#include "BLI_dynstr.h"
+#include "BLI_blenlib.h"
+#include "BLI_ghash.h"
+#include "BLI_heap.h"
+
+#include "BKE_global.h"
+#include "BKE_utildefines.h"
+
+#include "GPU_material.h"
+#include "GPU_extensions.h"
+
+#include "BLO_sys_types.h" // for intptr_t support
+
+#include "gpu_codegen.h"
+
+#include <string.h>
+#include <stdarg.h>
+
+#ifdef _WIN32
+#ifndef vsnprintf
+#define vsnprintf _vsnprintf
+#endif
+#ifndef snprintf
+#define snprintf _snprintf
+#endif
+#endif
+
+extern char datatoc_gpu_shader_material_glsl[];
+extern char datatoc_gpu_shader_vertex_glsl[];
+
+/* structs and defines */
+
+typedef enum GPUDataSource {
+ GPU_SOURCE_VEC_UNIFORM,
+ GPU_SOURCE_BUILTIN,
+ GPU_SOURCE_TEX_PIXEL,
+ GPU_SOURCE_TEX,
+ GPU_SOURCE_ATTRIB
+} GPUDataSource;
+
+static char* GPU_DATATYPE_STR[17] = {"", "float", "vec2", "vec3", "vec4",
+ 0, 0, 0, 0, "mat3", 0, 0, 0, 0, 0, 0, "mat4"};
+
+struct GPUNode {
+ struct GPUNode *next, *prev;
+
+ char *name;
+ int tag;
+
+ ListBase inputs;
+ ListBase outputs;
+};
+
+struct GPUNodeLink {
+ GPUNodeStack *socket;
+
+ int attribtype;
+ char *attribname;
+
+ int image;
+
+ int texture;
+ int texturesize;
+
+ void *ptr1, *ptr2;
+
+ int dynamic;
+
+ int type;
+ int users;
+
+ GPUTexture *dynamictex;
+
+ GPUBuiltin builtin;
+
+ struct GPUOutput *output;
+};
+
+typedef struct GPUOutput {
+ struct GPUOutput *next, *prev;
+
+ GPUNode *node;
+ int type; /* data type = length of vector/matrix */
+ GPUNodeLink *link; /* output link */
+ int id; /* unique id as created by code generator */
+} GPUOutput;
+
+typedef struct GPUInput {
+ struct GPUInput *next, *prev;
+
+ GPUNode *node;
+
+ int type; /* datatype */
+ int source; /* data source */
+
+ int id; /* unique id as created by code generator */
+ int texid; /* number for multitexture */
+ int attribid; /* id for vertex attributes */
+ int bindtex; /* input is responsible for binding the texture? */
+ int definetex; /* input is responsible for defining the pixel? */
+ int textarget; /* GL_TEXTURE_* */
+ int textype; /* datatype */
+
+ struct Image *ima; /* image */
+ struct ImageUser *iuser;/* image user */
+ float *dynamicvec; /* vector data in case it is dynamic */
+ GPUTexture *tex; /* input texture, only set at runtime */
+ int shaderloc; /* id from opengl */
+ char shadername[32]; /* name in shader */
+
+ float vec[16]; /* vector data */
+ GPUNodeLink *link;
+ int dynamictex; /* dynamic? */
+ int attribtype; /* attribute type */
+ char attribname[32]; /* attribute name */
+ int attribfirst; /* this is the first one that is bound */
+ GPUBuiltin builtin; /* builtin uniform */
+} GPUInput;
+
+struct GPUPass {
+ struct GPUPass *next, *prev;
+
+ ListBase inputs;
+ struct GPUOutput *output;
+ struct GPUShader *shader;
+};
+
+/* Strings utility */
+
+static void BLI_dynstr_printf(DynStr *dynstr, const char *format, ...)
+{
+ va_list args;
+ int retval;
+ char str[2048];
+
+ va_start(args, format);
+ retval = vsnprintf(str, sizeof(str), format, args);
+ va_end(args);
+
+ if (retval >= sizeof(str))
+ fprintf(stderr, "BLI_dynstr_printf: limit exceeded\n");
+ else
+ BLI_dynstr_append(dynstr, str);
+}
+
+/* GLSL code parsing for finding function definitions.
+ * These are stored in a hash for lookup when creating a material. */
+
+static GHash *FUNCTION_HASH= NULL;
+/*static char *FUNCTION_PROTOTYPES= NULL;
+static GPUShader *FUNCTION_LIB= NULL;*/
+
+static int gpu_str_prefix(char *str, char *prefix)
+{
+ while(*str && *prefix) {
+ if(*str != *prefix)
+ return 0;
+
+ str++;
+ prefix++;
+ }
+
+ return (*prefix == '\0');
+}
+
+static char *gpu_str_skip_token(char *str, char *token, int max)
+{
+ int len = 0;
+
+ /* skip a variable/function name */
+ while(*str) {
+ if(ELEM6(*str, ' ', '(', ')', ',', '\t', '\n'))
+ break;
+ else {
+ if(token && len < max-1) {
+ *token= *str;
+ token++;
+ len++;
+ }
+ str++;
+ }
+ }
+
+ if(token)
+ *token= '\0';
+
+ /* skip the next special characters:
+ * note the missing ')' */
+ while(*str) {
+ if(ELEM5(*str, ' ', '(', ',', '\t', '\n'))
+ str++;
+ else
+ break;
+ }
+
+ return str;
+}
+
+static void gpu_parse_functions_string(GHash *hash, char *code)
+{
+ GPUFunction *function;
+ int i, type, qual;
+
+ while((code = strstr(code, "void "))) {
+ function = MEM_callocN(sizeof(GPUFunction), "GPUFunction");
+
+ code = gpu_str_skip_token(code, NULL, 0);
+ code = gpu_str_skip_token(code, function->name, MAX_FUNCTION_NAME);
+
+ /* get parameters */
+ while(*code && *code != ')') {
+ /* test if it's an input or output */
+ qual = FUNCTION_QUAL_IN;
+ if(gpu_str_prefix(code, "out "))
+ qual = FUNCTION_QUAL_OUT;
+ if(gpu_str_prefix(code, "inout "))
+ qual = FUNCTION_QUAL_INOUT;
+ if((qual != FUNCTION_QUAL_IN) || gpu_str_prefix(code, "in "))
+ code = gpu_str_skip_token(code, NULL, 0);
+
+ /* test for type */
+ type= 0;
+ for(i=1; i<=16; i++) {
+ if(GPU_DATATYPE_STR[i] && gpu_str_prefix(code, GPU_DATATYPE_STR[i])) {
+ type= i;
+ break;
+ }
+ }
+
+ if(!type && gpu_str_prefix(code, "sampler2DShadow"))
+ type= GPU_SHADOW2D;
+ if(!type && gpu_str_prefix(code, "sampler1D"))
+ type= GPU_TEX1D;
+ if(!type && gpu_str_prefix(code, "sampler2D"))
+ type= GPU_TEX2D;
+
+ if(type) {
+ /* add paramater */
+ code = gpu_str_skip_token(code, NULL, 0);
+ code = gpu_str_skip_token(code, NULL, 0);
+ function->paramqual[function->totparam]= qual;
+ function->paramtype[function->totparam]= type;
+ function->totparam++;
+ }
+ else {
+ fprintf(stderr, "GPU invalid function parameter in %s.\n", function->name);
+ break;
+ }
+ }
+
+ if(strlen(function->name) == 0 || function->totparam == 0) {
+ fprintf(stderr, "GPU functions parse error.\n");
+ MEM_freeN(function);
+ break;
+ }
+
+ BLI_ghash_insert(hash, function->name, function);
+ }
+}
+
+#if 0
+static char *gpu_generate_function_prototyps(GHash *hash)
+{
+ DynStr *ds = BLI_dynstr_new();
+ GHashIterator *ghi;
+ GPUFunction *function;
+ char *name, *prototypes;
+ int a;
+
+ /* automatically generate function prototypes to add to the top of the
+ * generated code, to avoid have to add the actual code & recompile all */
+ ghi = BLI_ghashIterator_new(hash);
+
+ for(; !BLI_ghashIterator_isDone(ghi); BLI_ghashIterator_step(ghi)) {
+ name = BLI_ghashIterator_getValue(ghi);
+ function = BLI_ghashIterator_getValue(ghi);
+
+ BLI_dynstr_printf(ds, "void %s(", name);
+ for(a=0; a<function->totparam; a++) {
+ if(function->paramqual[a] == FUNCTION_QUAL_OUT)
+ BLI_dynstr_append(ds, "out ");
+ else if(function->paramqual[a] == FUNCTION_QUAL_INOUT)
+ BLI_dynstr_append(ds, "inout ");
+
+ if(function->paramtype[a] == GPU_TEX1D)
+ BLI_dynstr_append(ds, "sampler1D");
+ else if(function->paramtype[a] == GPU_TEX2D)
+ BLI_dynstr_append(ds, "sampler2D");
+ else if(function->paramtype[a] == GPU_SHADOW2D)
+ BLI_dynstr_append(ds, "sampler2DShadow");
+ else
+ BLI_dynstr_append(ds, GPU_DATATYPE_STR[function->paramtype[a]]);
+
+ //BLI_dynstr_printf(ds, " param%d", a);
+
+ if(a != function->totparam-1)
+ BLI_dynstr_append(ds, ", ");
+ }
+ BLI_dynstr_append(ds, ");\n");
+ }
+
+ BLI_dynstr_append(ds, "\n");
+
+ prototypes = BLI_dynstr_get_cstring(ds);
+ BLI_dynstr_free(ds);
+
+ return prototypes;
+}
+#endif
+
+GPUFunction *GPU_lookup_function(char *name)
+{
+ if(!FUNCTION_HASH) {
+ FUNCTION_HASH = BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp);
+ gpu_parse_functions_string(FUNCTION_HASH, datatoc_gpu_shader_material_glsl);
+ /*FUNCTION_PROTOTYPES = gpu_generate_function_prototyps(FUNCTION_HASH);
+ FUNCTION_LIB = GPU_shader_create_lib(datatoc_gpu_shader_material_glsl);*/
+ }
+
+ return (GPUFunction*)BLI_ghash_lookup(FUNCTION_HASH, name);
+}
+
+void GPU_extensions_exit(void)
+{
+ extern Material defmaterial; // render module abuse...
+
+ if(defmaterial.gpumaterial.first)
+ GPU_material_free(&defmaterial);
+
+ if(FUNCTION_HASH) {
+ BLI_ghash_free(FUNCTION_HASH, NULL, (GHashValFreeFP)MEM_freeN);
+ FUNCTION_HASH = NULL;
+ }
+ /*if(FUNCTION_PROTOTYPES) {
+ MEM_freeN(FUNCTION_PROTOTYPES);
+ FUNCTION_PROTOTYPES = NULL;
+ }*/
+ /*if(FUNCTION_LIB) {
+ GPU_shader_free(FUNCTION_LIB);
+ FUNCTION_LIB = NULL;
+ }*/
+}
+
+/* GLSL code generation */
+
+static void codegen_convert_datatype(DynStr *ds, int from, int to, char *tmp, int id)
+{
+ char name[1024];
+
+ snprintf(name, sizeof(name), "%s%d", tmp, id);
+
+ if (from == to) {
+ BLI_dynstr_append(ds, name);
+ }
+ else if (to == GPU_FLOAT) {
+ if (from == GPU_VEC4)
+ BLI_dynstr_printf(ds, "dot(%s.rgb, vec3(0.35, 0.45, 0.2))", name);
+ else if (from == GPU_VEC3)
+ BLI_dynstr_printf(ds, "dot(%s, vec3(0.33))", name);
+ else if (from == GPU_VEC2)
+ BLI_dynstr_printf(ds, "%s.r", name);
+ }
+ else if (to == GPU_VEC2) {
+ if (from == GPU_VEC4)
+ BLI_dynstr_printf(ds, "vec2(dot(%s.rgb, vec3(0.35, 0.45, 0.2)), %s.a)", name, name);
+ else if (from == GPU_VEC3)
+ BLI_dynstr_printf(ds, "vec2(dot(%s.rgb, vec3(0.33)), 1.0)", name);
+ else if (from == GPU_FLOAT)
+ BLI_dynstr_printf(ds, "vec2(%s, 1.0)", name);
+ }
+ else if (to == GPU_VEC3) {
+ if (from == GPU_VEC4)
+ BLI_dynstr_printf(ds, "%s.rgb", name);
+ else if (from == GPU_VEC2)
+ BLI_dynstr_printf(ds, "vec3(%s.r, %s.r, %s.r)", name, name, name);
+ else if (from == GPU_FLOAT)
+ BLI_dynstr_printf(ds, "vec3(%s, %s, %s)", name, name, name);
+ }
+ else {
+ if (from == GPU_VEC3)
+ BLI_dynstr_printf(ds, "vec4(%s, 1.0)", name);
+ else if (from == GPU_VEC2)
+ BLI_dynstr_printf(ds, "vec4(%s.r, %s.r, %s.r, %s.g)", name, name, name, name);
+ else if (from == GPU_FLOAT)
+ BLI_dynstr_printf(ds, "vec4(%s, %s, %s, 1.0)", name, name, name);
+ }
+}
+
+static void codegen_print_datatype(DynStr *ds, int type, float *data)
+{
+ int i;
+
+ BLI_dynstr_printf(ds, "%s(", GPU_DATATYPE_STR[type]);
+
+ for(i=0; i<type; i++) {
+ BLI_dynstr_printf(ds, "%f", data[i]);
+ if(i == type-1)
+ BLI_dynstr_append(ds, ")");
+ else
+ BLI_dynstr_append(ds, ", ");
+ }
+}
+
+static int codegen_input_has_texture(GPUInput *input)
+{
+ if (input->link)
+ return 0;
+ else if(input->ima)
+ return 1;
+ else
+ return input->tex != 0;
+}
+
+char *GPU_builtin_name(GPUBuiltin builtin)
+{
+ if(builtin == GPU_VIEW_MATRIX)
+ return "unfviewmat";
+ else if(builtin == GPU_OBJECT_MATRIX)
+ return "unfobmat";
+ else if(builtin == GPU_INVERSE_VIEW_MATRIX)
+ return "unfinvviewmat";
+ else if(builtin == GPU_INVERSE_OBJECT_MATRIX)
+ return "unfinvobmat";
+ else if(builtin == GPU_VIEW_POSITION)
+ return "varposition";
+ else if(builtin == GPU_VIEW_NORMAL)
+ return "varnormal";
+ else if(builtin == GPU_OBCOLOR)
+ return "unfobcolor";
+ else
+ return "";
+}
+
+static void codegen_set_unique_ids(ListBase *nodes)
+{
+ GHash *bindhash, *definehash;
+ GPUNode *node;
+ GPUInput *input;
+ GPUOutput *output;
+ int id = 1, texid = 0;
+
+ bindhash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
+ definehash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
+
+ for (node=nodes->first; node; node=node->next) {
+ for (input=node->inputs.first; input; input=input->next) {
+ /* set id for unique names of uniform variables */
+ input->id = id++;
+ input->bindtex = 0;
+ input->definetex = 0;
+
+ /* set texid used for settings texture slot with multitexture */
+ if (codegen_input_has_texture(input) &&
+ ((input->source == GPU_SOURCE_TEX) || (input->source == GPU_SOURCE_TEX_PIXEL))) {
+ if (input->link) {
+ /* input is texture from buffer, assign only one texid per
+ buffer to avoid sampling the same texture twice */
+ if (!BLI_ghash_haskey(bindhash, input->link)) {
+ input->texid = texid++;
+ input->bindtex = 1;
+ BLI_ghash_insert(bindhash, input->link, SET_INT_IN_POINTER(input->texid));
+ }
+ else
+ input->texid = GET_INT_FROM_POINTER(BLI_ghash_lookup(bindhash, input->link));
+ }
+ else if(input->ima) {
+ /* input is texture from image, assign only one texid per
+ buffer to avoid sampling the same texture twice */
+ if (!BLI_ghash_haskey(bindhash, input->ima)) {
+ input->texid = texid++;
+ input->bindtex = 1;
+ BLI_ghash_insert(bindhash, input->ima, SET_INT_IN_POINTER(input->texid));
+ }
+ else
+ input->texid = GET_INT_FROM_POINTER(BLI_ghash_lookup(bindhash, input->ima));
+ }
+ else {
+ if (!BLI_ghash_haskey(bindhash, input->tex)) {
+ /* input is user created texture, check tex pointer */
+ input->texid = texid++;
+ input->bindtex = 1;
+ BLI_ghash_insert(bindhash, input->tex, SET_INT_IN_POINTER(input->texid));
+ }
+ else
+ input->texid = GET_INT_FROM_POINTER(BLI_ghash_lookup(bindhash, input->tex));
+ }
+
+ /* make sure this pixel is defined exactly once */
+ if (input->source == GPU_SOURCE_TEX_PIXEL) {
+ if(input->ima) {
+ if (!BLI_ghash_haskey(definehash, input->ima)) {
+ input->definetex = 1;
+ BLI_ghash_insert(definehash, input->ima, SET_INT_IN_POINTER(input->texid));
+ }
+ }
+ else {
+ if (!BLI_ghash_haskey(definehash, input->link)) {
+ input->definetex = 1;
+ BLI_ghash_insert(definehash, input->link, SET_INT_IN_POINTER(input->texid));
+ }
+ }
+ }
+ }
+ }
+
+ for (output=node->outputs.first; output; output=output->next)
+ /* set id for unique names of tmp variables storing output */
+ output->id = id++;
+ }
+
+ BLI_ghash_free(bindhash, NULL, NULL);
+ BLI_ghash_free(definehash, NULL, NULL);
+}
+
+static void codegen_print_uniforms_functions(DynStr *ds, ListBase *nodes)
+{
+ GPUNode *node;
+ GPUInput *input;
+ char *name;
+ int builtins = 0;
+
+ /* print uniforms */
+ for (node=nodes->first; node; node=node->next) {
+ for (input=node->inputs.first; input; input=input->next) {
+ if ((input->source == GPU_SOURCE_TEX) || (input->source == GPU_SOURCE_TEX_PIXEL)) {
+ /* create exactly one sampler for each texture */
+ if (codegen_input_has_texture(input) && input->bindtex)
+ BLI_dynstr_printf(ds, "uniform %s samp%d;\n",
+ (input->textype == GPU_TEX1D)? "sampler1D":
+ (input->textype == GPU_TEX2D)? "sampler2D": "sampler2DShadow",
+ input->texid);
+ }
+ else if(input->source == GPU_SOURCE_BUILTIN) {
+ /* only define each builting uniform/varying once */
+ if(!(builtins & input->builtin)) {
+ builtins |= input->builtin;
+ name = GPU_builtin_name(input->builtin);
+
+ if(gpu_str_prefix(name, "unf")) {
+ BLI_dynstr_printf(ds, "uniform %s %s;\n",
+ GPU_DATATYPE_STR[input->type], name);
+ }
+ else {
+ BLI_dynstr_printf(ds, "varying %s %s;\n",
+ GPU_DATATYPE_STR[input->type], name);
+ }
+ }
+ }
+ else if (input->source == GPU_SOURCE_VEC_UNIFORM) {
+ if(input->dynamicvec) {
+ /* only create uniforms for dynamic vectors */
+ BLI_dynstr_printf(ds, "uniform %s unf%d;\n",
+ GPU_DATATYPE_STR[input->type], input->id);
+ }
+ else {
+ /* for others use const so the compiler can do folding */
+ BLI_dynstr_printf(ds, "const %s cons%d = ",
+ GPU_DATATYPE_STR[input->type], input->id);
+ codegen_print_datatype(ds, input->type, input->vec);
+ BLI_dynstr_append(ds, ";\n");
+ }
+ }
+ else if (input->source == GPU_SOURCE_ATTRIB && input->attribfirst) {
+ BLI_dynstr_printf(ds, "varying %s var%d;\n",
+ GPU_DATATYPE_STR[input->type], input->attribid);
+ }
+ }
+ }
+
+ BLI_dynstr_append(ds, "\n");
+}
+
+static void codegen_declare_tmps(DynStr *ds, ListBase *nodes)
+{
+ GPUNode *node;
+ GPUInput *input;
+ GPUOutput *output;
+
+ for (node=nodes->first; node; node=node->next) {
+ /* load pixels from textures */
+ for (input=node->inputs.first; input; input=input->next) {
+ if (input->source == GPU_SOURCE_TEX_PIXEL) {
+ if (codegen_input_has_texture(input) && input->definetex) {
+ BLI_dynstr_printf(ds, "\tvec4 tex%d = texture2D(", input->texid);
+ BLI_dynstr_printf(ds, "samp%d, gl_TexCoord[%d].st);\n",
+ input->texid, input->texid);
+ }
+ }
+ }
+
+ /* declare temporary variables for node output storage */
+ for (output=node->outputs.first; output; output=output->next)
+ BLI_dynstr_printf(ds, "\t%s tmp%d;\n",
+ GPU_DATATYPE_STR[output->type], output->id);
+ }
+
+ BLI_dynstr_append(ds, "\n");
+}
+
+static void codegen_call_functions(DynStr *ds, ListBase *nodes, GPUOutput *finaloutput)
+{
+ GPUNode *node;
+ GPUInput *input;
+ GPUOutput *output;
+
+ for (node=nodes->first; node; node=node->next) {
+ BLI_dynstr_printf(ds, "\t%s(", node->name);
+
+ for (input=node->inputs.first; input; input=input->next) {
+ if (input->source == GPU_SOURCE_TEX) {
+ BLI_dynstr_printf(ds, "samp%d", input->texid);
+ if (input->link)
+ BLI_dynstr_printf(ds, ", gl_TexCoord[%d].st", input->texid);
+ }
+ else if (input->source == GPU_SOURCE_TEX_PIXEL) {
+ if (input->link && input->link->output)
+ codegen_convert_datatype(ds, input->link->output->type, input->type,
+ "tmp", input->link->output->id);
+ else
+ codegen_convert_datatype(ds, input->link->output->type, input->type,
+ "tex", input->texid);
+ }
+ else if(input->source == GPU_SOURCE_BUILTIN)
+ BLI_dynstr_printf(ds, "%s", GPU_builtin_name(input->builtin));
+ else if(input->source == GPU_SOURCE_VEC_UNIFORM) {
+ if(input->dynamicvec)
+ BLI_dynstr_printf(ds, "unf%d", input->id);
+ else
+ BLI_dynstr_printf(ds, "cons%d", input->id);
+ }
+ else if (input->source == GPU_SOURCE_ATTRIB)
+ BLI_dynstr_printf(ds, "var%d", input->attribid);
+
+ BLI_dynstr_append(ds, ", ");
+ }
+
+ for (output=node->outputs.first; output; output=output->next) {
+ BLI_dynstr_printf(ds, "tmp%d", output->id);
+ if (output->next)
+ BLI_dynstr_append(ds, ", ");
+ }
+
+ BLI_dynstr_append(ds, ");\n");
+ }
+
+ BLI_dynstr_append(ds, "\n\tgl_FragColor = ");
+ codegen_convert_datatype(ds, finaloutput->type, GPU_VEC4, "tmp", finaloutput->id);
+ BLI_dynstr_append(ds, ";\n");
+}
+
+static char *code_generate_fragment(ListBase *nodes, GPUOutput *output, const char *name)
+{
+ DynStr *ds = BLI_dynstr_new();
+ char *code;
+
+ /*BLI_dynstr_append(ds, FUNCTION_PROTOTYPES);*/
+
+ codegen_set_unique_ids(nodes);
+ codegen_print_uniforms_functions(ds, nodes);
+
+ //if(G.f & G_DEBUG)
+ // BLI_dynstr_printf(ds, "/* %s */\n", name);
+
+ BLI_dynstr_append(ds, "void main(void)\n");
+ BLI_dynstr_append(ds, "{\n");
+
+ codegen_declare_tmps(ds, nodes);
+ codegen_call_functions(ds, nodes, output);
+
+ BLI_dynstr_append(ds, "}\n");
+
+ /* create shader */
+ code = BLI_dynstr_get_cstring(ds);
+ BLI_dynstr_free(ds);
+
+ //if(G.f & G_DEBUG) printf("%s\n", code);
+
+ return code;
+}
+
+static char *code_generate_vertex(ListBase *nodes)
+{
+ DynStr *ds = BLI_dynstr_new();
+ GPUNode *node;
+ GPUInput *input;
+ char *code;
+
+ for (node=nodes->first; node; node=node->next) {
+ for (input=node->inputs.first; input; input=input->next) {
+ if (input->source == GPU_SOURCE_ATTRIB && input->attribfirst) {
+ BLI_dynstr_printf(ds, "attribute %s att%d;\n",
+ GPU_DATATYPE_STR[input->type], input->attribid);
+ BLI_dynstr_printf(ds, "varying %s var%d;\n",
+ GPU_DATATYPE_STR[input->type], input->attribid);
+ }
+ }
+ }
+
+ BLI_dynstr_append(ds, "\n");
+ BLI_dynstr_append(ds, datatoc_gpu_shader_vertex_glsl);
+
+ for (node=nodes->first; node; node=node->next)
+ for (input=node->inputs.first; input; input=input->next)
+ if (input->source == GPU_SOURCE_ATTRIB && input->attribfirst) {
+ if(input->attribtype == CD_TANGENT) /* silly exception */
+ BLI_dynstr_printf(ds, "\tvar%d = gl_NormalMatrix * ", input->attribid);
+ else
+ BLI_dynstr_printf(ds, "\tvar%d = ", input->attribid);
+
+ BLI_dynstr_printf(ds, "att%d;\n", input->attribid);
+ }
+
+ BLI_dynstr_append(ds, "}\n\n");
+
+ code = BLI_dynstr_get_cstring(ds);
+
+ BLI_dynstr_free(ds);
+
+ //if(G.f & G_DEBUG) printf("%s\n", code);
+
+ return code;
+}
+
+/* GPU pass binding/unbinding */
+
+GPUShader *GPU_pass_shader(GPUPass *pass)
+{
+ return pass->shader;
+}
+
+void GPU_nodes_extract_dynamic_inputs(GPUPass *pass, ListBase *nodes)
+{
+ GPUShader *shader = pass->shader;
+ GPUNode *node;
+ GPUInput *next, *input;
+ ListBase *inputs = &pass->inputs;
+ int extract, z;
+
+ memset(inputs, 0, sizeof(*inputs));
+
+ if(!shader)
+ return;
+
+ GPU_shader_bind(shader);
+
+ for (node=nodes->first; node; node=node->next) {
+ z = 0;
+ for (input=node->inputs.first; input; input=next, z++) {
+ next = input->next;
+
+ /* attributes don't need to be bound, they already have
+ * an id that the drawing functions will use */
+ if(input->source == GPU_SOURCE_ATTRIB ||
+ input->source == GPU_SOURCE_BUILTIN)
+ continue;
+
+ if (input->ima || input->tex)
+ snprintf(input->shadername, sizeof(input->shadername), "samp%d", input->texid);
+ else
+ snprintf(input->shadername, sizeof(input->shadername), "unf%d", input->id);
+
+ /* pass non-dynamic uniforms to opengl */
+ extract = 0;
+
+ if(input->ima || input->tex) {
+ if (input->bindtex)
+ extract = 1;
+ }
+ else if(input->dynamicvec)
+ extract = 1;
+
+ if(extract)
+ input->shaderloc = GPU_shader_get_uniform(shader, input->shadername);
+
+ /* extract nodes */
+ if(extract) {
+ BLI_remlink(&node->inputs, input);
+ BLI_addtail(inputs, input);
+ }
+ }
+ }
+
+ GPU_shader_unbind(shader);
+}
+
+void GPU_pass_bind(GPUPass *pass, double time)
+{
+ GPUInput *input;
+ GPUShader *shader = pass->shader;
+ ListBase *inputs = &pass->inputs;
+
+ if (!shader)
+ return;
+
+ GPU_shader_bind(shader);
+
+ /* now bind the textures */
+ for (input=inputs->first; input; input=input->next) {
+ if (input->ima)
+ input->tex = GPU_texture_from_blender(input->ima, input->iuser, time);
+
+ if(input->tex && input->bindtex) {
+ GPU_texture_bind(input->tex, input->texid);
+ GPU_shader_uniform_texture(shader, input->shaderloc, input->tex);
+ }
+ }
+}
+
+void GPU_pass_update_uniforms(GPUPass *pass)
+{
+ GPUInput *input;
+ GPUShader *shader = pass->shader;
+ ListBase *inputs = &pass->inputs;
+
+ if (!shader)
+ return;
+
+ /* pass dynamic inputs to opengl, others were removed */
+ for (input=inputs->first; input; input=input->next)
+ if(!(input->ima || input->tex))
+ GPU_shader_uniform_vector(shader, input->shaderloc, input->type, 1,
+ input->dynamicvec);
+}
+
+void GPU_pass_unbind(GPUPass *pass)
+{
+ GPUInput *input;
+ GPUShader *shader = pass->shader;
+ ListBase *inputs = &pass->inputs;
+
+ if (!shader)
+ return;
+
+ for (input=inputs->first; input; input=input->next) {
+ if(input->tex && input->bindtex)
+ GPU_texture_unbind(input->tex);
+
+ if (input->ima)
+ input->tex = 0;
+ }
+
+ GPU_shader_unbind(shader);
+}
+
+/* Node Link Functions */
+
+GPUNodeLink *GPU_node_link_create(int type)
+{
+ GPUNodeLink *link = MEM_callocN(sizeof(GPUNodeLink), "GPUNodeLink");
+ link->type = type;
+ link->users++;
+
+ return link;
+}
+
+void GPU_node_link_free(GPUNodeLink *link)
+{
+ link->users--;
+
+ if (link->users < 0)
+ fprintf(stderr, "GPU_node_link_free: negative refcount\n");
+
+ if (link->users == 0) {
+ if (link->output)
+ link->output->link = NULL;
+ MEM_freeN(link);
+ }
+}
+
+/* Node Functions */
+
+GPUNode *GPU_node_begin(char *name)
+{
+ GPUNode *node = MEM_callocN(sizeof(GPUNode), "GPUNode");
+
+ node->name = name;
+
+ return node;
+}
+
+void GPU_node_end(GPUNode *node)
+{
+ /* empty */
+}
+
+static void gpu_node_input_link(GPUNode *node, GPUNodeLink *link, int type)
+{
+ GPUInput *input;
+ GPUNode *outnode;
+ char *name;
+
+ if(link->output) {
+ outnode = link->output->node;
+ name = outnode->name;
+
+ if(strcmp(name, "set_value")==0 || strcmp(name, "set_rgb")==0) {
+ input = MEM_dupallocN(outnode->inputs.first);
+ input->type = type;
+ if(input->link)
+ input->link->users++;
+ BLI_addtail(&node->inputs, input);
+ return;
+ }
+ }
+
+ input = MEM_callocN(sizeof(GPUInput), "GPUInput");
+ input->node = node;
+
+ if(link->builtin) {
+ /* builtin uniform */
+ input->type = type;
+ input->source = GPU_SOURCE_BUILTIN;
+ input->builtin = link->builtin;
+
+ MEM_freeN(link);
+ }
+ else if(link->output) {
+ /* link to a node output */
+ input->type = type;
+ input->source = GPU_SOURCE_TEX_PIXEL;
+ input->link = link;
+ link->users++;
+ }
+ else if(link->dynamictex) {
+ /* dynamic texture, GPUTexture is updated/deleted externally */
+ input->type = type;
+ input->source = GPU_SOURCE_TEX;
+
+ input->tex = link->dynamictex;
+ input->textarget = GL_TEXTURE_2D;
+ input->textype = type;
+ input->dynamictex = 1;
+ MEM_freeN(link);
+ }
+ else if(link->texture) {
+ /* small texture created on the fly, like for colorbands */
+ input->type = GPU_VEC4;
+ input->source = GPU_SOURCE_TEX;
+ input->textype = type;
+
+ if (type == GPU_TEX1D) {
+ input->tex = GPU_texture_create_1D(link->texturesize, link->ptr1);
+ input->textarget = GL_TEXTURE_1D;
+ }
+ else {
+ input->tex = GPU_texture_create_2D(link->texturesize, link->texturesize, link->ptr2);
+ input->textarget = GL_TEXTURE_2D;
+ }
+
+ MEM_freeN(link->ptr1);
+ MEM_freeN(link);
+ }
+ else if(link->image) {
+ /* blender image */
+ input->type = GPU_VEC4;
+ input->source = GPU_SOURCE_TEX;
+
+ input->ima = link->ptr1;
+ input->textarget = GL_TEXTURE_2D;
+ input->textype = GPU_TEX2D;
+ MEM_freeN(link);
+ }
+ else if(link->attribtype) {
+ /* vertex attribute */
+ input->type = type;
+ input->source = GPU_SOURCE_ATTRIB;
+
+ input->attribtype = link->attribtype;
+ BLI_strncpy(input->attribname, link->attribname, sizeof(input->attribname));
+ MEM_freeN(link);
+ }
+ else {
+ /* uniform vector */
+ input->type = type;
+ input->source = GPU_SOURCE_VEC_UNIFORM;
+
+ memcpy(input->vec, link->ptr1, type*sizeof(float));
+ if(link->dynamic)
+ input->dynamicvec= link->ptr1;
+ MEM_freeN(link);
+ }
+
+ BLI_addtail(&node->inputs, input);
+}
+
+static void gpu_node_input_socket(GPUNode *node, GPUNodeStack *sock)
+{
+ GPUNodeLink *link;
+
+ if(sock->link) {
+ gpu_node_input_link(node, sock->link, sock->type);
+ }
+ else {
+ link = GPU_node_link_create(0);
+ link->ptr1 = sock->vec;
+ gpu_node_input_link(node, link, sock->type);
+ }
+}
+
+void GPU_node_output(GPUNode *node, int type, char *name, GPUNodeLink **link)
+{
+ GPUOutput *output = MEM_callocN(sizeof(GPUOutput), "GPUOutput");
+
+ output->type = type;
+ output->node = node;
+
+ if (link) {
+ *link = output->link = GPU_node_link_create(type);
+ output->link->output = output;
+
+ /* note: the caller owns the reference to the linkfer, GPUOutput
+ merely points to it, and if the node is destroyed it will
+ set that pointer to NULL */
+ }
+
+ BLI_addtail(&node->outputs, output);
+}
+
+void GPU_inputs_free(ListBase *inputs)
+{
+ GPUInput *input;
+
+ for(input=inputs->first; input; input=input->next) {
+ if(input->link)
+ GPU_node_link_free(input->link);
+ else if(input->tex && !input->dynamictex)
+ GPU_texture_free(input->tex);
+ }
+
+ BLI_freelistN(inputs);
+}
+
+void GPU_node_free(GPUNode *node)
+{
+ GPUOutput *output;
+
+ GPU_inputs_free(&node->inputs);
+
+ for (output=node->outputs.first; output; output=output->next)
+ if (output->link) {
+ output->link->output = NULL;
+ GPU_node_link_free(output->link);
+ }
+
+ BLI_freelistN(&node->outputs);
+ MEM_freeN(node);
+}
+
+void GPU_nodes_free(ListBase *nodes)
+{
+ GPUNode *node;
+
+ while (nodes->first) {
+ node = nodes->first;
+ BLI_remlink(nodes, node);
+ GPU_node_free(node);
+ }
+}
+
+/* vertex attributes */
+
+void gpu_nodes_get_vertex_attributes(ListBase *nodes, GPUVertexAttribs *attribs)
+{
+ GPUNode *node;
+ GPUInput *input;
+ int a;
+
+ /* convert attributes requested by node inputs to an array of layers,
+ * checking for duplicates and assigning id's starting from zero. */
+
+ memset(attribs, 0, sizeof(*attribs));
+
+ for(node=nodes->first; node; node=node->next) {
+ for(input=node->inputs.first; input; input=input->next) {
+ if(input->source == GPU_SOURCE_ATTRIB) {
+ for(a=0; a<attribs->totlayer; a++) {
+ if(attribs->layer[a].type == input->attribtype &&
+ strcmp(attribs->layer[a].name, input->attribname) == 0)
+ break;
+ }
+
+ if(a == attribs->totlayer && a < GPU_MAX_ATTRIB) {
+ input->attribid = attribs->totlayer++;
+ input->attribfirst = 1;
+
+ attribs->layer[a].type = input->attribtype;
+ attribs->layer[a].glindex = input->attribid;
+ BLI_strncpy(attribs->layer[a].name, input->attribname,
+ sizeof(attribs->layer[a].name));
+ }
+ else
+ input->attribid = attribs->layer[a].glindex;
+ }
+ }
+ }
+}
+
+void gpu_nodes_get_builtin_flag(ListBase *nodes, int *builtin)
+{
+ GPUNode *node;
+ GPUInput *input;
+
+ *builtin= 0;
+
+ for(node=nodes->first; node; node=node->next)
+ for(input=node->inputs.first; input; input=input->next)
+ if(input->source == GPU_SOURCE_BUILTIN)
+ *builtin |= input->builtin;
+}
+
+/* varargs linking */
+
+GPUNodeLink *GPU_attribute(int type, char *name)
+{
+ GPUNodeLink *link = GPU_node_link_create(0);
+
+ link->attribtype= type;
+ link->attribname= name;
+
+ return link;
+}
+
+GPUNodeLink *GPU_uniform(float *num)
+{
+ GPUNodeLink *link = GPU_node_link_create(0);
+
+ link->ptr1= num;
+ link->ptr2= NULL;
+
+ return link;
+}
+
+GPUNodeLink *GPU_dynamic_uniform(float *num)
+{
+ GPUNodeLink *link = GPU_node_link_create(0);
+
+ link->ptr1= num;
+ link->ptr2= NULL;
+ link->dynamic= 1;
+
+ return link;
+}
+
+GPUNodeLink *GPU_image(Image *ima, ImageUser *iuser)
+{
+ GPUNodeLink *link = GPU_node_link_create(0);
+
+ link->image= 1;
+ link->ptr1= ima;
+ link->ptr2= iuser;
+
+ return link;
+}
+
+GPUNodeLink *GPU_texture(int size, float *pixels)
+{
+ GPUNodeLink *link = GPU_node_link_create(0);
+
+ link->texture = 1;
+ link->texturesize = size;
+ link->ptr1= pixels;
+
+ return link;
+}
+
+GPUNodeLink *GPU_dynamic_texture(GPUTexture *tex)
+{
+ GPUNodeLink *link = GPU_node_link_create(0);
+
+ link->dynamic = 1;
+ link->dynamictex = tex;
+
+ return link;
+}
+
+GPUNodeLink *GPU_socket(GPUNodeStack *sock)
+{
+ GPUNodeLink *link = GPU_node_link_create(0);
+
+ link->socket= sock;
+
+ return link;
+}
+
+GPUNodeLink *GPU_builtin(GPUBuiltin builtin)
+{
+ GPUNodeLink *link = GPU_node_link_create(0);
+
+ link->builtin= builtin;
+
+ return link;
+}
+
+int GPU_link(GPUMaterial *mat, char *name, ...)
+{
+ GPUNode *node;
+ GPUFunction *function;
+ GPUNodeLink *link, **linkptr;
+ va_list params;
+ int i;
+
+ function = GPU_lookup_function(name);
+ if(!function) {
+ fprintf(stderr, "GPU failed to find function %s\n", name);
+ return 0;
+ }
+
+ node = GPU_node_begin(name);
+
+ va_start(params, name);
+ for(i=0; i<function->totparam; i++) {
+ if(function->paramqual[i] != FUNCTION_QUAL_IN) {
+ linkptr= va_arg(params, GPUNodeLink**);
+ GPU_node_output(node, function->paramtype[i], "", linkptr);
+ }
+ else {
+ link= va_arg(params, GPUNodeLink*);
+ gpu_node_input_link(node, link, function->paramtype[i]);
+ }
+ }
+ va_end(params);
+
+ GPU_node_end(node);
+
+ gpu_material_add_node(mat, node);
+
+ return 1;
+}
+
+int GPU_stack_link(GPUMaterial *mat, char *name, GPUNodeStack *in, GPUNodeStack *out, ...)
+{
+ GPUNode *node;
+ GPUFunction *function;
+ GPUNodeLink *link, **linkptr;
+ va_list params;
+ int i, totin, totout;
+
+ function = GPU_lookup_function(name);
+ if(!function) {
+ fprintf(stderr, "GPU failed to find function %s\n", name);
+ return 0;
+ }
+
+ node = GPU_node_begin(name);
+ totin = 0;
+ totout = 0;
+
+ if(in) {
+ for(i = 0; in[i].type != GPU_NONE; i++) {
+ gpu_node_input_socket(node, &in[i]);
+ totin++;
+ }
+ }
+
+ if(out) {
+ for(i = 0; out[i].type != GPU_NONE; i++) {
+ GPU_node_output(node, out[i].type, out[i].name, &out[i].link);
+ totout++;
+ }
+ }
+
+ va_start(params, out);
+ for(i=0; i<function->totparam; i++) {
+ if(function->paramqual[i] != FUNCTION_QUAL_IN) {
+ if(totout == 0) {
+ linkptr= va_arg(params, GPUNodeLink**);
+ GPU_node_output(node, function->paramtype[i], "", linkptr);
+ }
+ else
+ totout--;
+ }
+ else {
+ if(totin == 0) {
+ link= va_arg(params, GPUNodeLink*);
+ if(link->socket)
+ gpu_node_input_socket(node, link->socket);
+ else
+ gpu_node_input_link(node, link, function->paramtype[i]);
+ }
+ else
+ totin--;
+ }
+ }
+ va_end(params);
+
+ GPU_node_end(node);
+
+ gpu_material_add_node(mat, node);
+
+ return 1;
+}
+
+int GPU_link_changed(GPUNodeLink *link)
+{
+ GPUNode *node;
+ GPUInput *input;
+ char *name;
+
+ if(link->output) {
+ node = link->output->node;
+ name = node->name;
+
+ if(strcmp(name, "set_value")==0 || strcmp(name, "set_rgb")==0) {
+ input = node->inputs.first;
+ return (input->link != NULL);
+ }
+
+ return 1;
+ }
+ else
+ return 0;
+}
+
+/* Pass create/free */
+
+void gpu_nodes_tag(GPUNodeLink *link)
+{
+ GPUNode *node;
+ GPUInput *input;
+
+ if(!link->output)
+ return;
+
+ node = link->output->node;
+ if(node->tag)
+ return;
+
+ node->tag= 1;
+ for(input=node->inputs.first; input; input=input->next)
+ if(input->link)
+ gpu_nodes_tag(input->link);
+}
+
+void gpu_nodes_prune(ListBase *nodes, GPUNodeLink *outlink)
+{
+ GPUNode *node, *next;
+
+ for(node=nodes->first; node; node=node->next)
+ node->tag= 0;
+
+ gpu_nodes_tag(outlink);
+
+ for(node=nodes->first; node; node=next) {
+ next = node->next;
+
+ if(!node->tag) {
+ BLI_remlink(nodes, node);
+ GPU_node_free(node);
+ }
+ }
+}
+
+GPUPass *GPU_generate_pass(ListBase *nodes, GPUNodeLink *outlink, GPUVertexAttribs *attribs, int *builtins, const char *name)
+{
+ GPUShader *shader;
+ GPUPass *pass;
+ char *vertexcode, *fragmentcode;
+
+ /*if(!FUNCTION_LIB) {
+ GPU_nodes_free(nodes);
+ return NULL;
+ }*/
+
+ /* prune unused nodes */
+ gpu_nodes_prune(nodes, outlink);
+
+ gpu_nodes_get_vertex_attributes(nodes, attribs);
+ gpu_nodes_get_builtin_flag(nodes, builtins);
+
+ /* generate code and compile with opengl */
+ fragmentcode = code_generate_fragment(nodes, outlink->output, name);
+ vertexcode = code_generate_vertex(nodes);
+ shader = GPU_shader_create(vertexcode, fragmentcode, datatoc_gpu_shader_material_glsl); /*FUNCTION_LIB);*/
+ MEM_freeN(fragmentcode);
+ MEM_freeN(vertexcode);
+
+ /* failed? */
+ if (!shader) {
+ memset(attribs, 0, sizeof(*attribs));
+ memset(builtins, 0, sizeof(*builtins));
+ GPU_nodes_free(nodes);
+ return NULL;
+ }
+
+ /* create pass */
+ pass = MEM_callocN(sizeof(GPUPass), "GPUPass");
+
+ pass->output = outlink->output;
+ pass->shader = shader;
+
+ /* extract dynamic inputs and throw away nodes */
+ GPU_nodes_extract_dynamic_inputs(pass, nodes);
+ GPU_nodes_free(nodes);
+
+ return pass;
+}
+
+void GPU_pass_free(GPUPass *pass)
+{
+ GPU_shader_free(pass->shader);
+ GPU_inputs_free(&pass->inputs);
+ MEM_freeN(pass);
+}
+
diff --git a/source/blender/gpu/intern/gpu_codegen.h b/source/blender/gpu/intern/gpu_codegen.h
new file mode 100644
index 00000000000..53b52f24f16
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_codegen.h
@@ -0,0 +1,87 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Brecht Van Lommel.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __GPU_CODEGEN_H__
+#define __GPU_CODEGEN_H__
+
+#include "DNA_listBase.h"
+
+struct ListBase;
+struct GPUShader;
+struct GPUOutput;
+struct GPUNode;
+struct GPUVertexAttribs;
+
+#define MAX_FUNCTION_NAME 64
+#define MAX_PARAMETER 32
+
+#define FUNCTION_QUAL_IN 0
+#define FUNCTION_QUAL_OUT 1
+#define FUNCTION_QUAL_INOUT 2
+
+typedef struct GPUFunction {
+ char name[MAX_FUNCTION_NAME];
+ int paramtype[MAX_PARAMETER];
+ int paramqual[MAX_PARAMETER];
+ int totparam;
+} GPUFunction;
+
+GPUFunction *GPU_lookup_function(char *name);
+
+/* Pass Generation
+ - Takes a list of nodes and a desired output, and makes a pass. This
+ will take ownership of the nodes and free them early if unused or
+ at the end if used.
+*/
+
+struct GPUPass;
+typedef struct GPUPass GPUPass;
+
+GPUPass *GPU_generate_pass(ListBase *nodes, struct GPUNodeLink *outlink,
+ struct GPUVertexAttribs *attribs, int *builtin, const char *name);
+
+struct GPUShader *GPU_pass_shader(GPUPass *pass);
+
+void GPU_pass_bind(GPUPass *pass, double time);
+void GPU_pass_update_uniforms(GPUPass *pass);
+void GPU_pass_unbind(GPUPass *pass);
+
+void GPU_pass_free(GPUPass *pass);
+
+/* Material calls */
+
+char *GPU_builtin_name(GPUBuiltin builtin);
+void gpu_material_add_node(struct GPUMaterial *material, struct GPUNode *node);
+int GPU_link_changed(struct GPUNodeLink *link);
+
+#endif
+
diff --git a/source/blender/gpu/intern/gpu_draw.c b/source/blender/gpu/intern/gpu_draw.c
new file mode 100644
index 00000000000..4025a12a867
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_draw.c
@@ -0,0 +1,1185 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Brecht Van Lommel.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include <string.h>
+
+#include "GL/glew.h"
+
+#include "DNA_image_types.h"
+#include "DNA_lamp_types.h"
+#include "DNA_material_types.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_node_types.h"
+#include "DNA_object_types.h"
+#include "DNA_scene_types.h"
+#include "DNA_userdef_types.h"
+#include "DNA_view3d_types.h"
+
+#include "MEM_guardedalloc.h"
+
+#include "IMB_imbuf.h"
+#include "IMB_imbuf_types.h"
+
+#include "BKE_bmfont.h"
+#include "BKE_global.h"
+#include "BKE_image.h"
+#include "BKE_main.h"
+#include "BKE_material.h"
+#include "BKE_node.h"
+#include "BKE_object.h"
+#include "BKE_utildefines.h"
+
+#include "GPU_extensions.h"
+#include "GPU_material.h"
+#include "GPU_draw.h"
+
+/* These are some obscure rendering functions shared between the
+ * game engine and the blender, in this module to avoid duplicaten
+ * and abstract them away from the rest a bit */
+
+/* Text Rendering */
+
+static void gpu_mcol(unsigned int ucol)
+{
+ /* mcol order is swapped */
+ char *cp= (char *)&ucol;
+ glColor3ub(cp[3], cp[2], cp[1]);
+}
+
+void GPU_render_text(MTFace *tface, int mode,
+ const char *textstr, int textlen, unsigned int *col,
+ float *v1, float *v2, float *v3, float *v4, int glattrib)
+{
+ if (mode & TF_BMFONT) {
+ Image* ima;
+ int characters, index, character;
+ float centerx, centery, sizex, sizey, transx, transy, movex, movey, advance;
+
+ characters = textlen;
+
+ ima = (Image*)tface->tpage;
+ if (ima == NULL)
+ characters = 0;
+
+ // color has been set
+ if (tface->mode & TF_OBCOL)
+ col= NULL;
+ else if (!col)
+ glColor3f(1.0f, 1.0f, 1.0f);
+
+ glPushMatrix();
+ for (index = 0; index < characters; index++) {
+ float uv[4][2];
+
+ // lets calculate offset stuff
+ character = textstr[index];
+
+ // space starts at offset 1
+ // character = character - ' ' + 1;
+ matrixGlyph((ImBuf *)ima->ibufs.first, character, & centerx, &centery,
+ &sizex, &sizey, &transx, &transy, &movex, &movey, &advance);
+
+ uv[0][0] = (tface->uv[0][0] - centerx) * sizex + transx;
+ uv[0][1] = (tface->uv[0][1] - centery) * sizey + transy;
+ uv[1][0] = (tface->uv[1][0] - centerx) * sizex + transx;
+ uv[1][1] = (tface->uv[1][1] - centery) * sizey + transy;
+ uv[2][0] = (tface->uv[2][0] - centerx) * sizex + transx;
+ uv[2][1] = (tface->uv[2][1] - centery) * sizey + transy;
+
+ glBegin(GL_POLYGON);
+ if(glattrib >= 0) glVertexAttrib2fvARB(glattrib, uv[0]);
+ else glTexCoord2fv(uv[0]);
+ if(col) gpu_mcol(col[0]);
+ glVertex3f(sizex * v1[0] + movex, sizey * v1[1] + movey, v1[2]);
+
+ if(glattrib >= 0) glVertexAttrib2fvARB(glattrib, uv[1]);
+ else glTexCoord2fv(uv[1]);
+ if(col) gpu_mcol(col[1]);
+ glVertex3f(sizex * v2[0] + movex, sizey * v2[1] + movey, v2[2]);
+
+ if(glattrib >= 0) glVertexAttrib2fvARB(glattrib, uv[2]);
+ else glTexCoord2fv(uv[2]);
+ if(col) gpu_mcol(col[2]);
+ glVertex3f(sizex * v3[0] + movex, sizey * v3[1] + movey, v3[2]);
+
+ if(v4) {
+ uv[3][0] = (tface->uv[3][0] - centerx) * sizex + transx;
+ uv[3][1] = (tface->uv[3][1] - centery) * sizey + transy;
+
+ if(glattrib >= 0) glVertexAttrib2fvARB(glattrib, uv[3]);
+ else glTexCoord2fv(uv[3]);
+ if(col) gpu_mcol(col[3]);
+ glVertex3f(sizex * v4[0] + movex, sizey * v4[1] + movey, v4[2]);
+ }
+ glEnd();
+
+ glTranslatef(advance, 0.0, 0.0);
+ }
+ glPopMatrix();
+ }
+}
+
+/* Checking powers of two for images since opengl 1.x requires it */
+
+static int is_pow2(int num)
+{
+ /* (n&(n-1)) zeros the least significant bit of n */
+ return ((num)&(num-1))==0;
+}
+
+static int smaller_pow2(int num)
+{
+ while (!is_pow2(num))
+ num= num&(num-1);
+
+ return num;
+}
+
+static int is_pow2_limit(int num)
+{
+ /* take texture clamping into account */
+ if (U.glreslimit != 0 && num > U.glreslimit)
+ return 0;
+
+ return ((num)&(num-1))==0;
+}
+
+static int smaller_pow2_limit(int num)
+{
+ /* take texture clamping into account */
+ if (U.glreslimit != 0 && num > U.glreslimit)
+ return U.glreslimit;
+
+ return smaller_pow2(num);
+}
+
+/* Current OpenGL state caching for GPU_set_tpage */
+
+static struct GPUTextureState {
+ int curtile, tile;
+ int curtilemode, tilemode;
+ int curtileXRep, tileXRep;
+ int curtileYRep, tileYRep;
+ Image *ima, *curima;
+
+ int domipmap, linearmipmap;
+
+ int alphamode;
+ MTFace *lasttface;
+} GTS = {0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, 1, 0, -1, NULL};
+
+/* Mipmap settings */
+
+void GPU_set_mipmap(int mipmap)
+{
+ if (GTS.domipmap != (mipmap != 0)) {
+ GPU_free_images();
+ GTS.domipmap = mipmap != 0;
+ }
+}
+
+void GPU_set_linear_mipmap(int linear)
+{
+ if (GTS.linearmipmap != (linear != 0)) {
+ GPU_free_images();
+ GTS.linearmipmap = linear != 0;
+ }
+}
+
+static int gpu_get_mipmap(void)
+{
+ return GTS.domipmap && (!(G.f & G_TEXTUREPAINT));
+}
+
+static GLenum gpu_get_mipmap_filter(int mag)
+{
+ /* linearmipmap is off by default *when mipmapping is off,
+ * use unfiltered display */
+ if(mag) {
+ if(GTS.linearmipmap || GTS.domipmap)
+ return GL_LINEAR;
+ else
+ return GL_NEAREST;
+ }
+ else {
+ if(GTS.linearmipmap)
+ return GL_LINEAR_MIPMAP_LINEAR;
+ else if(GTS.domipmap)
+ return GL_LINEAR_MIPMAP_NEAREST;
+ else
+ return GL_NEAREST;
+ }
+}
+
+/* Set OpenGL state for an MTFace */
+
+static void gpu_make_repbind(Image *ima)
+{
+ ImBuf *ibuf;
+
+ ibuf = BKE_image_get_ibuf(ima, NULL);
+ if(ibuf==NULL)
+ return;
+
+ if(ima->repbind) {
+ glDeleteTextures(ima->totbind, (GLuint *)ima->repbind);
+ MEM_freeN(ima->repbind);
+ ima->repbind= 0;
+ ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
+ }
+
+ ima->totbind= ima->xrep*ima->yrep;
+
+ if(ima->totbind>1)
+ ima->repbind= MEM_callocN(sizeof(int)*ima->totbind, "repbind");
+}
+
+static void gpu_clear_tpage()
+{
+ if(GTS.lasttface==0)
+ return;
+
+ GTS.lasttface= 0;
+ GTS.curtile= 0;
+ GTS.curima= 0;
+ if(GTS.curtilemode!=0) {
+ glMatrixMode(GL_TEXTURE);
+ glLoadIdentity();
+ glMatrixMode(GL_MODELVIEW);
+ }
+ GTS.curtilemode= 0;
+ GTS.curtileXRep=0;
+ GTS.curtileYRep=0;
+ GTS.alphamode= -1;
+
+ glDisable(GL_BLEND);
+ glDisable(GL_TEXTURE_2D);
+ glDisable(GL_TEXTURE_GEN_S);
+ glDisable(GL_TEXTURE_GEN_T);
+ glDisable(GL_ALPHA_TEST);
+}
+
+static void gpu_set_blend_mode(GPUBlendMode blendmode)
+{
+ if(blendmode == GPU_BLEND_SOLID) {
+ glDisable(GL_BLEND);
+ glDisable(GL_ALPHA_TEST);
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ }
+ else if(blendmode==GPU_BLEND_ADD) {
+ glEnable(GL_BLEND);
+ glBlendFunc(GL_ONE, GL_ONE);
+ glDisable(GL_ALPHA_TEST);
+ }
+ else if(blendmode==GPU_BLEND_ALPHA) {
+ glEnable(GL_BLEND);
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+
+ /* if U.glalphaclip == 1.0, some cards go bonkers...
+ * turn off alpha test in this case */
+
+ /* added after 2.45 to clip alpha */
+ if(U.glalphaclip == 1.0) {
+ glDisable(GL_ALPHA_TEST);
+ }
+ else {
+ glEnable(GL_ALPHA_TEST);
+ glAlphaFunc(GL_GREATER, U.glalphaclip);
+ }
+ }
+ else if(blendmode==GPU_BLEND_CLIP) {
+ glDisable(GL_BLEND);
+ glEnable(GL_ALPHA_TEST);
+ glAlphaFunc(GL_GREATER, 0.5f);
+ }
+}
+
+static void gpu_verify_alpha_mode(MTFace *tface)
+{
+ /* verify alpha blending modes */
+ if(GTS.alphamode == tface->transp)
+ return;
+
+ gpu_set_blend_mode(tface->transp);
+ GTS.alphamode= tface->transp;
+}
+
+static void gpu_verify_reflection(Image *ima)
+{
+ if (ima && (ima->flag & IMA_REFLECT)) {
+ /* enable reflection mapping */
+ glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
+ glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
+
+ glEnable(GL_TEXTURE_GEN_S);
+ glEnable(GL_TEXTURE_GEN_T);
+ }
+ else {
+ /* disable reflection mapping */
+ glDisable(GL_TEXTURE_GEN_S);
+ glDisable(GL_TEXTURE_GEN_T);
+ }
+}
+
+int GPU_verify_image(Image *ima, int tftile, int tfmode, int compare)
+{
+ ImBuf *ibuf = NULL;
+ unsigned int *bind = NULL;
+ int rectw, recth, tpx=0, tpy=0, y;
+ unsigned int *rectrow, *tilerectrow;
+ unsigned int *tilerect= NULL, *scalerect= NULL, *rect= NULL;
+ short texwindx, texwindy, texwinsx, texwinsy;
+
+ /* initialize tile mode and number of repeats */
+ GTS.ima = ima;
+ GTS.tilemode= (tfmode & TF_TILES) || (ima && (ima->tpageflag & IMA_TWINANIM));
+ GTS.tileXRep = 0;
+ GTS.tileYRep = 0;
+
+ /* setting current tile according to frame */
+ if(ima && (ima->tpageflag & IMA_TWINANIM))
+ GTS.tile= ima->lastframe;
+ else
+ GTS.tile= tftile;
+
+ GTS.tile = MAX2(0, GTS.tile);
+
+ if(ima) {
+ GTS.tileXRep = ima->xrep;
+ GTS.tileYRep = ima->yrep;
+ }
+
+ /* if same image & tile, we're done */
+ if(compare && ima == GTS.curima && GTS.curtile == GTS.tile &&
+ GTS.tilemode == GTS.curtilemode && GTS.curtileXRep == GTS.tileXRep &&
+ GTS.curtileYRep == GTS.tileYRep)
+ return (ima!=0);
+
+ /* if tiling mode or repeat changed, change texture matrix to fit */
+ if(GTS.tilemode!=GTS.curtilemode || GTS.curtileXRep!=GTS.tileXRep ||
+ GTS.curtileYRep != GTS.tileYRep) {
+
+ glMatrixMode(GL_TEXTURE);
+ glLoadIdentity();
+
+ if((tfmode & TF_TILES) && ima!=NULL)
+ glScalef(ima->xrep, ima->yrep, 1.0);
+
+ glMatrixMode(GL_MODELVIEW);
+ }
+
+ /* check if we have a valid image */
+ if(ima==NULL || ima->ok==0)
+ return 0;
+
+ /* check if we have a valid image buffer */
+ ibuf= BKE_image_get_ibuf(ima, NULL);
+
+ if(ibuf==NULL)
+ return 0;
+
+ /* ensure we have a char buffer and not only float */
+ if ((ibuf->rect==NULL) && ibuf->rect_float)
+ IMB_rect_from_float(ibuf);
+
+ if(GTS.tilemode) {
+ /* tiled mode */
+ if(ima->repbind==0) gpu_make_repbind(ima);
+ if(GTS.tile>=ima->totbind) GTS.tile= 0;
+
+ /* this happens when you change repeat buttons */
+ if(ima->repbind) bind= &ima->repbind[GTS.tile];
+ else bind= &ima->bindcode;
+
+ if(*bind==0) {
+
+ texwindx= ibuf->x/ima->xrep;
+ texwindy= ibuf->y/ima->yrep;
+
+ if(GTS.tile>=ima->xrep*ima->yrep)
+ GTS.tile= ima->xrep*ima->yrep-1;
+
+ texwinsy= GTS.tile / ima->xrep;
+ texwinsx= GTS.tile - texwinsy*ima->xrep;
+
+ texwinsx*= texwindx;
+ texwinsy*= texwindy;
+
+ tpx= texwindx;
+ tpy= texwindy;
+
+ rect= ibuf->rect + texwinsy*ibuf->x + texwinsx;
+ }
+ }
+ else {
+ /* regular image mode */
+ bind= &ima->bindcode;
+
+ if(*bind==0) {
+ tpx= ibuf->x;
+ tpy= ibuf->y;
+ rect= ibuf->rect;
+ }
+ }
+
+ if(*bind != 0) {
+ /* enable opengl drawing with textures */
+ glBindTexture(GL_TEXTURE_2D, *bind);
+ return *bind;
+ }
+
+ rectw = tpx;
+ recth = tpy;
+
+ /* for tiles, copy only part of image into buffer */
+ if (GTS.tilemode) {
+ tilerect= MEM_mallocN(rectw*recth*sizeof(*tilerect), "tilerect");
+
+ for (y=0; y<recth; y++) {
+ rectrow= &rect[y*ibuf->x];
+ tilerectrow= &tilerect[y*rectw];
+
+ memcpy(tilerectrow, rectrow, tpx*sizeof(*rectrow));
+ }
+
+ rect= tilerect;
+ }
+
+ /* scale if not a power of two */
+ if (!is_pow2_limit(rectw) || !is_pow2_limit(recth)) {
+ rectw= smaller_pow2_limit(rectw);
+ recth= smaller_pow2_limit(recth);
+
+ scalerect= MEM_mallocN(rectw*recth*sizeof(*scalerect), "scalerect");
+ gluScaleImage(GL_RGBA, tpx, tpy, GL_UNSIGNED_BYTE, rect, rectw, recth, GL_UNSIGNED_BYTE, scalerect);
+ rect= scalerect;
+ }
+
+ /* create image */
+ glGenTextures(1, (GLuint *)bind);
+ glBindTexture( GL_TEXTURE_2D, *bind);
+
+ if (!gpu_get_mipmap()) {
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, rectw, recth, 0, GL_RGBA, GL_UNSIGNED_BYTE, rect);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
+ }
+ else {
+ gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, rectw, recth, GL_RGBA, GL_UNSIGNED_BYTE, rect);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gpu_get_mipmap_filter(0));
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
+
+ ima->tpageflag |= IMA_MIPMAP_COMPLETE;
+ }
+
+ /* set to modulate with vertex color */
+ glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
+
+ /* clean up */
+ if (tilerect)
+ MEM_freeN(tilerect);
+ if (scalerect)
+ MEM_freeN(scalerect);
+
+ return *bind;
+}
+
+static void gpu_verify_repeat(Image *ima)
+{
+ /* set either clamp or repeat in X/Y */
+ if (ima->tpageflag & IMA_CLAMP_U)
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ else
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+
+ if (ima->tpageflag & IMA_CLAMP_V)
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+ else
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+}
+
+int GPU_set_tpage(MTFace *tface)
+{
+ Image *ima;
+
+ /* check if we need to clear the state */
+ if(tface==0) {
+ gpu_clear_tpage();
+ return 0;
+ }
+
+ ima= tface->tpage;
+ GTS.lasttface= tface;
+
+ gpu_verify_alpha_mode(tface);
+ gpu_verify_reflection(ima);
+
+ if(GPU_verify_image(ima, tface->tile, tface->mode, 1)) {
+ GTS.curtile= GTS.tile;
+ GTS.curima= GTS.ima;
+ GTS.curtilemode= GTS.tilemode;
+ GTS.curtileXRep = GTS.tileXRep;
+ GTS.curtileYRep = GTS.tileYRep;
+
+ glEnable(GL_TEXTURE_2D);
+ }
+ else {
+ glDisable(GL_TEXTURE_2D);
+
+ GTS.curtile= 0;
+ GTS.curima= 0;
+ GTS.curtilemode= 0;
+ GTS.curtileXRep = 0;
+ GTS.curtileYRep = 0;
+
+ return 0;
+ }
+
+ gpu_verify_repeat(ima);
+
+ /* Did this get lost in the image recode? */
+ /* tag_image_time(ima);*/
+
+ return 1;
+}
+
+/* these two functions are called on entering and exiting texture paint mode,
+ temporary disabling/enabling mipmapping on all images for quick texture
+ updates with glTexSubImage2D. images that didn't change don't have to be
+ re-uploaded to OpenGL */
+void GPU_paint_set_mipmap(int mipmap)
+{
+ Image* ima;
+
+ if(!GTS.domipmap)
+ return;
+
+ if(mipmap) {
+ for(ima=G.main->image.first; ima; ima=ima->id.next) {
+ if(ima->bindcode) {
+ if(ima->tpageflag & IMA_MIPMAP_COMPLETE) {
+ glBindTexture(GL_TEXTURE_2D, ima->bindcode);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gpu_get_mipmap_filter(0));
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
+ }
+ else
+ GPU_free_image(ima);
+ }
+ }
+
+ }
+ else {
+ for(ima=G.main->image.first; ima; ima=ima->id.next) {
+ if(ima->bindcode) {
+ glBindTexture(GL_TEXTURE_2D, ima->bindcode);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
+ }
+ }
+ }
+}
+
+void GPU_paint_update_image(Image *ima, int x, int y, int w, int h)
+{
+ ImBuf *ibuf;
+
+ ibuf = BKE_image_get_ibuf(ima, NULL);
+
+ if (ima->repbind || gpu_get_mipmap() || !ima->bindcode || !ibuf ||
+ (!is_pow2(ibuf->x) || !is_pow2(ibuf->y)) ||
+ (w == 0) || (h == 0)) {
+ /* these cases require full reload still */
+ GPU_free_image(ima);
+ }
+ else {
+ /* for the special case, we can do a partial update
+ * which is much quicker for painting */
+ GLint row_length, skip_pixels, skip_rows;
+
+ glGetIntegerv(GL_UNPACK_ROW_LENGTH, &row_length);
+ glGetIntegerv(GL_UNPACK_SKIP_PIXELS, &skip_pixels);
+ glGetIntegerv(GL_UNPACK_SKIP_ROWS, &skip_rows);
+
+ if ((ibuf->rect==NULL) && ibuf->rect_float)
+ IMB_rect_from_float(ibuf);
+
+ glBindTexture(GL_TEXTURE_2D, ima->bindcode);
+
+ glPixelStorei(GL_UNPACK_ROW_LENGTH, ibuf->x);
+ glPixelStorei(GL_UNPACK_SKIP_PIXELS, x);
+ glPixelStorei(GL_UNPACK_SKIP_ROWS, y);
+
+ glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA,
+ GL_UNSIGNED_BYTE, ibuf->rect);
+
+ glPixelStorei(GL_UNPACK_ROW_LENGTH, row_length);
+ glPixelStorei(GL_UNPACK_SKIP_PIXELS, skip_pixels);
+ glPixelStorei(GL_UNPACK_SKIP_ROWS, skip_rows);
+
+ if(ima->tpageflag & IMA_MIPMAP_COMPLETE)
+ ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
+ }
+}
+
+void GPU_update_images_framechange(void)
+{
+ Image *ima;
+
+ for(ima=G.main->image.first; ima; ima=ima->id.next) {
+ if(ima->tpageflag & IMA_TWINANIM) {
+ if(ima->twend >= ima->xrep*ima->yrep)
+ ima->twend= ima->xrep*ima->yrep-1;
+
+ /* check: is bindcode not in the array? free. (to do) */
+
+ ima->lastframe++;
+ if(ima->lastframe > ima->twend)
+ ima->lastframe= ima->twsta;
+ }
+ }
+}
+
+int GPU_update_image_time(Image *ima, double time)
+{
+ int inc = 0;
+ float diff;
+ int newframe;
+
+ if (!ima)
+ return 0;
+
+ if (ima->lastupdate<0)
+ ima->lastupdate = 0;
+
+ if (ima->lastupdate>time)
+ ima->lastupdate=(float)time;
+
+ if(ima->tpageflag & IMA_TWINANIM) {
+ if(ima->twend >= ima->xrep*ima->yrep) ima->twend= ima->xrep*ima->yrep-1;
+
+ /* check: is the bindcode not in the array? Then free. (still to do) */
+
+ diff = (float)(time-ima->lastupdate);
+ inc = (int)(diff*(float)ima->animspeed);
+
+ ima->lastupdate+=((float)inc/(float)ima->animspeed);
+
+ newframe = ima->lastframe+inc;
+
+ if(newframe > (int)ima->twend) {
+ if(ima->twend-ima->twsta != 0)
+ newframe = (int)ima->twsta-1 + (newframe-ima->twend)%(ima->twend-ima->twsta);
+ else
+ newframe = ima->twsta;
+ }
+
+ ima->lastframe = newframe;
+ }
+
+ return inc;
+}
+
+void GPU_free_image(Image *ima)
+{
+ /* free regular image binding */
+ if(ima->bindcode) {
+ glDeleteTextures(1, (GLuint *)&ima->bindcode);
+ ima->bindcode= 0;
+ ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
+ }
+
+ /* free glsl image binding */
+ if(ima->gputexture) {
+ GPU_texture_free(ima->gputexture);
+ ima->gputexture= NULL;
+ }
+
+ /* free repeated image binding */
+ if(ima->repbind) {
+ glDeleteTextures(ima->totbind, (GLuint *)ima->repbind);
+
+ MEM_freeN(ima->repbind);
+ ima->repbind= NULL;
+ ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
+ }
+}
+
+void GPU_free_images(void)
+{
+ Image* ima;
+
+ if(G.main)
+ for(ima=G.main->image.first; ima; ima=ima->id.next)
+ GPU_free_image(ima);
+}
+
+/* OpenGL Materials */
+
+/* materials start counting at # one.... */
+#define MAXMATBUF (MAXMAT+1)
+
+/* OpenGL state caching for materials */
+
+static struct GPUMaterialState {
+ float matbuf[MAXMATBUF][2][4];
+ int totmat;
+
+ Material *gmatbuf[MAXMATBUF];
+ Material *gboundmat;
+ Object *gob;
+ Scene *gscene;
+
+ GPUBlendMode blendmode[MAXMATBUF];
+ int alphapass;
+
+ int lastmatnr, lastretval;
+ GPUBlendMode lastblendmode;
+} GMS;
+
+Material *gpu_active_node_material(Material *ma)
+{
+ if(ma && ma->use_nodes && ma->nodetree) {
+ bNode *node= nodeGetActiveID(ma->nodetree, ID_MA);
+
+ if(node)
+ return (Material *)node->id;
+ else
+ return NULL;
+ }
+
+ return ma;
+}
+
+void GPU_set_object_materials(Scene *scene, Object *ob, int glsl, int *do_alpha_pass)
+{
+ extern Material defmaterial; /* from material.c */
+ Material *ma;
+ GPUMaterial *gpumat;
+ GPUBlendMode blendmode;
+ int a;
+
+ /* initialize state */
+ memset(&GMS, 0, sizeof(GMS));
+ GMS.lastmatnr = -1;
+ GMS.lastretval = -1;
+ GMS.lastblendmode = GPU_BLEND_SOLID;
+
+ GMS.gob = ob;
+ GMS.gscene = scene;
+ GMS.totmat= ob->totcol;
+
+ GMS.alphapass = (G.vd && G.vd->transp);
+ if(do_alpha_pass)
+ *do_alpha_pass = 0;
+
+ /* no materials assigned? */
+ if(ob->totcol==0) {
+ GMS.matbuf[0][0][0]= defmaterial.r;
+ GMS.matbuf[0][0][1]= defmaterial.g;
+ GMS.matbuf[0][0][2]= defmaterial.b;
+ GMS.matbuf[0][0][3]= 1.0;
+
+ GMS.matbuf[0][1][0]= defmaterial.specr;
+ GMS.matbuf[0][1][1]= defmaterial.specg;
+ GMS.matbuf[0][1][2]= defmaterial.specb;
+ GMS.matbuf[0][1][3]= 1.0;
+
+ /* do material 1 too, for displists! */
+ QUATCOPY(GMS.matbuf[1][0], GMS.matbuf[0][0]);
+ QUATCOPY(GMS.matbuf[1][1], GMS.matbuf[0][1]);
+
+ if(glsl) {
+ GMS.gmatbuf[0]= &defmaterial;
+ GPU_material_from_blender(GMS.gscene, &defmaterial);
+ }
+
+ GMS.blendmode[0]= GPU_BLEND_SOLID;
+ }
+
+ /* setup materials */
+ for(a=1; a<=ob->totcol; a++) {
+ /* find a suitable material */
+ ma= give_current_material(ob, a);
+ if(!glsl) ma= gpu_active_node_material(ma);
+ if(ma==NULL) ma= &defmaterial;
+
+ /* this shouldn't happen .. */
+ if(a>=MAXMATBUF)
+ continue;
+
+ /* create glsl material if requested */
+ gpumat = (glsl)? GPU_material_from_blender(GMS.gscene, ma): NULL;
+
+ if(gpumat) {
+ /* do glsl only if creating it succeed, else fallback */
+ GMS.gmatbuf[a]= ma;
+ blendmode = GPU_material_blend_mode(gpumat, ob->col);
+ }
+ else {
+ /* fixed function opengl materials */
+ if (ma->mode & MA_SHLESS) {
+ GMS.matbuf[a][0][0]= ma->r;
+ GMS.matbuf[a][0][1]= ma->g;
+ GMS.matbuf[a][0][2]= ma->b;
+ } else {
+ GMS.matbuf[a][0][0]= (ma->ref+ma->emit)*ma->r;
+ GMS.matbuf[a][0][1]= (ma->ref+ma->emit)*ma->g;
+ GMS.matbuf[a][0][2]= (ma->ref+ma->emit)*ma->b;
+
+ GMS.matbuf[a][1][0]= ma->spec*ma->specr;
+ GMS.matbuf[a][1][1]= ma->spec*ma->specg;
+ GMS.matbuf[a][1][2]= ma->spec*ma->specb;
+ GMS.matbuf[a][1][3]= 1.0;
+ }
+
+ blendmode = (ma->alpha == 1.0f)? GPU_BLEND_SOLID: GPU_BLEND_ALPHA;
+ if(do_alpha_pass && GMS.alphapass)
+ GMS.matbuf[a][0][3]= ma->alpha;
+ else
+ GMS.matbuf[a][0][3]= 1.0f;
+ }
+
+ /* setting do_alpha_pass = 1 indicates this object needs to be
+ * drawn in a second alpha pass for improved blending */
+ if(do_alpha_pass) {
+ GMS.blendmode[a]= blendmode;
+ if(ELEM(blendmode, GPU_BLEND_ALPHA, GPU_BLEND_ADD) && !GMS.alphapass)
+ *do_alpha_pass= 1;
+ }
+ }
+
+ /* let's start with a clean state */
+ GPU_disable_material();
+}
+
+int GPU_enable_material(int nr, void *attribs)
+{
+ GPUVertexAttribs *gattribs = attribs;
+ GPUMaterial *gpumat;
+ GPUBlendMode blendmode;
+
+ /* prevent index to use un-initialized array items */
+ if(nr>GMS.totmat)
+ nr= GMS.totmat;
+
+ if(gattribs)
+ memset(gattribs, 0, sizeof(*gattribs));
+
+ /* keep current material */
+ if(nr>=MAXMATBUF || nr==GMS.lastmatnr)
+ return GMS.lastretval;
+
+ /* unbind glsl material */
+ if(GMS.gboundmat) {
+ if(GMS.alphapass) glDepthMask(0);
+ GPU_material_unbind(GPU_material_from_blender(GMS.gscene, GMS.gboundmat));
+ GMS.gboundmat= NULL;
+ }
+
+ /* draw materials with alpha in alpha pass */
+ GMS.lastmatnr = nr;
+ GMS.lastretval = ELEM(GMS.blendmode[nr], GPU_BLEND_SOLID, GPU_BLEND_CLIP);
+ if(GMS.alphapass)
+ GMS.lastretval = !GMS.lastretval;
+
+ if(GMS.lastretval) {
+ if(gattribs && GMS.gmatbuf[nr]) {
+ /* bind glsl material and get attributes */
+ Material *mat = GMS.gmatbuf[nr];
+
+ gpumat = GPU_material_from_blender(GMS.gscene, mat);
+ GPU_material_vertex_attributes(gpumat, gattribs);
+ GPU_material_bind(gpumat, GMS.gob->lay, G.vd->lay, 1.0);
+ GPU_material_bind_uniforms(gpumat, GMS.gob->obmat, G.vd->viewmat, G.vd->viewinv, GMS.gob->col);
+ GMS.gboundmat= mat;
+
+ if(GMS.alphapass) glDepthMask(1);
+ }
+ else {
+ /* or do fixed function opengl material */
+ glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, GMS.matbuf[nr][0]);
+ glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, GMS.matbuf[nr][1]);
+ }
+
+ /* set (alpha) blending mode */
+ blendmode = (GMS.alphapass)? GPU_BLEND_ALPHA: GPU_BLEND_SOLID;
+ GPU_set_material_blend_mode(blendmode);
+ }
+
+ return GMS.lastretval;
+}
+
+void GPU_set_material_blend_mode(int blendmode)
+{
+ if(GMS.lastblendmode == blendmode)
+ return;
+
+ gpu_set_blend_mode(blendmode);
+ GMS.lastblendmode = blendmode;
+}
+
+int GPU_get_material_blend_mode(void)
+{
+ return GMS.lastblendmode;
+}
+
+void GPU_disable_material(void)
+{
+ GMS.lastmatnr= -1;
+ GMS.lastretval= 1;
+
+ if(GMS.gboundmat) {
+ if(GMS.alphapass) glDepthMask(0);
+ GPU_material_unbind(GPU_material_from_blender(GMS.gscene, GMS.gboundmat));
+ GMS.gboundmat= NULL;
+ }
+
+ GPU_set_material_blend_mode(GPU_BLEND_SOLID);
+}
+
+/* Lights */
+
+int GPU_default_lights(void)
+{
+ int a, count = 0;
+
+ /* initialize */
+ if(U.light[0].flag==0 && U.light[1].flag==0 && U.light[2].flag==0) {
+ U.light[0].flag= 1;
+ U.light[0].vec[0]= -0.3; U.light[0].vec[1]= 0.3; U.light[0].vec[2]= 0.9;
+ U.light[0].col[0]= 0.8; U.light[0].col[1]= 0.8; U.light[0].col[2]= 0.8;
+ U.light[0].spec[0]= 0.5; U.light[0].spec[1]= 0.5; U.light[0].spec[2]= 0.5;
+ U.light[0].spec[3]= 1.0;
+
+ U.light[1].flag= 0;
+ U.light[1].vec[0]= 0.5; U.light[1].vec[1]= 0.5; U.light[1].vec[2]= 0.1;
+ U.light[1].col[0]= 0.4; U.light[1].col[1]= 0.4; U.light[1].col[2]= 0.8;
+ U.light[1].spec[0]= 0.3; U.light[1].spec[1]= 0.3; U.light[1].spec[2]= 0.5;
+ U.light[1].spec[3]= 1.0;
+
+ U.light[2].flag= 0;
+ U.light[2].vec[0]= 0.3; U.light[2].vec[1]= -0.3; U.light[2].vec[2]= -0.2;
+ U.light[2].col[0]= 0.8; U.light[2].col[1]= 0.5; U.light[2].col[2]= 0.4;
+ U.light[2].spec[0]= 0.5; U.light[2].spec[1]= 0.4; U.light[2].spec[2]= 0.3;
+ U.light[2].spec[3]= 1.0;
+ }
+
+ glLightfv(GL_LIGHT0, GL_POSITION, U.light[0].vec);
+ glLightfv(GL_LIGHT0, GL_DIFFUSE, U.light[0].col);
+ glLightfv(GL_LIGHT0, GL_SPECULAR, U.light[0].spec);
+
+ glLightfv(GL_LIGHT1, GL_POSITION, U.light[1].vec);
+ glLightfv(GL_LIGHT1, GL_DIFFUSE, U.light[1].col);
+ glLightfv(GL_LIGHT1, GL_SPECULAR, U.light[1].spec);
+
+ glLightfv(GL_LIGHT2, GL_POSITION, U.light[2].vec);
+ glLightfv(GL_LIGHT2, GL_DIFFUSE, U.light[2].col);
+ glLightfv(GL_LIGHT2, GL_SPECULAR, U.light[2].spec);
+
+ for(a=0; a<8; a++) {
+ if(a<3) {
+ if(U.light[a].flag) {
+ glEnable(GL_LIGHT0+a);
+ count++;
+ }
+ else
+ glDisable(GL_LIGHT0+a);
+
+ // clear stuff from other opengl lamp usage
+ glLightf(GL_LIGHT0+a, GL_SPOT_CUTOFF, 180.0);
+ glLightf(GL_LIGHT0+a, GL_CONSTANT_ATTENUATION, 1.0);
+ glLightf(GL_LIGHT0+a, GL_LINEAR_ATTENUATION, 0.0);
+ }
+ else
+ glDisable(GL_LIGHT0+a);
+ }
+
+ glDisable(GL_LIGHTING);
+
+ glDisable(GL_COLOR_MATERIAL);
+
+ return count;
+}
+
+int GPU_scene_object_lights(Scene *scene, Object *ob, int lay, float viewmat[][4])
+{
+ Base *base;
+ Lamp *la;
+ int count;
+ float position[4], direction[4], energy[4];
+
+ /* disable all lights */
+ for(count=0; count<8; count++)
+ glDisable(GL_LIGHT0+count);
+
+ count= 0;
+
+ for(base=scene->base.first; base; base=base->next) {
+ if(base->object->type!=OB_LAMP)
+ continue;
+
+ if(!(base->lay & lay) || !(base->lay & ob->lay))
+ continue;
+
+ la= base->object->data;
+
+ /* setup lamp transform */
+ glPushMatrix();
+ glLoadMatrixf((float *)viewmat);
+
+ where_is_object_simul(base->object);
+
+ if(la->type==LA_SUN) {
+ /* sun lamp */
+ VECCOPY(direction, base->object->obmat[2]);
+ direction[3]= 0.0;
+
+ glLightfv(GL_LIGHT0+count, GL_POSITION, direction);
+ }
+ else {
+ /* other lamps with attenuation */
+ VECCOPY(position, base->object->obmat[3]);
+ position[3]= 1.0f;
+
+ glLightfv(GL_LIGHT0+count, GL_POSITION, position);
+ glLightf(GL_LIGHT0+count, GL_CONSTANT_ATTENUATION, 1.0);
+ glLightf(GL_LIGHT0+count, GL_LINEAR_ATTENUATION, la->att1/la->dist);
+ glLightf(GL_LIGHT0+count, GL_QUADRATIC_ATTENUATION, la->att2/(la->dist*la->dist));
+
+ if(la->type==LA_SPOT) {
+ /* spot lamp */
+ direction[0]= -base->object->obmat[2][0];
+ direction[1]= -base->object->obmat[2][1];
+ direction[2]= -base->object->obmat[2][2];
+ glLightfv(GL_LIGHT0+count, GL_SPOT_DIRECTION, direction);
+ glLightf(GL_LIGHT0+count, GL_SPOT_CUTOFF, la->spotsize/2.0);
+ glLightf(GL_LIGHT0+count, GL_SPOT_EXPONENT, 128.0*la->spotblend);
+ }
+ else
+ glLightf(GL_LIGHT0+count, GL_SPOT_CUTOFF, 180.0);
+ }
+
+ /* setup energy */
+ energy[0]= la->energy*la->r;
+ energy[1]= la->energy*la->g;
+ energy[2]= la->energy*la->b;
+ energy[3]= 1.0;
+
+ glLightfv(GL_LIGHT0+count, GL_DIFFUSE, energy);
+ glLightfv(GL_LIGHT0+count, GL_SPECULAR, energy);
+ glEnable(GL_LIGHT0+count);
+
+ glPopMatrix();
+
+ count++;
+ if(count==8)
+ break;
+ }
+
+ return count;
+}
+
+/* Default OpenGL State */
+
+void GPU_state_init(void)
+{
+ /* also called when doing opengl rendering and in the game engine */
+ float mat_ambient[] = { 0.0, 0.0, 0.0, 0.0 };
+ float mat_specular[] = { 0.5, 0.5, 0.5, 1.0 };
+ float mat_shininess[] = { 35.0 };
+ int a, x, y;
+ GLubyte pat[32*32];
+ const GLubyte *patc= pat;
+
+ glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient);
+ glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_specular);
+ glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
+ glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess);
+
+ GPU_default_lights();
+
+ /* no local viewer, looks ugly in ortho mode */
+ /* glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, &one); */
+
+ glDepthFunc(GL_LEQUAL);
+ /* scaling matrices */
+ glEnable(GL_NORMALIZE);
+
+ glShadeModel(GL_FLAT);
+
+ glDisable(GL_ALPHA_TEST);
+ glDisable(GL_BLEND);
+ glDisable(GL_DEPTH_TEST);
+ glDisable(GL_FOG);
+ glDisable(GL_LIGHTING);
+ glDisable(GL_LOGIC_OP);
+ glDisable(GL_STENCIL_TEST);
+ glDisable(GL_TEXTURE_1D);
+ glDisable(GL_TEXTURE_2D);
+
+ /* default on, disable/enable should be local per function */
+ glEnableClientState(GL_VERTEX_ARRAY);
+ glEnableClientState(GL_NORMAL_ARRAY);
+
+ glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
+ glPixelTransferi(GL_RED_SCALE, 1);
+ glPixelTransferi(GL_RED_BIAS, 0);
+ glPixelTransferi(GL_GREEN_SCALE, 1);
+ glPixelTransferi(GL_GREEN_BIAS, 0);
+ glPixelTransferi(GL_BLUE_SCALE, 1);
+ glPixelTransferi(GL_BLUE_BIAS, 0);
+ glPixelTransferi(GL_ALPHA_SCALE, 1);
+ glPixelTransferi(GL_ALPHA_BIAS, 0);
+
+ glPixelTransferi(GL_DEPTH_BIAS, 0);
+ glPixelTransferi(GL_DEPTH_SCALE, 1);
+ glDepthRange(0.0, 1.0);
+
+ a= 0;
+ for(x=0; x<32; x++) {
+ for(y=0; y<4; y++) {
+ if( (x) & 1) pat[a++]= 0x88;
+ else pat[a++]= 0x22;
+ }
+ }
+
+ glPolygonStipple(patc);
+
+ glMatrixMode(GL_TEXTURE);
+ glLoadIdentity();
+ glMatrixMode(GL_MODELVIEW);
+
+ glFrontFace(GL_CCW);
+ glCullFace(GL_BACK);
+ glDisable(GL_CULL_FACE);
+}
+
diff --git a/source/blender/gpu/intern/gpu_extensions.c b/source/blender/gpu/intern/gpu_extensions.c
new file mode 100644
index 00000000000..7654c67419b
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_extensions.c
@@ -0,0 +1,998 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License. See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Brecht Van Lommel.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "GL/glew.h"
+
+#include "DNA_listBase.h"
+#include "DNA_image_types.h"
+#include "DNA_userdef_types.h"
+
+#include "MEM_guardedalloc.h"
+
+#include "BKE_image.h"
+#include "BKE_global.h"
+#include "BKE_utildefines.h"
+
+#include "IMB_imbuf.h"
+#include "IMB_imbuf_types.h"
+
+#include "BLI_blenlib.h"
+
+#include "GPU_draw.h"
+#include "GPU_extensions.h"
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+/* Extensions support */
+
+/* extensions used:
+ - texture border clamp: 1.3 core
+ - fragement shader: 2.0 core
+ - framebuffer object: ext specification
+ - multitexture 1.3 core
+ - arb non power of two: 2.0 core
+ - pixel buffer objects? 2.1 core
+ - arb draw buffers? 2.0 core
+*/
+
+static struct GPUGlobal {
+ GLint maxtextures;
+ GLuint currentfb;
+ int minimumsupport;
+ int extdisabled;
+} GG = {1, 0, 0, 0};
+
+void GPU_extensions_disable()
+{
+ GG.extdisabled = 1;
+}
+
+void GPU_extensions_init()
+{
+ glewInit();
+
+ /* glewIsSupported("GL_VERSION_2_0") */
+
+ if (GLEW_ARB_multitexture)
+ glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS_ARB, &GG.maxtextures);
+
+ GG.minimumsupport = 1;
+ if (!GLEW_ARB_multitexture) GG.minimumsupport = 0;
+ if (!GLEW_ARB_vertex_shader) GG.minimumsupport = 0;
+ if (!GLEW_ARB_fragment_shader) GG.minimumsupport = 0;
+}
+
+int GPU_extensions_minimum_support()
+{
+ return !GG.extdisabled && GG.minimumsupport;
+}
+
+int GPU_print_error(char *str)
+{
+ GLenum errCode;
+
+ if (G.f & G_DEBUG) {
+ if ((errCode = glGetError()) != GL_NO_ERROR) {
+ fprintf(stderr, "%s opengl error: %s\n", str, gluErrorString(errCode));
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+static void GPU_print_framebuffer_error(GLenum status)
+{
+ fprintf(stderr, "GPUFrameBuffer: framebuffer incomplete error %d\n",
+ (int)status);
+
+ switch(status) {
+ case GL_FRAMEBUFFER_COMPLETE_EXT:
+ break;
+ case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
+ fprintf(stderr, "Incomplete attachment.\n");
+ break;
+ case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
+ fprintf(stderr, "Unsupported framebuffer format.\n");
+ break;
+ case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
+ fprintf(stderr, "Missing attachment.\n");
+ break;
+ case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
+ fprintf(stderr, "Attached images must have same dimensions.\n");
+ break;
+ case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
+ fprintf(stderr, "Attached images must have same format.\n");
+ break;
+ case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
+ fprintf(stderr, "Missing draw buffer.\n");
+ break;
+ case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT:
+ fprintf(stderr, "Missing read buffer.\n");
+ break;
+ default:
+ fprintf(stderr, "Unknown.\n");
+ break;
+ }
+}
+
+/* GPUTexture */
+
+struct GPUTexture {
+ int w, h; /* width/height */
+ int number; /* number for multitexture binding */
+ int refcount; /* reference count */
+ GLenum target; /* GL_TEXTURE_* */
+ GLuint bindcode; /* opengl identifier for texture */
+ int fromblender; /* we got the texture from Blender */
+
+ GPUFrameBuffer *fb; /* GPUFramebuffer this texture is attached to */
+ int depth; /* is a depth texture? */
+};
+
+static unsigned char *GPU_texture_convert_pixels(int length, float *fpixels)
+{
+ unsigned char *pixels, *p;
+ float *fp;
+ int a, len;
+
+ len = 4*length;
+ fp = fpixels;
+ p = pixels = MEM_callocN(sizeof(unsigned char)*len, "GPUTexturePixels");
+
+ for (a=0; a<len; a++, p++, fp++)
+ *p = FTOCHAR((*fp));
+
+ return pixels;
+}
+
+static int is_pow2(int n)
+{
+ return ((n)&(n-1))==0;
+}
+
+static int larger_pow2(int n)
+{
+ if (is_pow2(n))
+ return n;
+
+ while(!is_pow2(n))
+ n= n&(n-1);
+
+ return n*2;
+}
+
+static void GPU_glTexSubImageEmpty(GLenum target, GLenum format, int x, int y, int w, int h)
+{
+ void *pixels = MEM_callocN(sizeof(char)*4*w*h, "GPUTextureEmptyPixels");
+
+ if (target == GL_TEXTURE_1D)
+ glTexSubImage1D(target, 0, x, w, format, GL_UNSIGNED_BYTE, pixels);
+ else
+ glTexSubImage2D(target, 0, x, y, w, h, format, GL_UNSIGNED_BYTE, pixels);
+
+ MEM_freeN(pixels);
+}
+
+static GPUTexture *GPU_texture_create_nD(int w, int h, int n, float *fpixels, int depth)
+{
+ GPUTexture *tex;
+ GLenum type, format, internalformat;
+ void *pixels = NULL;
+
+ if(depth && !GLEW_ARB_depth_texture)
+ return NULL;
+
+ tex = MEM_callocN(sizeof(GPUTexture), "GPUTexture");
+ tex->w = w;
+ tex->h = h;
+ tex->number = -1;
+ tex->refcount = 1;
+ tex->target = (n == 1)? GL_TEXTURE_1D: GL_TEXTURE_2D;
+ tex->depth = depth;
+
+ glGenTextures(1, &tex->bindcode);
+
+ if (!tex->bindcode) {
+ fprintf(stderr, "GPUTexture: texture create failed: %d\n",
+ (int)glGetError());
+ GPU_texture_free(tex);
+ return NULL;
+ }
+
+ if (!GLEW_ARB_texture_non_power_of_two) {
+ tex->w = larger_pow2(tex->w);
+ tex->h = larger_pow2(tex->h);
+ }
+
+ tex->number = 0;
+ glBindTexture(tex->target, tex->bindcode);
+
+ if(depth) {
+ type = GL_UNSIGNED_BYTE;
+ format = GL_DEPTH_COMPONENT;
+ internalformat = GL_DEPTH_COMPONENT;
+ }
+ else {
+ type = GL_UNSIGNED_BYTE;
+ format = GL_RGBA;
+ internalformat = GL_RGBA8;
+
+ if (fpixels)
+ pixels = GPU_texture_convert_pixels(w*h, fpixels);
+ }
+
+ if (tex->target == GL_TEXTURE_1D) {
+ glTexImage1D(tex->target, 0, internalformat, tex->w, 0, format, type, 0);
+
+ if (fpixels) {
+ glTexSubImage1D(tex->target, 0, 0, w, format, type,
+ pixels? pixels: fpixels);
+
+ if (tex->w > w)
+ GPU_glTexSubImageEmpty(tex->target, format, w, 0,
+ tex->w-w, 1);
+ }
+ }
+ else {
+ glTexImage2D(tex->target, 0, internalformat, tex->w, tex->h, 0,
+ format, type, 0);
+
+ if (fpixels) {
+ glTexSubImage2D(tex->target, 0, 0, 0, w, h,
+ format, type, pixels? pixels: fpixels);
+
+ if (tex->w > w)
+ GPU_glTexSubImageEmpty(tex->target, format, w, 0, tex->w-w, tex->h);
+ if (tex->h > h)
+ GPU_glTexSubImageEmpty(tex->target, format, 0, h, w, tex->h-h);
+ }
+ }
+
+ if (pixels)
+ MEM_freeN(pixels);
+
+ if(depth) {
+ glTexParameteri(tex->target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+ glTexParameteri(tex->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ glTexParameteri(tex->target, GL_TEXTURE_COMPARE_MODE_ARB, GL_COMPARE_R_TO_TEXTURE);
+ glTexParameteri(tex->target, GL_TEXTURE_COMPARE_FUNC_ARB, GL_LEQUAL);
+ glTexParameteri(tex->target, GL_DEPTH_TEXTURE_MODE_ARB, GL_INTENSITY);
+ }
+ else {
+ glTexParameteri(tex->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ glTexParameteri(tex->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ }
+
+ if (tex->target != GL_TEXTURE_1D) {
+ /* CLAMP_TO_BORDER is an OpenGL 1.3 core feature */
+ GLenum wrapmode = (depth)? GL_CLAMP_TO_EDGE: GL_CLAMP_TO_BORDER;
+ glTexParameteri(tex->target, GL_TEXTURE_WRAP_S, wrapmode);
+ glTexParameteri(tex->target, GL_TEXTURE_WRAP_T, wrapmode);
+
+#if 0
+ float borderColor[] = { 1.0f, 1.0f, 1.0f, 1.0f };
+ glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor);
+#endif
+ }
+ else
+ glTexParameteri(tex->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+
+ return tex;
+}
+
+GPUTexture *GPU_texture_from_blender(Image *ima, ImageUser *iuser, double time)
+{
+ GPUTexture *tex;
+ GLint w, h, border, lastbindcode, bindcode;
+
+ glGetIntegerv(GL_TEXTURE_BINDING_2D, &lastbindcode);
+
+ GPU_update_image_time(ima, time);
+ bindcode = GPU_verify_image(ima, 0, 0, 0);
+
+ if(ima->gputexture) {
+ ima->gputexture->bindcode = bindcode;
+ glBindTexture(GL_TEXTURE_2D, lastbindcode);
+ return ima->gputexture;
+ }
+
+ if(!bindcode) {
+ glBindTexture(GL_TEXTURE_2D, lastbindcode);
+ return NULL;
+ }
+
+ tex = MEM_callocN(sizeof(GPUTexture), "GPUTexture");
+ tex->bindcode = bindcode;
+ tex->number = -1;
+ tex->refcount = 1;
+ tex->target = GL_TEXTURE_2D;
+ tex->fromblender = 1;
+
+ ima->gputexture= tex;
+
+ if (!glIsTexture(tex->bindcode)) {
+ GPU_print_error("Blender Texture");
+ }
+ else {
+ glBindTexture(GL_TEXTURE_2D, tex->bindcode);
+ glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &w);
+ glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &h);
+ glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_BORDER, &border);
+
+ tex->w = w - border;
+ tex->h = h - border;
+ }
+
+ glBindTexture(GL_TEXTURE_2D, lastbindcode);
+
+ return tex;
+}
+
+GPUTexture *GPU_texture_create_1D(int w, float *fpixels)
+{
+ GPUTexture *tex = GPU_texture_create_nD(w, 1, 1, fpixels, 0);
+
+ if (tex)
+ GPU_texture_unbind(tex);
+
+ return tex;
+}
+
+GPUTexture *GPU_texture_create_2D(int w, int h, float *fpixels)
+{
+ GPUTexture *tex = GPU_texture_create_nD(w, h, 2, fpixels, 0);
+
+ if (tex)
+ GPU_texture_unbind(tex);
+
+ return tex;
+}
+
+GPUTexture *GPU_texture_create_depth(int w, int h)
+{
+ GPUTexture *tex = GPU_texture_create_nD(w, h, 2, NULL, 1);
+
+ if (tex)
+ GPU_texture_unbind(tex);
+
+ return tex;
+}
+
+void GPU_texture_bind(GPUTexture *tex, int number)
+{
+ GLenum arbnumber;
+
+ if (number >= GG.maxtextures) {
+ GPU_print_error("Not enough texture slots.");
+ return;
+ }
+
+ if(number == -1)
+ return;
+
+ GPU_print_error("Pre Texture Bind");
+
+ arbnumber = (GLenum)((GLuint)GL_TEXTURE0_ARB + number);
+ if (number != 0) glActiveTextureARB(arbnumber);
+ glBindTexture(tex->target, tex->bindcode);
+ glEnable(tex->target);
+ if (number != 0) glActiveTextureARB(GL_TEXTURE0_ARB);
+
+ tex->number = number;
+
+ GPU_print_error("Post Texture Bind");
+}
+
+void GPU_texture_unbind(GPUTexture *tex)
+{
+ GLenum arbnumber;
+
+ if (tex->number >= GG.maxtextures) {
+ GPU_print_error("Not enough texture slots.");
+ return;
+ }
+
+ if(tex->number == -1)
+ return;
+
+ GPU_print_error("Pre Texture Unbind");
+
+ arbnumber = (GLenum)((GLuint)GL_TEXTURE0_ARB + tex->number);
+ if (tex->number != 0) glActiveTextureARB(arbnumber);
+ glBindTexture(tex->target, 0);
+ glDisable(tex->target);
+ if (tex->number != 0) glActiveTextureARB(GL_TEXTURE0_ARB);
+
+ tex->number = -1;
+
+ GPU_print_error("Post Texture Unbind");
+}
+
+void GPU_texture_free(GPUTexture *tex)
+{
+ tex->refcount--;
+
+ if (tex->refcount < 0)
+ fprintf(stderr, "GPUTexture: negative refcount\n");
+
+ if (tex->refcount == 0) {
+ if (tex->fb)
+ GPU_framebuffer_texture_detach(tex->fb, tex);
+ if (tex->bindcode && !tex->fromblender)
+ glDeleteTextures(1, &tex->bindcode);
+
+ MEM_freeN(tex);
+ }
+}
+
+void GPU_texture_ref(GPUTexture *tex)
+{
+ tex->refcount++;
+}
+
+int GPU_texture_target(GPUTexture *tex)
+{
+ return tex->target;
+}
+
+int GPU_texture_opengl_width(GPUTexture *tex)
+{
+ return tex->w;
+}
+
+int GPU_texture_opengl_height(GPUTexture *tex)
+{
+ return tex->h;
+}
+
+GPUFrameBuffer *GPU_texture_framebuffer(GPUTexture *tex)
+{
+ return tex->fb;
+}
+
+/* GPUFrameBuffer */
+
+struct GPUFrameBuffer {
+ GLuint object;
+ GPUTexture *colortex;
+ GPUTexture *depthtex;
+};
+
+GPUFrameBuffer *GPU_framebuffer_create()
+{
+ GPUFrameBuffer *fb;
+
+ if (!GLEW_EXT_framebuffer_object)
+ return NULL;
+
+ fb= MEM_callocN(sizeof(GPUFrameBuffer), "GPUFrameBuffer");
+ glGenFramebuffersEXT(1, &fb->object);
+
+ if (!fb->object) {
+ fprintf(stderr, "GPUFFrameBuffer: framebuffer gen failed. %d\n",
+ (int)glGetError());
+ GPU_framebuffer_free(fb);
+ return NULL;
+ }
+
+ return fb;
+}
+
+int GPU_framebuffer_texture_attach(GPUFrameBuffer *fb, GPUTexture *tex)
+{
+ GLenum status;
+ GLenum attachment;
+
+ if(tex->depth)
+ attachment = GL_DEPTH_ATTACHMENT_EXT;
+ else
+ attachment = GL_COLOR_ATTACHMENT0_EXT;
+
+ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb->object);
+ GG.currentfb = fb->object;
+
+ glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, attachment,
+ tex->target, tex->bindcode, 0);
+
+ if(tex->depth) {
+ glDrawBuffer(GL_NONE);
+ glReadBuffer(GL_NONE);
+ }
+ else {
+ glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
+ glReadBuffer(GL_NONE);
+ }
+
+ status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
+
+ if (status != GL_FRAMEBUFFER_COMPLETE_EXT) {
+ GPU_framebuffer_restore();
+ GPU_print_framebuffer_error(status);
+ return 0;
+ }
+
+ if(tex->depth)
+ fb->depthtex = tex;
+ else
+ fb->colortex = tex;
+
+ tex->fb= fb;
+
+ return 1;
+}
+
+void GPU_framebuffer_texture_detach(GPUFrameBuffer *fb, GPUTexture *tex)
+{
+ GLenum attachment;
+
+ if(!tex->fb)
+ return;
+
+ if(GG.currentfb != tex->fb->object) {
+ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, tex->fb->object);
+ GG.currentfb = tex->fb->object;
+ }
+
+ if(tex->depth) {
+ fb->depthtex = NULL;
+ attachment = GL_DEPTH_ATTACHMENT_EXT;
+ }
+ else {
+ fb->colortex = NULL;
+ attachment = GL_COLOR_ATTACHMENT0_EXT;
+ }
+
+ glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, attachment,
+ tex->target, 0, 0);
+
+ tex->fb = NULL;
+}
+
+void GPU_framebuffer_texture_bind(GPUFrameBuffer *fb, GPUTexture *tex)
+{
+ /* push attributes */
+ glPushAttrib(GL_ENABLE_BIT);
+ glPushAttrib(GL_VIEWPORT_BIT);
+ glDisable(GL_SCISSOR_TEST);
+
+ /* bind framebuffer */
+ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, tex->fb->object);
+
+ /* push matrices and set default viewport and matrix */
+ glViewport(0, 0, tex->w, tex->h);
+ GG.currentfb = tex->fb->object;
+
+ glMatrixMode(GL_PROJECTION);
+ glPushMatrix();
+ glLoadIdentity();
+ glMatrixMode(GL_MODELVIEW);
+ glPushMatrix();
+ glLoadIdentity();
+}
+
+void GPU_framebuffer_texture_unbind(GPUFrameBuffer *fb, GPUTexture *tex)
+{
+ /* restore matrix */
+ glMatrixMode(GL_PROJECTION);
+ glPopMatrix();
+ glMatrixMode(GL_MODELVIEW);
+ glPopMatrix();
+
+ /* restore attributes */
+ glPopAttrib();
+ glPopAttrib();
+ glEnable(GL_SCISSOR_TEST);
+}
+
+void GPU_framebuffer_free(GPUFrameBuffer *fb)
+{
+ if(fb->depthtex)
+ GPU_framebuffer_texture_detach(fb, fb->depthtex);
+ if(fb->colortex)
+ GPU_framebuffer_texture_detach(fb, fb->colortex);
+
+ if(fb->object) {
+ glDeleteFramebuffersEXT(1, &fb->object);
+
+ if (GG.currentfb == fb->object) {
+ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
+ GG.currentfb = 0;
+ }
+ }
+
+ MEM_freeN(fb);
+}
+
+void GPU_framebuffer_restore()
+{
+ if (GG.currentfb != 0) {
+ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
+ GG.currentfb = 0;
+ }
+}
+
+/* GPUShader */
+
+struct GPUShader {
+ GLhandleARB object; /* handle for full shader */
+ GLhandleARB vertex; /* handle for vertex shader */
+ GLhandleARB fragment; /* handle for fragment shader */
+ GLhandleARB lib; /* handle for libment shader */
+ int totattrib; /* total number of attributes */
+};
+
+static void shader_print_errors(char *task, char *log, const char *code)
+{
+ const char *c, *pos, *end = code + strlen(code);
+ int line = 1;
+
+ fprintf(stderr, "GPUShader: %s error:\n", task);
+
+ if(G.f & G_DEBUG) {
+ c = code;
+ while ((c < end) && (pos = strchr(c, '\n'))) {
+ fprintf(stderr, "%2d ", line);
+ fwrite(c, (pos+1)-c, 1, stderr);
+ c = pos+1;
+ line++;
+ }
+
+ fprintf(stderr, "%s", c);
+ }
+
+ fprintf(stderr, "%s\n", log);
+}
+
+GPUShader *GPU_shader_create(const char *vertexcode, const char *fragcode, /*GPUShader *lib,*/ const char *libcode)
+{
+ GLint status;
+ GLcharARB log[5000];
+ const char *fragsource[2];
+ GLsizei length = 0;
+ GLint count;
+ GPUShader *shader;
+
+ if (!GLEW_ARB_vertex_shader || !GLEW_ARB_fragment_shader)
+ return NULL;
+
+ shader = MEM_callocN(sizeof(GPUShader), "GPUShader");
+
+ if(vertexcode)
+ shader->vertex = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
+ if(fragcode)
+ shader->fragment = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
+ shader->object = glCreateProgramObjectARB();
+
+ if (!shader->object ||
+ (vertexcode && !shader->vertex) ||
+ (fragcode && !shader->fragment)) {
+ fprintf(stderr, "GPUShader, object creation failed.\n");
+ GPU_shader_free(shader);
+ return NULL;
+ }
+
+ if(vertexcode) {
+ glAttachObjectARB(shader->object, shader->vertex);
+ glShaderSourceARB(shader->vertex, 1, (const char**)&vertexcode, NULL);
+
+ glCompileShaderARB(shader->vertex);
+ glGetObjectParameterivARB(shader->vertex, GL_OBJECT_COMPILE_STATUS_ARB, &status);
+
+ if (!status) {
+ glGetInfoLogARB(shader->vertex, sizeof(log), &length, log);
+ shader_print_errors("compile", log, vertexcode);
+
+ GPU_shader_free(shader);
+ return NULL;
+ }
+ }
+
+ if(fragcode) {
+ count = 0;
+ if(libcode) fragsource[count++] = libcode;
+ if(fragcode) fragsource[count++] = fragcode;
+
+ glAttachObjectARB(shader->object, shader->fragment);
+ glShaderSourceARB(shader->fragment, count, fragsource, NULL);
+
+ glCompileShaderARB(shader->fragment);
+ glGetObjectParameterivARB(shader->fragment, GL_OBJECT_COMPILE_STATUS_ARB, &status);
+
+ if (!status) {
+ glGetInfoLogARB(shader->fragment, sizeof(log), &length, log);
+ shader_print_errors("compile", log, fragcode);
+
+ GPU_shader_free(shader);
+ return NULL;
+ }
+ }
+
+ /*if(lib && lib->lib)
+ glAttachObjectARB(shader->object, lib->lib);*/
+
+ glLinkProgramARB(shader->object);
+ glGetObjectParameterivARB(shader->object, GL_OBJECT_LINK_STATUS_ARB, &status);
+ if (!status) {
+ glGetInfoLogARB(shader->object, sizeof(log), &length, log);
+ shader_print_errors("linking", log, fragcode);
+
+ GPU_shader_free(shader);
+ return NULL;
+ }
+
+ return shader;
+}
+
+#if 0
+GPUShader *GPU_shader_create_lib(const char *code)
+{
+ GLint status;
+ GLcharARB log[5000];
+ GLsizei length = 0;
+ GPUShader *shader;
+
+ if (!GLEW_ARB_vertex_shader || !GLEW_ARB_fragment_shader)
+ return NULL;
+
+ shader = MEM_callocN(sizeof(GPUShader), "GPUShader");
+
+ shader->lib = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
+
+ if (!shader->lib) {
+ fprintf(stderr, "GPUShader, object creation failed.\n");
+ GPU_shader_free(shader);
+ return NULL;
+ }
+
+ glShaderSourceARB(shader->lib, 1, (const char**)&code, NULL);
+
+ glCompileShaderARB(shader->lib);
+ glGetObjectParameterivARB(shader->lib, GL_OBJECT_COMPILE_STATUS_ARB, &status);
+
+ if (!status) {
+ glGetInfoLogARB(shader->lib, sizeof(log), &length, log);
+ shader_print_errors("compile", log, code);
+
+ GPU_shader_free(shader);
+ return NULL;
+ }
+
+ return shader;
+}
+#endif
+
+void GPU_shader_bind(GPUShader *shader)
+{
+ GPU_print_error("Pre Shader Bind");
+ glUseProgramObjectARB(shader->object);
+ GPU_print_error("Post Shader Bind");
+}
+
+void GPU_shader_unbind()
+{
+ GPU_print_error("Pre Shader Unbind");
+ glUseProgramObjectARB(0);
+ GPU_print_error("Post Shader Unbind");
+}
+
+void GPU_shader_free(GPUShader *shader)
+{
+ if (shader->lib)
+ glDeleteObjectARB(shader->lib);
+ if (shader->vertex)
+ glDeleteObjectARB(shader->vertex);
+ if (shader->fragment)
+ glDeleteObjectARB(shader->fragment);
+ if (shader->object)
+ glDeleteObjectARB(shader->object);
+ MEM_freeN(shader);
+}
+
+int GPU_shader_get_uniform(GPUShader *shader, char *name)
+{
+ return glGetUniformLocationARB(shader->object, name);
+}
+
+void GPU_shader_uniform_vector(GPUShader *shader, int location, int length, int arraysize, float *value)
+{
+ if(location == -1)
+ return;
+
+ GPU_print_error("Pre Uniform Vector");
+
+ if (length == 1) glUniform1fvARB(location, arraysize, value);
+ else if (length == 2) glUniform2fvARB(location, arraysize, value);
+ else if (length == 3) glUniform3fvARB(location, arraysize, value);
+ else if (length == 4) glUniform4fvARB(location, arraysize, value);
+ else if (length == 9) glUniformMatrix3fvARB(location, arraysize, 0, value);
+ else if (length == 16) glUniformMatrix4fvARB(location, arraysize, 0, value);
+
+ GPU_print_error("Post Uniform Vector");
+}
+
+void GPU_shader_uniform_texture(GPUShader *shader, int location, GPUTexture *tex)
+{
+ GLenum arbnumber;
+
+ if (tex->number >= GG.maxtextures) {
+ GPU_print_error("Not enough texture slots.");
+ return;
+ }
+
+ if(tex->number == -1)
+ return;
+
+ if(location == -1)
+ return;
+
+ GPU_print_error("Pre Uniform Texture");
+
+ arbnumber = (GLenum)((GLuint)GL_TEXTURE0_ARB + tex->number);
+
+ if (tex->number != 0) glActiveTextureARB(arbnumber);
+ glBindTexture(tex->target, tex->bindcode);
+ glUniform1iARB(location, tex->number);
+ glEnable(tex->target);
+ if (tex->number != 0) glActiveTextureARB(GL_TEXTURE0_ARB);
+
+ GPU_print_error("Post Uniform Texture");
+}
+
+int GPU_shader_get_attribute(GPUShader *shader, char *name)
+{
+ int index;
+
+ GPU_print_error("Pre Get Attribute");
+
+ index = glGetAttribLocationARB(shader->object, name);
+
+ GPU_print_error("Post Get Attribute");
+
+ return index;
+}
+
+#if 0
+/* GPUPixelBuffer */
+
+typedef struct GPUPixelBuffer {
+ GLuint bindcode[2];
+ GLuint current;
+ int datasize;
+ int numbuffers;
+ int halffloat;
+} GPUPixelBuffer;
+
+void GPU_pixelbuffer_free(GPUPixelBuffer *pb)
+{
+ if (pb->bindcode[0])
+ glDeleteBuffersARB(pb->numbuffers, pb->bindcode);
+ MEM_freeN(pb);
+}
+
+GPUPixelBuffer *gpu_pixelbuffer_create(int x, int y, int halffloat, int numbuffers)
+{
+ GPUPixelBuffer *pb;
+
+ if (!GLEW_ARB_multitexture || !GLEW_EXT_pixel_buffer_object)
+ return NULL;
+
+ pb = MEM_callocN(sizeof(GPUPixelBuffer), "GPUPBO");
+ pb->datasize = x*y*4*((halffloat)? 16: 8);
+ pb->numbuffers = numbuffers;
+ pb->halffloat = halffloat;
+
+ glGenBuffersARB(pb->numbuffers, pb->bindcode);
+
+ if (!pb->bindcode[0]) {
+ fprintf(stderr, "GPUPixelBuffer allocation failed\n");
+ GPU_pixelbuffer_free(pb);
+ return NULL;
+ }
+
+ return pb;
+}
+
+void GPU_pixelbuffer_texture(GPUTexture *tex, GPUPixelBuffer *pb)
+{
+ void *pixels;
+ int i;
+
+ glBindTexture(GL_TEXTURE_RECTANGLE_EXT, tex->bindcode);
+
+ for (i = 0; i < pb->numbuffers; i++) {
+ glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT, pb->bindcode[pb->current]);
+ glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_EXT, pb->datasize, NULL,
+ GL_STREAM_DRAW_ARB);
+
+ pixels = glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT, GL_WRITE_ONLY);
+ /*memcpy(pixels, _oImage.data(), pb->datasize);*/
+
+ if (!glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT)) {
+ fprintf(stderr, "Could not unmap opengl PBO\n");
+ break;
+ }
+ }
+
+ glBindTexture(GL_TEXTURE_RECTANGLE_EXT, 0);
+}
+
+static int pixelbuffer_map_into_gpu(GLuint bindcode)
+{
+ void *pixels;
+
+ glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT, bindcode);
+ pixels = glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT, GL_WRITE_ONLY);
+
+ /* do stuff in pixels */
+
+ if (!glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT)) {
+ fprintf(stderr, "Could not unmap opengl PBO\n");
+ return 0;
+ }
+
+ return 1;
+}
+
+static void pixelbuffer_copy_to_texture(GPUTexture *tex, GPUPixelBuffer *pb, GLuint bindcode)
+{
+ GLenum type = (pb->halffloat)? GL_HALF_FLOAT_NV: GL_UNSIGNED_BYTE;
+ glBindTexture(GL_TEXTURE_RECTANGLE_EXT, tex->bindcode);
+ glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT, bindcode);
+
+ glTexSubImage2D(GL_TEXTURE_RECTANGLE_EXT, 0, 0, 0, tex->w, tex->h,
+ GL_RGBA, type, NULL);
+
+ glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT, 0);
+ glBindTexture(GL_TEXTURE_RECTANGLE_EXT, 0);
+}
+
+void GPU_pixelbuffer_async_to_gpu(GPUTexture *tex, GPUPixelBuffer *pb)
+{
+ int newbuffer;
+
+ if (pb->numbuffers == 1) {
+ pixelbuffer_copy_to_texture(tex, pb, pb->bindcode[0]);
+ pixelbuffer_map_into_gpu(pb->bindcode[0]);
+ }
+ else {
+ pb->current = (pb->current+1)%pb->numbuffers;
+ newbuffer = (pb->current+1)%pb->numbuffers;
+
+ pixelbuffer_map_into_gpu(pb->bindcode[newbuffer]);
+ pixelbuffer_copy_to_texture(tex, pb, pb->bindcode[pb->current]);
+ }
+}
+#endif
+
diff --git a/source/blender/gpu/intern/gpu_material.c b/source/blender/gpu/intern/gpu_material.c
new file mode 100644
index 00000000000..46df003cbbc
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_material.c
@@ -0,0 +1,1502 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2006 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Brecht Van Lommel.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include <math.h>
+#include <string.h>
+
+#include "GL/glew.h"
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_image_types.h"
+#include "DNA_lamp_types.h"
+#include "DNA_listBase.h"
+#include "DNA_material_types.h"
+#include "DNA_object_types.h"
+#include "DNA_scene_types.h"
+#include "DNA_texture_types.h"
+#include "DNA_view3d_types.h"
+#include "DNA_world_types.h"
+
+#include "BKE_anim.h"
+#include "BKE_colortools.h"
+#include "BKE_DerivedMesh.h"
+#include "BKE_global.h"
+#include "BKE_main.h"
+#include "BKE_node.h"
+#include "BKE_scene.h"
+#include "BKE_texture.h"
+#include "BKE_utildefines.h"
+
+#include "BLI_arithb.h"
+#include "BLI_blenlib.h"
+
+#include "GPU_extensions.h"
+#include "GPU_material.h"
+
+#include "gpu_codegen.h"
+
+#include <string.h>
+
+/* Structs */
+
+typedef enum DynMatProperty {
+ DYN_LAMP_CO = 1,
+ DYN_LAMP_VEC = 2,
+ DYN_LAMP_IMAT = 4,
+ DYN_LAMP_PERSMAT = 8,
+} DynMatProperty;
+
+struct GPUMaterial {
+ Scene *scene;
+ Material *ma;
+
+ /* for creating the material */
+ ListBase nodes;
+ GPUNodeLink *outlink;
+
+ /* for binding the material */
+ GPUPass *pass;
+ GPUVertexAttribs attribs;
+ int bound;
+ int builtins;
+ int alpha, obcolalpha;
+ int dynproperty;
+
+ /* for passing uniforms */
+ int viewmatloc, invviewmatloc;
+ int obmatloc, invobmatloc;
+ int obcolloc;
+
+ ListBase lamps;
+};
+
+struct GPULamp {
+ Scene *scene;
+ Object *ob;
+ Object *par;
+ Lamp *la;
+
+ int type, mode, lay;
+
+ float dynenergy, dyncol[3];
+ float energy, col[3];
+
+ float co[3], vec[3];
+ float dynco[3], dynvec[3];
+ float obmat[4][4];
+ float imat[4][4];
+ float dynimat[4][4];
+
+ float spotsi, spotbl, k;
+ float dist, att1, att2;
+
+ float bias, d, clipend;
+ int size;
+
+ int falloff_type;
+ struct CurveMapping *curfalloff;
+
+ float winmat[4][4];
+ float viewmat[4][4];
+ float persmat[4][4];
+ float dynpersmat[4][4];
+
+ GPUFrameBuffer *fb;
+ GPUTexture *tex;
+
+ ListBase materials;
+};
+
+/* Functions */
+
+static GPUMaterial *GPU_material_construct_begin(Material *ma)
+{
+ GPUMaterial *material = MEM_callocN(sizeof(GPUMaterial), "GPUMaterial");
+
+ material->ma= ma;
+
+ return material;
+}
+
+static void gpu_material_set_attrib_id(GPUMaterial *material)
+{
+ GPUVertexAttribs *attribs;
+ GPUShader *shader;
+ GPUPass *pass;
+ char name[32];
+ int a, b;
+
+ attribs= &material->attribs;
+ pass= material->pass;
+ if(!pass) {
+ attribs->totlayer = 0;
+ return;
+ }
+
+ shader= GPU_pass_shader(pass);
+ if(!shader) {
+ attribs->totlayer = 0;
+ return;
+ }
+
+ /* convert from attribute number to the actual id assigned by opengl,
+ * in case the attrib does not get a valid index back, it was probably
+ * removed by the glsl compiler by dead code elimination */
+
+ for(a=0, b=0; a<attribs->totlayer; a++) {
+ sprintf(name, "att%d", attribs->layer[a].glindex);
+ attribs->layer[a].glindex = GPU_shader_get_attribute(shader, name);
+
+ if(attribs->layer[a].glindex >= 0) {
+ attribs->layer[b] = attribs->layer[a];
+ b++;
+ }
+ }
+
+ attribs->totlayer = b;
+}
+
+static int GPU_material_construct_end(GPUMaterial *material)
+{
+ if (material->outlink) {
+ GPUNodeLink *outlink;
+ GPUShader *shader;
+
+ outlink = material->outlink;
+ material->pass = GPU_generate_pass(&material->nodes, outlink,
+ &material->attribs, &material->builtins, material->ma->id.name);
+
+ if(!material->pass)
+ return 0;
+
+ gpu_material_set_attrib_id(material);
+
+ shader = GPU_pass_shader(material->pass);
+
+ if(material->builtins & GPU_VIEW_MATRIX)
+ material->viewmatloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_VIEW_MATRIX));
+ if(material->builtins & GPU_INVERSE_VIEW_MATRIX)
+ material->invviewmatloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_INVERSE_VIEW_MATRIX));
+ if(material->builtins & GPU_OBJECT_MATRIX)
+ material->obmatloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_OBJECT_MATRIX));
+ if(material->builtins & GPU_INVERSE_OBJECT_MATRIX)
+ material->invobmatloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_INVERSE_OBJECT_MATRIX));
+ if(material->builtins & GPU_OBCOLOR)
+ material->obcolloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_OBCOLOR));
+
+ return 1;
+ }
+
+ return 0;
+}
+
+void GPU_material_free(Material *ma)
+{
+ LinkData *link;
+ LinkData *nlink, *mlink, *next;
+
+ for(link=ma->gpumaterial.first; link; link=link->next) {
+ GPUMaterial *material = link->data;
+
+ if(material->pass)
+ GPU_pass_free(material->pass);
+
+ for(nlink=material->lamps.first; nlink; nlink=nlink->next) {
+ GPULamp *lamp = nlink->data;
+
+ for(mlink=lamp->materials.first; mlink; mlink=next) {
+ next = mlink->next;
+ if(mlink->data == ma)
+ BLI_freelinkN(&lamp->materials, mlink);
+ }
+ }
+
+ BLI_freelistN(&material->lamps);
+
+ MEM_freeN(material);
+ }
+
+ BLI_freelistN(&ma->gpumaterial);
+}
+
+void GPU_material_bind(GPUMaterial *material, int oblay, int viewlay, double time)
+{
+ if(material->pass) {
+ LinkData *nlink;
+ GPULamp *lamp;
+
+ /* handle layer lamps */
+ for(nlink=material->lamps.first; nlink; nlink=nlink->next) {
+ lamp= nlink->data;
+
+ if((lamp->lay & viewlay) && (!(lamp->mode & LA_LAYER) || (lamp->lay & oblay))) {
+ lamp->dynenergy = lamp->energy;
+ VECCOPY(lamp->dyncol, lamp->col);
+ }
+ else {
+ lamp->dynenergy = 0.0f;
+ lamp->dyncol[0]= lamp->dyncol[1]= lamp->dyncol[2] = 0.0f;
+ }
+ }
+
+ GPU_pass_bind(material->pass, time);
+ material->bound = 1;
+ }
+}
+
+void GPU_material_bind_uniforms(GPUMaterial *material, float obmat[][4], float viewmat[][4], float viewinv[][4], float obcol[4])
+{
+ if(material->pass) {
+ GPUShader *shader = GPU_pass_shader(material->pass);
+ LinkData *nlink;
+ GPULamp *lamp;
+ float invmat[4][4], col[4];
+
+ /* handle builtins */
+ if(material->builtins & GPU_VIEW_MATRIX) {
+ GPU_shader_uniform_vector(shader, material->viewmatloc, 16, 1, (float*)viewmat);
+ }
+ if(material->builtins & GPU_INVERSE_VIEW_MATRIX) {
+ GPU_shader_uniform_vector(shader, material->invviewmatloc, 16, 1, (float*)viewinv);
+ }
+ if(material->builtins & GPU_OBJECT_MATRIX) {
+ GPU_shader_uniform_vector(shader, material->obmatloc, 16, 1, (float*)obmat);
+ }
+ if(material->builtins & GPU_INVERSE_OBJECT_MATRIX) {
+ Mat4Invert(invmat, obmat);
+ GPU_shader_uniform_vector(shader, material->invobmatloc, 16, 1, (float*)invmat);
+ }
+ if(material->builtins & GPU_OBCOLOR) {
+ QUATCOPY(col, obcol);
+ CLAMP(col[3], 0.0f, 1.0f);
+ GPU_shader_uniform_vector(shader, material->obcolloc, 4, 1, col);
+ }
+
+ /* update lamps */
+ for(nlink=material->lamps.first; nlink; nlink=nlink->next) {
+ lamp= nlink->data;
+
+ if(material->dynproperty & DYN_LAMP_VEC) {
+ VECCOPY(lamp->dynvec, lamp->vec);
+ Normalize(lamp->dynvec);
+ VecMulf(lamp->dynvec, -1.0f);
+ Mat4Mul3Vecfl(viewmat, lamp->dynvec);
+ }
+
+ if(material->dynproperty & DYN_LAMP_CO) {
+ VECCOPY(lamp->dynco, lamp->co);
+ Mat4MulVecfl(viewmat, lamp->dynco);
+ }
+
+ if(material->dynproperty & DYN_LAMP_IMAT)
+ Mat4MulMat4(lamp->dynimat, viewinv, lamp->imat);
+ if(material->dynproperty & DYN_LAMP_PERSMAT)
+ Mat4MulMat4(lamp->dynpersmat, viewinv, lamp->persmat);
+ }
+
+ GPU_pass_update_uniforms(material->pass);
+ }
+}
+
+void GPU_material_unbind(GPUMaterial *material)
+{
+ if (material->pass) {
+ material->bound = 0;
+ GPU_pass_unbind(material->pass);
+ }
+}
+
+int GPU_material_bound(GPUMaterial *material)
+{
+ return material->bound;
+}
+
+void GPU_material_vertex_attributes(GPUMaterial *material, GPUVertexAttribs *attribs)
+{
+ *attribs = material->attribs;
+}
+
+void GPU_material_output_link(GPUMaterial *material, GPUNodeLink *link)
+{
+ if(!material->outlink)
+ material->outlink= link;
+}
+
+void GPU_material_enable_alpha(GPUMaterial *material)
+{
+ material->alpha= 1;
+}
+
+GPUBlendMode GPU_material_blend_mode(GPUMaterial *material, float obcol[3])
+{
+ if(material->alpha || (material->obcolalpha && obcol[3] < 1.0f))
+ return GPU_BLEND_ALPHA;
+ else
+ return GPU_BLEND_SOLID;
+}
+
+void gpu_material_add_node(GPUMaterial *material, GPUNode *node)
+{
+ BLI_addtail(&material->nodes, node);
+}
+
+/* Code generation */
+
+static GPUNodeLink *lamp_get_visibility(GPUMaterial *mat, GPULamp *lamp, GPUNodeLink **lv, GPUNodeLink **dist)
+{
+ GPUNodeLink *visifac, *inpr;
+
+ /* from get_lamp_visibility */
+ if(lamp->type==LA_SUN || lamp->type==LA_HEMI) {
+ mat->dynproperty |= DYN_LAMP_VEC;
+ GPU_link(mat, "lamp_visibility_sun_hemi", GPU_dynamic_uniform(lamp->dynvec), lv, dist, &visifac);
+ return visifac;
+ }
+ else {
+ mat->dynproperty |= DYN_LAMP_CO;
+ GPU_link(mat, "lamp_visibility_other", GPU_builtin(GPU_VIEW_POSITION), GPU_dynamic_uniform(lamp->dynco), lv, dist, &visifac);
+
+ if(lamp->type==LA_AREA)
+ return visifac;
+
+ switch(lamp->falloff_type)
+ {
+ case LA_FALLOFF_CONSTANT:
+ break;
+ case LA_FALLOFF_INVLINEAR:
+ GPU_link(mat, "lamp_falloff_invlinear", GPU_uniform(&lamp->dist), *dist, &visifac);
+ break;
+ case LA_FALLOFF_INVSQUARE:
+ GPU_link(mat, "lamp_falloff_invsquare", GPU_uniform(&lamp->dist), *dist, &visifac);
+ break;
+ case LA_FALLOFF_SLIDERS:
+ GPU_link(mat, "lamp_falloff_sliders", GPU_uniform(&lamp->dist), GPU_uniform(&lamp->att1), GPU_uniform(&lamp->att2), *dist, &visifac);
+ break;
+ case LA_FALLOFF_CURVE:
+ {
+ float *array;
+ int size;
+
+ curvemapping_table_RGBA(lamp->curfalloff, &array, &size);
+ GPU_link(mat, "lamp_falloff_curve", GPU_uniform(&lamp->dist), GPU_texture(size, array), *dist, &visifac);
+ }
+ break;
+ }
+
+ if(lamp->mode & LA_SPHERE)
+ GPU_link(mat, "lamp_visibility_sphere", GPU_uniform(&lamp->dist), *dist, visifac, &visifac);
+
+ if(lamp->type == LA_SPOT) {
+ if(lamp->mode & LA_SQUARE) {
+ mat->dynproperty |= DYN_LAMP_VEC|DYN_LAMP_IMAT;
+ GPU_link(mat, "lamp_visibility_spot_square", GPU_dynamic_uniform(lamp->dynvec), GPU_dynamic_uniform((float*)lamp->dynimat), *lv, &inpr);
+ }
+ else {
+ mat->dynproperty |= DYN_LAMP_VEC;
+ GPU_link(mat, "lamp_visibility_spot_circle", GPU_dynamic_uniform(lamp->dynvec), *lv, &inpr);
+ }
+
+ GPU_link(mat, "lamp_visibility_spot", GPU_uniform(&lamp->spotsi), GPU_uniform(&lamp->spotbl), inpr, visifac, &visifac);
+ }
+
+ GPU_link(mat, "lamp_visibility_clamp", visifac, &visifac);
+
+ return visifac;
+ }
+}
+
+#if 0
+static void area_lamp_vectors(LampRen *lar)
+{
+ float xsize= 0.5*lar->area_size, ysize= 0.5*lar->area_sizey, multifac;
+
+ /* make it smaller, so area light can be multisampled */
+ multifac= 1.0f/sqrt((float)lar->ray_totsamp);
+ xsize *= multifac;
+ ysize *= multifac;
+
+ /* corner vectors */
+ lar->area[0][0]= lar->co[0] - xsize*lar->mat[0][0] - ysize*lar->mat[1][0];
+ lar->area[0][1]= lar->co[1] - xsize*lar->mat[0][1] - ysize*lar->mat[1][1];
+ lar->area[0][2]= lar->co[2] - xsize*lar->mat[0][2] - ysize*lar->mat[1][2];
+
+ /* corner vectors */
+ lar->area[1][0]= lar->co[0] - xsize*lar->mat[0][0] + ysize*lar->mat[1][0];
+ lar->area[1][1]= lar->co[1] - xsize*lar->mat[0][1] + ysize*lar->mat[1][1];
+ lar->area[1][2]= lar->co[2] - xsize*lar->mat[0][2] + ysize*lar->mat[1][2];
+
+ /* corner vectors */
+ lar->area[2][0]= lar->co[0] + xsize*lar->mat[0][0] + ysize*lar->mat[1][0];
+ lar->area[2][1]= lar->co[1] + xsize*lar->mat[0][1] + ysize*lar->mat[1][1];
+ lar->area[2][2]= lar->co[2] + xsize*lar->mat[0][2] + ysize*lar->mat[1][2];
+
+ /* corner vectors */
+ lar->area[3][0]= lar->co[0] + xsize*lar->mat[0][0] - ysize*lar->mat[1][0];
+ lar->area[3][1]= lar->co[1] + xsize*lar->mat[0][1] - ysize*lar->mat[1][1];
+ lar->area[3][2]= lar->co[2] + xsize*lar->mat[0][2] - ysize*lar->mat[1][2];
+ /* only for correction button size, matrix size works on energy */
+ lar->areasize= lar->dist*lar->dist/(4.0*xsize*ysize);
+}
+#endif
+
+static void ramp_blend(GPUMaterial *mat, GPUNodeLink *fac, GPUNodeLink *col1, GPUNodeLink *col2, int type, GPUNodeLink **outcol)
+{
+ static char *names[] = {"mix_blend", "mix_add", "mix_mult", "mix_sub",
+ "mix_screen", "mix_div", "mix_diff", "mix_dark", "mix_light",
+ "mix_overlay", "mix_dodge", "mix_burn", "mix_hue", "mix_sat",
+ "mix_val", "mix_color"};
+
+ GPU_link(mat, names[type], fac, col1, col2, outcol);
+}
+
+static void do_colorband_blend(GPUMaterial *mat, ColorBand *coba, GPUNodeLink *fac, float rampfac, int type, GPUNodeLink *incol, GPUNodeLink **outcol)
+{
+ GPUNodeLink *tmp, *alpha, *col;
+ float *array;
+ int size;
+
+ /* do colorband */
+ colorband_table_RGBA(coba, &array, &size);
+ GPU_link(mat, "valtorgb", fac, GPU_texture(size, array), &col, &tmp);
+
+ /* use alpha in fac */
+ GPU_link(mat, "mtex_alpha_from_col", col, &alpha);
+ GPU_link(mat, "math_multiply", alpha, GPU_uniform(&rampfac), &fac);
+
+ /* blending method */
+ ramp_blend(mat, fac, incol, col, type, outcol);
+}
+
+static void ramp_diffuse_result(GPUShadeInput *shi, GPUNodeLink **diff)
+{
+ Material *ma= shi->mat;
+ GPUMaterial *mat= shi->gpumat;
+ GPUNodeLink *fac;
+
+ if(!(G.fileflags & G_FILE_GLSL_NO_RAMPS)) {
+ if(ma->ramp_col) {
+ if(ma->rampin_col==MA_RAMP_IN_RESULT) {
+ GPU_link(mat, "ramp_rgbtobw", *diff, &fac);
+
+ /* colorband + blend */
+ do_colorband_blend(mat, ma->ramp_col, fac, ma->rampfac_col, ma->rampblend_col, *diff, diff);
+ }
+ }
+ }
+}
+
+static void add_to_diffuse(GPUMaterial *mat, Material *ma, GPUShadeInput *shi, GPUNodeLink *is, GPUNodeLink *rgb, GPUNodeLink **diff)
+{
+ GPUNodeLink *fac, *tmp, *addcol;
+
+ if(!(G.fileflags & G_FILE_GLSL_NO_RAMPS) &&
+ ma->ramp_col && (ma->mode & MA_RAMP_COL)) {
+ /* MA_RAMP_IN_RESULT is exceptional */
+ if(ma->rampin_col==MA_RAMP_IN_RESULT) {
+ addcol = shi->rgb;
+ }
+ else {
+ /* input */
+ switch(ma->rampin_col) {
+ case MA_RAMP_IN_ENERGY:
+ GPU_link(mat, "ramp_rgbtobw", rgb, &fac);
+ break;
+ case MA_RAMP_IN_SHADER:
+ fac= is;
+ break;
+ case MA_RAMP_IN_NOR:
+ GPU_link(mat, "vec_math_dot", shi->view, shi->vn, &tmp, &fac);
+ break;
+ default:
+ GPU_link(mat, "set_value_zero", &fac);
+ break;
+ }
+
+ /* colorband + blend */
+ do_colorband_blend(mat, ma->ramp_col, fac, ma->rampfac_col, ma->rampblend_col, shi->rgb, &addcol);
+ }
+ }
+ else
+ addcol = shi->rgb;
+
+ /* output to */
+ GPU_link(mat, "shade_madd", *diff, rgb, addcol, diff);
+}
+
+static void ramp_spec_result(GPUShadeInput *shi, GPUNodeLink **spec)
+{
+ Material *ma= shi->mat;
+ GPUMaterial *mat= shi->gpumat;
+ GPUNodeLink *fac;
+
+ if(!(G.fileflags & G_FILE_GLSL_NO_RAMPS) &&
+ ma->ramp_spec && ma->rampin_spec==MA_RAMP_IN_RESULT) {
+ GPU_link(mat, "ramp_rgbtobw", *spec, &fac);
+
+ /* colorband + blend */
+ do_colorband_blend(mat, ma->ramp_spec, fac, ma->rampfac_spec, ma->rampblend_spec, *spec, spec);
+ }
+}
+
+static void do_specular_ramp(GPUShadeInput *shi, GPUNodeLink *is, GPUNodeLink *t, GPUNodeLink **spec)
+{
+ Material *ma= shi->mat;
+ GPUMaterial *mat= shi->gpumat;
+ GPUNodeLink *fac, *tmp;
+
+ *spec = shi->specrgb;
+
+ /* MA_RAMP_IN_RESULT is exception */
+ if(ma->ramp_spec && (ma->rampin_spec!=MA_RAMP_IN_RESULT)) {
+
+ /* input */
+ switch(ma->rampin_spec) {
+ case MA_RAMP_IN_ENERGY:
+ fac = t;
+ break;
+ case MA_RAMP_IN_SHADER:
+ fac = is;
+ break;
+ case MA_RAMP_IN_NOR:
+ GPU_link(mat, "vec_math_dot", shi->view, shi->vn, &tmp, &fac);
+ break;
+ default:
+ GPU_link(mat, "set_value_zero", &fac);
+ break;
+ }
+
+ /* colorband + blend */
+ do_colorband_blend(mat, ma->ramp_spec, fac, ma->rampfac_spec, ma->rampblend_spec, *spec, spec);
+ }
+}
+
+void add_user_list(ListBase *list, void *data)
+{
+ LinkData *link = MEM_callocN(sizeof(LinkData), "GPULinkData");
+ link->data = data;
+ BLI_addtail(list, link);
+}
+
+static void shade_one_light(GPUShadeInput *shi, GPUShadeResult *shr, GPULamp *lamp)
+{
+ Material *ma= shi->mat;
+ GPUMaterial *mat= shi->gpumat;
+ GPUNodeLink *lv, *dist, *visifac, *is, *inp, *i, *vn, *view;
+ GPUNodeLink *outcol, *specfac, *t, *shadfac;
+ float one = 1.0f;
+
+ if((lamp->mode & LA_ONLYSHADOW) && !(ma->mode & MA_SHADOW))
+ return;
+
+ vn= shi->vn;
+ view= shi->view;
+
+ visifac= lamp_get_visibility(mat, lamp, &lv, &dist);
+
+ /*if(ma->mode & MA_TANGENT_V)
+ GPU_link(mat, "shade_tangent_v", lv, GPU_attribute(CD_TANGENT, ""), &vn);*/
+
+ GPU_link(mat, "shade_inp", vn, lv, &inp);
+
+ if(lamp->mode & LA_NO_DIFF) {
+ GPU_link(mat, "shade_is_no_diffuse", &is);
+ }
+ else if(lamp->type == LA_HEMI) {
+ GPU_link(mat, "shade_is_hemi", inp, &is);
+ }
+ else {
+ if(lamp->type == LA_AREA) {
+ float area[4][4], areasize;
+
+ memset(&area, 0, sizeof(area));
+ memset(&areasize, 0, sizeof(areasize));
+ mat->dynproperty |= DYN_LAMP_VEC|DYN_LAMP_CO;
+ GPU_link(mat, "shade_inp_area", GPU_builtin(GPU_VIEW_POSITION), GPU_dynamic_uniform(lamp->dynco), GPU_dynamic_uniform(lamp->dynvec), vn, GPU_uniform((float*)area),
+ GPU_uniform(&areasize), GPU_uniform(&lamp->k), &inp);
+ }
+
+ is= inp; /* Lambert */
+
+ if(!(G.fileflags & G_FILE_GLSL_NO_SHADERS)) {
+ if(ma->diff_shader==MA_DIFF_ORENNAYAR)
+ GPU_link(mat, "shade_diffuse_oren_nayer", inp, vn, lv, view, GPU_uniform(&ma->roughness), &is);
+ else if(ma->diff_shader==MA_DIFF_TOON)
+ GPU_link(mat, "shade_diffuse_toon", vn, lv, view, GPU_uniform(&ma->param[0]), GPU_uniform(&ma->param[1]), &is);
+ else if(ma->diff_shader==MA_DIFF_MINNAERT)
+ GPU_link(mat, "shade_diffuse_minnaert", inp, vn, view, GPU_uniform(&ma->darkness), &is);
+ else if(ma->diff_shader==MA_DIFF_FRESNEL)
+ GPU_link(mat, "shade_diffuse_fresnel", vn, lv, view, GPU_uniform(&ma->param[0]), GPU_uniform(&ma->param[1]), &is);
+ }
+ }
+
+ if(!(G.fileflags & G_FILE_GLSL_NO_SHADERS))
+ if(ma->shade_flag & MA_CUBIC)
+ GPU_link(mat, "shade_cubic", is, &is);
+
+ i = is;
+ GPU_link(mat, "shade_visifac", i, visifac, shi->refl, &i);
+
+ vn = shi->vn;
+ /*if(ma->mode & MA_TANGENT_VN)
+ GPU_link(mat, "shade_tangent_v_spec", GPU_attribute(CD_TANGENT, ""), &vn);*/
+
+ /* this replaces if(i > 0.0) conditional until that is supported */
+ // done in shade_visifac now, GPU_link(mat, "mtex_value_clamp_positive", i, &i);
+
+ if((ma->mode & MA_SHADOW) && GPU_lamp_has_shadow_buffer(lamp)) {
+ if(!(G.fileflags & G_FILE_GLSL_NO_SHADOWS)) {
+ mat->dynproperty |= DYN_LAMP_PERSMAT;
+
+ GPU_link(mat, "test_shadowbuf",
+ GPU_builtin(GPU_VIEW_POSITION),
+ GPU_dynamic_texture(lamp->tex),
+ GPU_dynamic_uniform((float*)lamp->dynpersmat),
+ GPU_uniform(&lamp->bias), inp, &shadfac);
+
+ if(lamp->mode & LA_ONLYSHADOW) {
+ GPU_link(mat, "shade_only_shadow", i, shadfac,
+ GPU_dynamic_uniform(&lamp->dynenergy), &shadfac);
+
+ if(!(lamp->mode & LA_NO_DIFF))
+ GPU_link(mat, "shade_only_shadow_diffuse", shadfac, shi->rgb,
+ shr->diff, &shr->diff);
+
+ if(!(lamp->mode & LA_NO_SPEC))
+ GPU_link(mat, "shade_only_shadow_specular", shadfac, shi->specrgb,
+ shr->spec, &shr->spec);
+
+ add_user_list(&mat->lamps, lamp);
+ add_user_list(&lamp->materials, shi->gpumat->ma);
+ return;
+ }
+
+ GPU_link(mat, "math_multiply", i, shadfac, &i);
+ }
+ }
+ else if((G.fileflags & G_FILE_GLSL_NO_SHADOWS) && (lamp->mode & LA_ONLYSHADOW)) {
+ add_user_list(&mat->lamps, lamp);
+ add_user_list(&lamp->materials, shi->gpumat->ma);
+ return;
+ }
+ else
+ GPU_link(mat, "set_value", GPU_uniform(&one), &shadfac);
+
+ if(GPU_link_changed(shi->refl) || ma->ref != 0.0f) {
+ if(!(lamp->mode & LA_NO_DIFF)) {
+ GPUNodeLink *rgb;
+ GPU_link(mat, "shade_mul_value", i, GPU_dynamic_uniform(lamp->dyncol), &rgb);
+ add_to_diffuse(mat, ma, shi, is, rgb, &shr->diff);
+ }
+ }
+
+ if(G.fileflags & G_FILE_GLSL_NO_SHADERS);
+ else if(!(lamp->mode & LA_NO_SPEC) && !(lamp->mode & LA_ONLYSHADOW) &&
+ (GPU_link_changed(shi->spec) || ma->spec != 0.0f)) {
+ if(lamp->type == LA_HEMI) {
+ GPU_link(mat, "shade_hemi_spec", vn, lv, view, GPU_uniform(&ma->spec), shi->har, visifac, &t);
+ GPU_link(mat, "shade_add_spec", t, GPU_dynamic_uniform(lamp->dyncol), shi->specrgb, &outcol);
+ GPU_link(mat, "shade_add", shr->spec, outcol, &shr->spec);
+ }
+ else {
+ if(ma->spec_shader==MA_SPEC_PHONG)
+ GPU_link(mat, "shade_phong_spec", vn, lv, view, shi->har, &specfac);
+ else if(ma->spec_shader==MA_SPEC_COOKTORR)
+ GPU_link(mat, "shade_cooktorr_spec", vn, lv, view, shi->har, &specfac);
+ else if(ma->spec_shader==MA_SPEC_BLINN)
+ GPU_link(mat, "shade_blinn_spec", vn, lv, view, GPU_uniform(&ma->refrac), shi->har, &specfac);
+ else if(ma->spec_shader==MA_SPEC_WARDISO)
+ GPU_link(mat, "shade_wardiso_spec", vn, lv, view, GPU_uniform(&ma->rms), &specfac);
+ else
+ GPU_link(mat, "shade_toon_spec", vn, lv, view, GPU_uniform(&ma->param[2]), GPU_uniform(&ma->param[3]), &specfac);
+
+ if(lamp->type==LA_AREA)
+ GPU_link(mat, "shade_spec_area_inp", specfac, inp, &specfac);
+
+ GPU_link(mat, "shade_spec_t", shadfac, shi->spec, visifac, specfac, &t);
+
+ if(ma->mode & MA_RAMP_SPEC) {
+ GPUNodeLink *spec;
+ do_specular_ramp(shi, specfac, t, &spec);
+ GPU_link(mat, "shade_add_spec", t, GPU_dynamic_uniform(lamp->dyncol), spec, &outcol);
+ GPU_link(mat, "shade_add", shr->spec, outcol, &shr->spec);
+ }
+ else {
+ GPU_link(mat, "shade_add_spec", t, GPU_dynamic_uniform(lamp->dyncol), shi->specrgb, &outcol);
+ GPU_link(mat, "shade_add", shr->spec, outcol, &shr->spec);
+ }
+ }
+ }
+
+ add_user_list(&mat->lamps, lamp);
+ add_user_list(&lamp->materials, shi->gpumat->ma);
+}
+
+static void material_lights(GPUShadeInput *shi, GPUShadeResult *shr)
+{
+ Base *base;
+ Object *ob;
+ Scene *sce;
+ GPULamp *lamp;
+
+ for(SETLOOPER(shi->gpumat->scene, base)) {
+ ob= base->object;
+
+ if(ob->type==OB_LAMP) {
+ lamp = GPU_lamp_from_blender(shi->gpumat->scene, ob, NULL);
+ if(lamp)
+ shade_one_light(shi, shr, lamp);
+ }
+
+ if (ob->transflag & OB_DUPLI) {
+ DupliObject *dob;
+ ListBase *lb = object_duplilist(shi->gpumat->scene, ob);
+
+ for(dob=lb->first; dob; dob=dob->next) {
+ Object *ob = dob->ob;
+
+ if(ob->type==OB_LAMP) {
+ Mat4CpyMat4(ob->obmat, dob->mat);
+
+ lamp = GPU_lamp_from_blender(shi->gpumat->scene, ob, base->object);
+ if(lamp)
+ shade_one_light(shi, shr, lamp);
+ }
+ }
+
+ free_object_duplilist(lb);
+ }
+ }
+}
+
+static void texture_rgb_blend(GPUMaterial *mat, GPUNodeLink *tex, GPUNodeLink *out, GPUNodeLink *fact, GPUNodeLink *facg, int blendtype, GPUNodeLink **in)
+{
+ switch(blendtype) {
+ case MTEX_BLEND:
+ GPU_link(mat, "mtex_rgb_blend", out, tex, fact, facg, in);
+ break;
+ case MTEX_MUL:
+ GPU_link(mat, "mtex_rgb_mul", out, tex, fact, facg, in);
+ break;
+ case MTEX_SCREEN:
+ GPU_link(mat, "mtex_rgb_screen", out, tex, fact, facg, in);
+ break;
+ case MTEX_OVERLAY:
+ GPU_link(mat, "mtex_rgb_overlay", out, tex, fact, facg, in);
+ break;
+ case MTEX_SUB:
+ GPU_link(mat, "mtex_rgb_sub", out, tex, fact, facg, in);
+ break;
+ case MTEX_ADD:
+ GPU_link(mat, "mtex_rgb_add", out, tex, fact, facg, in);
+ break;
+ case MTEX_DIV:
+ GPU_link(mat, "mtex_rgb_div", out, tex, fact, facg, in);
+ break;
+ case MTEX_DIFF:
+ GPU_link(mat, "mtex_rgb_diff", out, tex, fact, facg, in);
+ break;
+ case MTEX_DARK:
+ GPU_link(mat, "mtex_rgb_dark", out, tex, fact, facg, in);
+ break;
+ case MTEX_LIGHT:
+ GPU_link(mat, "mtex_rgb_light", out, tex, fact, facg, in);
+ break;
+ case MTEX_BLEND_HUE:
+ GPU_link(mat, "mtex_rgb_hue", out, tex, fact, facg, in);
+ break;
+ case MTEX_BLEND_SAT:
+ GPU_link(mat, "mtex_rgb_sat", out, tex, fact, facg, in);
+ break;
+ case MTEX_BLEND_VAL:
+ GPU_link(mat, "mtex_rgb_val", out, tex, fact, facg, in);
+ break;
+ case MTEX_BLEND_COLOR:
+ GPU_link(mat, "mtex_rgb_color", out, tex, fact, facg, in);
+ break;
+ default:
+ GPU_link(mat, "set_rgb_zero", &in);
+ break;
+ }
+}
+
+static void texture_value_blend(GPUMaterial *mat, GPUNodeLink *tex, GPUNodeLink *out, GPUNodeLink *fact, GPUNodeLink *facg, int blendtype, int flip, GPUNodeLink **in)
+{
+ float flipf = (flip)? 1.0f: 0.0;
+
+ switch(blendtype) {
+ case MTEX_BLEND:
+ GPU_link(mat, "mtex_value_blend", out, tex, fact, facg, GPU_uniform(&flipf), in);
+ break;
+ case MTEX_MUL:
+ GPU_link(mat, "mtex_value_mul", out, tex, fact, facg, GPU_uniform(&flipf), in);
+ break;
+ case MTEX_SCREEN:
+ GPU_link(mat, "mtex_value_screen", out, tex, fact, facg, GPU_uniform(&flipf), in);
+ break;
+ case MTEX_SUB:
+ GPU_link(mat, "mtex_value_sub", out, tex, fact, facg, GPU_uniform(&flipf), in);
+ break;
+ case MTEX_ADD:
+ GPU_link(mat, "mtex_value_add", out, tex, fact, facg, GPU_uniform(&flipf), in);
+ break;
+ case MTEX_DIV:
+ GPU_link(mat, "mtex_value_div", out, tex, fact, facg, GPU_uniform(&flipf), in);
+ break;
+ case MTEX_DIFF:
+ GPU_link(mat, "mtex_value_diff", out, tex, fact, facg, GPU_uniform(&flipf), in);
+ break;
+ case MTEX_DARK:
+ GPU_link(mat, "mtex_value_dark", out, tex, fact, facg, GPU_uniform(&flipf), in);
+ break;
+ case MTEX_LIGHT:
+ GPU_link(mat, "mtex_value_light", out, tex, fact, facg, GPU_uniform(&flipf), in);
+ break;
+ default:
+ GPU_link(mat, "set_value_zero", &in);
+ break;
+ }
+}
+
+static void do_material_tex(GPUShadeInput *shi)
+{
+ Material *ma= shi->mat;
+ GPUMaterial *mat= shi->gpumat;
+ MTex *mtex;
+ Tex *tex;
+ GPUNodeLink *texco, *tin, *trgb, *tnor, *tcol, *stencil, *tnorfac;
+ GPUNodeLink *texco_norm, *texco_orco, *texco_object, *texco_tangent;
+ GPUNodeLink *texco_global, *texco_uv = NULL;
+ GPUNodeLink *colfac, *newnor, *varfac, *orn;
+ char *lastuvname = NULL;
+ float one = 1.0f, norfac, ofs[3];
+ int tex_nr, rgbnor, talpha;
+
+ GPU_link(mat, "set_value", GPU_uniform(&one), &stencil);
+
+ GPU_link(mat, "texco_norm", GPU_builtin(GPU_VIEW_NORMAL), &texco_norm);
+ GPU_link(mat, "texco_orco", GPU_attribute(CD_ORCO, ""), &texco_orco);
+ GPU_link(mat, "texco_object", GPU_builtin(GPU_INVERSE_VIEW_MATRIX),
+ GPU_builtin(GPU_INVERSE_OBJECT_MATRIX),
+ GPU_builtin(GPU_VIEW_POSITION), &texco_object);
+ GPU_link(mat, "texco_tangent", GPU_attribute(CD_TANGENT, ""), &texco_tangent);
+ GPU_link(mat, "texco_global", GPU_builtin(GPU_INVERSE_VIEW_MATRIX),
+ GPU_builtin(GPU_VIEW_POSITION), &texco_global);
+
+ orn= texco_norm;
+
+ /* go over texture slots */
+ for(tex_nr=0; tex_nr<MAX_MTEX; tex_nr++) {
+ /* separate tex switching */
+ if(ma->septex & (1<<tex_nr)) continue;
+
+ if(ma->mtex[tex_nr]) {
+ mtex= ma->mtex[tex_nr];
+
+ tex= mtex->tex;
+ if(tex==0) continue;
+
+ /* which coords */
+ if(mtex->texco==TEXCO_ORCO)
+ texco= texco_orco;
+ else if(mtex->texco==TEXCO_OBJECT)
+ texco= texco_object;
+ else if(mtex->texco==TEXCO_NORM)
+ texco= orn;
+ else if(mtex->texco==TEXCO_TANGENT)
+ texco= texco_object;
+ else if(mtex->texco==TEXCO_GLOB)
+ texco= texco_global;
+ else if(mtex->texco==TEXCO_REFL)
+ texco= shi->ref;
+ else if(mtex->texco==TEXCO_UV) {
+ if(1) { //!(texco_uv && strcmp(mtex->uvname, lastuvname) == 0)) {
+ GPU_link(mat, "texco_uv", GPU_attribute(CD_MTFACE, mtex->uvname), &texco_uv);
+ lastuvname = mtex->uvname;
+ }
+ texco= texco_uv;
+ }
+ else
+ continue;
+
+ /* in case of uv, this would just undo a multiplication in texco_uv */
+ if(mtex->texco != TEXCO_UV)
+ GPU_link(mat, "mtex_2d_mapping", texco, &texco);
+
+ if(mtex->size[0] != 1.0f || mtex->size[1] != 1.0f || mtex->size[2] != 1.0f)
+ GPU_link(mat, "mtex_mapping_size", texco, GPU_uniform(mtex->size), &texco);
+
+ ofs[0] = mtex->ofs[0] + 0.5f - 0.5f*mtex->size[0];
+ ofs[1] = mtex->ofs[1] + 0.5f - 0.5f*mtex->size[1];
+ ofs[2] = 0.0f;
+ if(ofs[0] != 0.0f || ofs[1] != 0.0f || ofs[2] != 0.0f)
+ GPU_link(mat, "mtex_mapping_ofs", texco, GPU_uniform(ofs), &texco);
+
+ talpha = 0;
+ rgbnor = 0;
+
+ if(tex && tex->type == TEX_IMAGE && tex->ima) {
+ GPU_link(mat, "mtex_image", texco, GPU_image(tex->ima, NULL), &tin, &trgb, &tnor);
+ rgbnor= TEX_RGB;
+
+ if(tex->imaflag & TEX_USEALPHA)
+ talpha= 1;
+ }
+ else continue;
+
+ /* texture output */
+ if((rgbnor & TEX_RGB) && (mtex->texflag & MTEX_RGBTOINT)) {
+ GPU_link(mat, "mtex_rgbtoint", trgb, &tin);
+ rgbnor -= TEX_RGB;
+ }
+
+ if(mtex->texflag & MTEX_NEGATIVE) {
+ if(rgbnor & TEX_RGB)
+ GPU_link(mat, "mtex_rgb_invert", trgb, &trgb);
+ else
+ GPU_link(mat, "mtex_value_invert", tin, &tin);
+ }
+
+ if(mtex->texflag & MTEX_STENCIL) {
+ if(rgbnor & TEX_RGB)
+ GPU_link(mat, "mtex_rgb_stencil", stencil, trgb, &stencil, &trgb);
+ else
+ GPU_link(mat, "mtex_value_stencil", stencil, tin, &stencil, &tin);
+ }
+
+ /* mapping */
+ if(mtex->mapto & (MAP_COL+MAP_COLSPEC)) {
+ /* stencil maps on the texture control slider, not texture intensity value */
+ if(mtex->colfac == 1.0f)
+ colfac = stencil;
+ else
+ GPU_link(mat, "math_multiply", GPU_uniform(&mtex->colfac), stencil, &colfac);
+
+ if((rgbnor & TEX_RGB)==0) {
+ GPU_link(mat, "set_rgb", GPU_uniform(&mtex->r), &tcol);
+ }
+ else {
+ GPU_link(mat, "set_rgba", trgb, &tcol);
+
+ if(mtex->mapto & MAP_ALPHA)
+ GPU_link(mat, "set_value", stencil, &tin);
+ else if(talpha)
+ GPU_link(mat, "mtex_alpha_from_col", trgb, &tin);
+ else
+ GPU_link(mat, "set_value_one", &tin);
+ }
+
+ if(mtex->mapto & MAP_COL)
+ texture_rgb_blend(mat, tcol, shi->rgb, tin, colfac, mtex->blendtype, &shi->rgb);
+
+ if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && (mtex->mapto & MAP_COLSPEC))
+ texture_rgb_blend(mat, tcol, shi->specrgb, tin, colfac, mtex->blendtype, &shi->specrgb);
+ }
+
+ if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && (mtex->mapto & MAP_NORM)) {
+ if(mtex->maptoneg & MAP_NORM) tex->norfac= -mtex->norfac;
+ else tex->norfac= mtex->norfac;
+
+ if((tex->type==TEX_IMAGE) && (tex->imaflag & TEX_NORMALMAP)) {
+ tex->norfac = mtex->norfac;
+
+ if(mtex->maptoneg & MAP_NORM)
+ GPU_link(mat, "mtex_negate_texnormal", tnor, &tnor);
+
+ if(mtex->normapspace == MTEX_NSPACE_TANGENT)
+ GPU_link(mat, "mtex_nspace_tangent", GPU_attribute(CD_TANGENT, ""), shi->vn, tnor, &newnor);
+ else
+ newnor = tnor;
+
+ norfac = MIN2(mtex->norfac, 1.0);
+ if(norfac == 1.0f && !GPU_link_changed(stencil)) {
+ shi->vn = newnor;
+ }
+ else {
+ tnorfac = GPU_uniform(&norfac);
+
+ if(GPU_link_changed(stencil))
+ GPU_link(mat, "math_multiply", tnorfac, stencil, &tnorfac);
+
+ GPU_link(mat, "mtex_blend_normal", tnorfac, shi->vn, newnor, &shi->vn);
+ }
+ }
+
+ GPU_link(mat, "vec_math_negate", shi->vn, &orn);
+ GPU_link(mat, "texco_refl", shi->vn, shi->view, &shi->ref);
+ }
+
+ if((mtex->mapto & MAP_VARS)) {
+ if(mtex->varfac == 1.0f)
+ varfac = stencil;
+ else
+ GPU_link(mat, "math_multiply", GPU_uniform(&mtex->varfac), stencil, &varfac);
+
+ if(rgbnor & TEX_RGB) {
+ if(talpha)
+ GPU_link(mat, "mtex_alpha_from_col", trgb, &tin);
+ else
+ GPU_link(mat, "mtex_rgbtoint", trgb, &tin);
+ }
+
+ if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_REF) {
+ int flip= mtex->maptoneg & MAP_REF;
+ texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->refl, tin, varfac, mtex->blendtype, flip, &shi->refl);
+ GPU_link(mat, "mtex_value_clamp_positive", shi->refl, &shi->refl);
+ }
+ if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_SPEC) {
+ int flip= mtex->maptoneg & MAP_SPEC;
+ texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->spec, tin, varfac, mtex->blendtype, flip, &shi->spec);
+ GPU_link(mat, "mtex_value_clamp_positive", shi->spec, &shi->spec);
+ }
+ if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_EMIT) {
+ int flip= mtex->maptoneg & MAP_EMIT;
+ texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->emit, tin, varfac, mtex->blendtype, flip, &shi->emit);
+ GPU_link(mat, "mtex_value_clamp_positive", shi->emit, &shi->emit);
+ }
+ if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_HAR) {
+ int flip= mtex->maptoneg & MAP_HAR;
+ GPU_link(mat, "mtex_har_divide", shi->har, &shi->har);
+ texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->har, tin, varfac, mtex->blendtype, flip, &shi->har);
+ GPU_link(mat, "mtex_har_multiply_clamp", shi->har, &shi->har);
+ }
+ if(mtex->mapto & MAP_ALPHA) {
+ int flip= mtex->maptoneg & MAP_ALPHA;
+ texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->alpha, tin, varfac, mtex->blendtype, flip, &shi->alpha);
+ GPU_link(mat, "mtex_value_clamp", shi->alpha, &shi->alpha);
+ }
+ if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_AMB) {
+ int flip= mtex->maptoneg & MAP_AMB;
+ texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->amb, tin, varfac, mtex->blendtype, flip, &shi->amb);
+ GPU_link(mat, "mtex_value_clamp", shi->amb, &shi->amb);
+ }
+ }
+ }
+ }
+}
+
+void GPU_shadeinput_set(GPUMaterial *mat, Material *ma, GPUShadeInput *shi)
+{
+ float hard = ma->har;
+
+ memset(shi, 0, sizeof(*shi));
+
+ shi->gpumat = mat;
+ shi->mat = ma;
+
+ GPU_link(mat, "set_rgb", GPU_uniform(&ma->r), &shi->rgb);
+ GPU_link(mat, "set_rgb", GPU_uniform(&ma->specr), &shi->specrgb);
+ GPU_link(mat, "shade_norm", GPU_builtin(GPU_VIEW_NORMAL), &shi->vn);
+ GPU_link(mat, "set_value", GPU_uniform(&ma->alpha), &shi->alpha);
+ GPU_link(mat, "set_value", GPU_uniform(&ma->ref), &shi->refl);
+ GPU_link(mat, "set_value", GPU_uniform(&ma->spec), &shi->spec);
+ GPU_link(mat, "set_value", GPU_uniform(&ma->emit), &shi->emit);
+ GPU_link(mat, "set_value", GPU_uniform(&hard), &shi->har);
+ GPU_link(mat, "set_value", GPU_uniform(&ma->amb), &shi->amb);
+ GPU_link(mat, "shade_view", GPU_builtin(GPU_VIEW_POSITION), &shi->view);
+ GPU_link(mat, "vcol_attribute", GPU_attribute(CD_MCOL, ""), &shi->vcol);
+ GPU_link(mat, "texco_refl", shi->vn, shi->view, &shi->ref);
+}
+
+void GPU_shaderesult_set(GPUShadeInput *shi, GPUShadeResult *shr)
+{
+ GPUMaterial *mat= shi->gpumat;
+ GPUNodeLink *emit, *ulinfac, *ulogfac, *mistfac;
+ Material *ma= shi->mat;
+ World *world= mat->scene->world;
+ float linfac, logfac, misttype;
+
+ memset(shr, 0, sizeof(*shr));
+
+ if(ma->mode & MA_VERTEXCOLP)
+ shi->rgb = shi->vcol;
+
+ do_material_tex(shi);
+
+ if(ma->mode & MA_ZTRA)
+ GPU_material_enable_alpha(mat);
+
+ if((G.fileflags & G_FILE_GLSL_NO_LIGHTS) || (ma->mode & MA_SHLESS)) {
+ shr->combined = shi->rgb;
+ shr->alpha = shi->alpha;
+ GPU_link(mat, "set_rgb", shi->rgb, &shr->diff);
+ GPU_link(mat, "set_rgb_zero", &shr->spec);
+ }
+ else {
+ if(GPU_link_changed(shi->emit) || ma->emit != 0.0f) {
+ if((ma->mode & (MA_VERTEXCOL|MA_VERTEXCOLP))== MA_VERTEXCOL) {
+ GPU_link(mat, "shade_add", shi->emit, shi->vcol, &emit);
+ GPU_link(mat, "shade_mul", emit, shi->rgb, &shr->diff);
+ }
+ else
+ GPU_link(mat, "shade_mul_value", shi->emit, shi->rgb, &shr->diff);
+ }
+ else
+ GPU_link(mat, "set_rgb_zero", &shr->diff);
+
+ GPU_link(mat, "set_rgb_zero", &shr->spec);
+
+ material_lights(shi, shr);
+
+ shr->combined = shr->diff;
+ shr->alpha = shi->alpha;
+
+ if(world) {
+ /* exposure correction */
+ if(world->exp!=0.0f || world->range!=1.0f) {
+ linfac= 1.0 + pow((2.0*world->exp + 0.5), -10);
+ logfac= log((linfac-1.0)/linfac)/world->range;
+
+ GPU_link(mat, "set_value", GPU_uniform(&linfac), &ulinfac);
+ GPU_link(mat, "set_value", GPU_uniform(&logfac), &ulogfac);
+
+ GPU_link(mat, "shade_exposure_correct", shr->combined,
+ ulinfac, ulogfac, &shr->combined);
+ GPU_link(mat, "shade_exposure_correct", shr->spec,
+ ulinfac, ulogfac, &shr->spec);
+ }
+
+ /* ambient color */
+ if(world->ambr!=0.0f || world->ambg!=0.0f || world->ambb!=0.0f) {
+ if(GPU_link_changed(shi->amb) || ma->amb != 0.0f)
+ GPU_link(mat, "shade_maddf", shr->combined, GPU_uniform(&ma->amb),
+ GPU_uniform(&world->ambr), &shr->combined);
+ }
+ }
+
+ if(ma->mode & MA_RAMP_COL) ramp_diffuse_result(shi, &shr->combined);
+ if(ma->mode & MA_RAMP_SPEC) ramp_spec_result(shi, &shr->spec);
+
+ if(GPU_link_changed(shi->spec) || ma->spec != 0.0f)
+ GPU_link(mat, "shade_add", shr->combined, shr->spec, &shr->combined);
+ }
+
+ GPU_link(mat, "mtex_alpha_to_col", shr->combined, shr->alpha, &shr->combined);
+
+ if(ma->shade_flag & MA_OBCOLOR)
+ GPU_link(mat, "shade_obcolor", shr->combined, GPU_builtin(GPU_OBCOLOR), &shr->combined);
+
+ if(world && (world->mode & WO_MIST) && !(ma->mode & MA_NOMIST)) {
+ misttype = world->mistype;
+
+ GPU_link(mat, "shade_mist_factor", GPU_builtin(GPU_VIEW_POSITION),
+ GPU_uniform(&world->miststa), GPU_uniform(&world->mistdist),
+ GPU_uniform(&misttype), GPU_uniform(&world->misi), &mistfac);
+
+ GPU_link(mat, "mix_blend", mistfac, shr->combined,
+ GPU_uniform(&world->horr), &shr->combined);
+ }
+
+ if(!(ma->mode & MA_ZTRA)) {
+ if(world && (GPU_link_changed(shr->alpha) || ma->alpha != 1.0f))
+ GPU_link(mat, "shade_world_mix", GPU_uniform(&world->horr),
+ shr->combined, &shr->combined);
+
+ GPU_link(mat, "shade_alpha_opaque", shr->combined, &shr->combined);
+ }
+
+ if(ma->shade_flag & MA_OBCOLOR) {
+ mat->obcolalpha = 1;
+ GPU_link(mat, "shade_alpha_obcolor", shr->combined, GPU_builtin(GPU_OBCOLOR), &shr->combined);
+ }
+}
+
+GPUNodeLink *GPU_blender_material(GPUMaterial *mat, Material *ma)
+{
+ GPUShadeInput shi;
+ GPUShadeResult shr;
+
+ GPU_shadeinput_set(mat, ma, &shi);
+ GPU_shaderesult_set(&shi, &shr);
+
+ return shr.combined;
+}
+
+GPUMaterial *GPU_material_from_blender(Scene *scene, Material *ma)
+{
+ GPUMaterial *mat;
+ GPUNodeLink *outlink;
+ LinkData *link;
+
+ for(link=ma->gpumaterial.first; link; link=link->next)
+ if(((GPUMaterial*)link->data)->scene == scene)
+ return link->data;
+
+ mat = GPU_material_construct_begin(ma);
+ mat->scene = scene;
+
+ if(!(G.fileflags & G_FILE_GLSL_NO_NODES) && ma->nodetree && ma->use_nodes) {
+ ntreeGPUMaterialNodes(ma->nodetree, mat);
+ }
+ else {
+ outlink = GPU_blender_material(mat, ma);
+ GPU_material_output_link(mat, outlink);
+ }
+
+ /*if(!GPU_material_construct_end(mat)) {
+ GPU_material_free(mat);
+ mat= NULL;
+ return 0;
+ }*/
+
+ GPU_material_construct_end(mat);
+
+ link = MEM_callocN(sizeof(LinkData), "GPUMaterialLink");
+ link->data = mat;
+ BLI_addtail(&ma->gpumaterial, link);
+
+ return mat;
+}
+
+void GPU_materials_free()
+{
+ Object *ob;
+ Material *ma;
+ extern Material defmaterial;
+
+ for(ma=G.main->mat.first; ma; ma=ma->id.next)
+ GPU_material_free(ma);
+
+ GPU_material_free(&defmaterial);
+
+ for(ob=G.main->object.first; ma; ma=ma->id.next)
+ GPU_lamp_free(ob);
+}
+
+/* Lamps and shadow buffers */
+
+void GPU_lamp_update(GPULamp *lamp, int lay, float obmat[][4])
+{
+ float mat[4][4];
+
+ lamp->lay = lay;
+
+ Mat4CpyMat4(mat, obmat);
+ Mat4Ortho(mat);
+
+ VECCOPY(lamp->vec, mat[2]);
+ VECCOPY(lamp->co, mat[3]);
+ Mat4CpyMat4(lamp->obmat, mat);
+ Mat4Invert(lamp->imat, mat);
+}
+
+static void gpu_lamp_from_blender(Scene *scene, Object *ob, Object *par, Lamp *la, GPULamp *lamp)
+{
+ float temp, angle, pixsize, wsize;
+
+ lamp->scene = scene;
+ lamp->ob = ob;
+ lamp->par = par;
+ lamp->la = la;
+
+ /* add_render_lamp */
+ lamp->mode = la->mode;
+ lamp->type = la->type;
+
+ lamp->energy = la->energy;
+ if(lamp->mode & LA_NEG) lamp->energy= -lamp->energy;
+
+ lamp->col[0]= la->r*lamp->energy;
+ lamp->col[1]= la->g*lamp->energy;
+ lamp->col[2]= la->b*lamp->energy;
+
+ GPU_lamp_update(lamp, ob->lay, ob->obmat);
+
+ lamp->spotsi= la->spotsize;
+ if(lamp->mode & LA_HALO)
+ if(lamp->spotsi > 170.0)
+ lamp->spotsi = 170.0;
+ lamp->spotsi= cos(M_PI*lamp->spotsi/360.0);
+ lamp->spotbl= (1.0 - lamp->spotsi)*la->spotblend;
+ lamp->k= la->k;
+
+ lamp->dist= la->dist;
+ lamp->falloff_type= la->falloff_type;
+ lamp->att1= la->att1;
+ lamp->att2= la->att2;
+ lamp->curfalloff= la->curfalloff;
+
+ /* initshadowbuf */
+ lamp->bias = 0.02f*la->bias;
+ lamp->size = la->bufsize;
+ lamp->d= la->clipsta;
+ lamp->clipend= la->clipend;
+
+ /* arbitrary correction for the fact we do no soft transition */
+ lamp->bias *= 0.25f;
+
+ /* makeshadowbuf */
+ angle= saacos(lamp->spotsi);
+ temp= 0.5f*lamp->size*cos(angle)/sin(angle);
+ pixsize= (lamp->d)/temp;
+ wsize= pixsize*0.5f*lamp->size;
+
+ i_window(-wsize, wsize, -wsize, wsize, lamp->d, lamp->clipend, lamp->winmat);
+}
+
+static void gpu_lamp_shadow_free(GPULamp *lamp)
+{
+ if(lamp->tex) {
+ GPU_texture_free(lamp->tex);
+ lamp->tex= NULL;
+ }
+ if(lamp->fb) {
+ GPU_framebuffer_free(lamp->fb);
+ lamp->fb= NULL;
+ }
+}
+
+GPULamp *GPU_lamp_from_blender(Scene *scene, Object *ob, Object *par)
+{
+ Lamp *la;
+ GPULamp *lamp;
+ LinkData *link;
+
+ for(link=ob->gpulamp.first; link; link=link->next) {
+ lamp = (GPULamp*)link->data;
+
+ if(lamp->par == par && lamp->scene == scene)
+ return link->data;
+ }
+
+ lamp = MEM_callocN(sizeof(GPULamp), "GPULamp");
+
+ link = MEM_callocN(sizeof(LinkData), "GPULampLink");
+ link->data = lamp;
+ BLI_addtail(&ob->gpulamp, link);
+
+ la = ob->data;
+ gpu_lamp_from_blender(scene, ob, par, la, lamp);
+
+ if(la->type==LA_SPOT && (la->mode & LA_SHAD_BUF)) {
+ /* opengl */
+ lamp->fb = GPU_framebuffer_create();
+ if(!lamp->fb) {
+ gpu_lamp_shadow_free(lamp);
+ return lamp;
+ }
+
+ lamp->tex = GPU_texture_create_depth(lamp->size, lamp->size);
+ if(!lamp->tex) {
+ gpu_lamp_shadow_free(lamp);
+ return lamp;
+ }
+
+ if(!GPU_framebuffer_texture_attach(lamp->fb, lamp->tex)) {
+ gpu_lamp_shadow_free(lamp);
+ return lamp;
+ }
+
+ GPU_framebuffer_restore();
+ }
+
+ return lamp;
+}
+
+void GPU_lamp_free(Object *ob)
+{
+ GPULamp *lamp;
+ LinkData *link;
+ LinkData *nlink;
+ Material *ma;
+
+ for(link=ob->gpulamp.first; link; link=link->next) {
+ lamp = link->data;
+
+ while(lamp->materials.first) {
+ nlink = lamp->materials.first;
+ ma = nlink->data;
+ BLI_freelinkN(&lamp->materials, nlink);
+
+ if(ma->gpumaterial.first)
+ GPU_material_free(ma);
+ }
+
+ gpu_lamp_shadow_free(lamp);
+
+ MEM_freeN(lamp);
+ }
+
+ BLI_freelistN(&ob->gpulamp);
+}
+
+int GPU_lamp_has_shadow_buffer(GPULamp *lamp)
+{
+ return (!(G.fileflags & G_FILE_GLSL_NO_SHADOWS) &&
+ !(G.fileflags & G_FILE_GLSL_NO_LIGHTS) &&
+ lamp->tex && lamp->fb);
+}
+
+void GPU_lamp_shadow_buffer_bind(GPULamp *lamp, float viewmat[][4], int *winsize, float winmat[][4])
+{
+ float rangemat[4][4], persmat[4][4];
+
+ /* initshadowbuf */
+ Mat4Invert(lamp->viewmat, lamp->obmat);
+ Normalize(lamp->viewmat[0]);
+ Normalize(lamp->viewmat[1]);
+ Normalize(lamp->viewmat[2]);
+
+ /* makeshadowbuf */
+ Mat4MulMat4(persmat, lamp->viewmat, lamp->winmat);
+
+ /* opengl depth buffer is range 0.0..1.0 instead of -1.0..1.0 in blender */
+ Mat4One(rangemat);
+ rangemat[0][0] = 0.5f;
+ rangemat[1][1] = 0.5f;
+ rangemat[2][2] = 0.5f;
+ rangemat[3][0] = 0.5f;
+ rangemat[3][1] = 0.5f;
+ rangemat[3][2] = 0.5f;
+
+ Mat4MulMat4(lamp->persmat, persmat, rangemat);
+
+ /* opengl */
+ GPU_framebuffer_texture_bind(lamp->fb, lamp->tex);
+
+ /* set matrices */
+ Mat4CpyMat4(viewmat, lamp->viewmat);
+ Mat4CpyMat4(winmat, lamp->winmat);
+ *winsize = lamp->size;
+}
+
+void GPU_lamp_shadow_buffer_unbind(GPULamp *lamp)
+{
+ GPU_framebuffer_texture_unbind(lamp->fb, lamp->tex);
+ GPU_framebuffer_restore();
+}
+
+int GPU_lamp_shadow_layer(GPULamp *lamp)
+{
+ if(lamp->fb && lamp->tex && (lamp->mode & (LA_LAYER|LA_LAYER_SHADOW)))
+ return lamp->lay;
+ else
+ return -1;
+}
+
diff --git a/source/blender/gpu/intern/gpu_shader_material.glsl b/source/blender/gpu/intern/gpu_shader_material.glsl
new file mode 100644
index 00000000000..16ed38cb47d
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_shader_material.glsl
@@ -0,0 +1,1555 @@
+
+float exp_blender(float f)
+{
+ return pow(2.71828182846, f);
+}
+
+void rgb_to_hsv(vec4 rgb, out vec4 outcol)
+{
+ float cmax, cmin, h, s, v, cdelta;
+ vec3 c;
+
+ cmax = max(rgb[0], max(rgb[1], rgb[2]));
+ cmin = min(rgb[0], min(rgb[1], rgb[2]));
+ cdelta = cmax-cmin;
+
+ v = cmax;
+ if (cmax!=0.0)
+ s = cdelta/cmax;
+ else {
+ s = 0.0;
+ h = 0.0;
+ }
+
+ if (s == 0.0) {
+ h = 0.0;
+ }
+ else {
+ c = (vec3(cmax, cmax, cmax) - rgb.xyz)/cdelta;
+
+ if (rgb.x==cmax) h = c[2] - c[1];
+ else if (rgb.y==cmax) h = 2.0 + c[0] - c[2];
+ else h = 4.0 + c[1] - c[0];
+
+ h /= 6.0;
+
+ if (h<0.0)
+ h += 1.0;
+ }
+
+ outcol = vec4(h, s, v, rgb.w);
+}
+
+void hsv_to_rgb(vec4 hsv, out vec4 outcol)
+{
+ float i, f, p, q, t, h, s, v;
+ vec3 rgb;
+
+ h = hsv[0];
+ s = hsv[1];
+ v = hsv[2];
+
+ if(s==0.0) {
+ rgb = vec3(v, v, v);
+ }
+ else {
+ if(h==1.0)
+ h = 0.0;
+
+ h *= 6.0;
+ i = floor(h);
+ f = h - i;
+ rgb = vec3(f, f, f);
+ p = v*(1.0-s);
+ q = v*(1.0-(s*f));
+ t = v*(1.0-(s*(1.0-f)));
+
+ if (i == 0.0) rgb = vec3(v, t, p);
+ else if (i == 1.0) rgb = vec3(q, v, p);
+ else if (i == 2.0) rgb = vec3(p, v, t);
+ else if (i == 3.0) rgb = vec3(p, q, v);
+ else if (i == 4.0) rgb = vec3(t, p, v);
+ else rgb = vec3(v, p, q);
+ }
+
+ outcol = vec4(rgb, hsv.w);
+}
+
+#define M_PI 3.14159265358979323846
+
+/*********** SHADER NODES ***************/
+
+void vcol_attribute(vec4 attvcol, out vec4 vcol)
+{
+ vcol = vec4(attvcol.x/255.0, attvcol.y/255.0, attvcol.z/255.0, 1.0);
+}
+
+void uv_attribute(vec2 attuv, out vec3 uv)
+{
+ uv = vec3(attuv*2.0 - vec2(1.0, 1.0), 0.0);
+}
+
+void geom(vec3 co, vec3 nor, mat4 viewinvmat, vec3 attorco, vec2 attuv, vec4 attvcol, out vec3 global, out vec3 local, out vec3 view, out vec3 orco, out vec3 uv, out vec3 normal, out vec4 vcol, out float frontback)
+{
+ local = co;
+ view = normalize(local);
+ global = (viewinvmat*vec4(local, 1.0)).xyz;
+ orco = attorco;
+ uv_attribute(attuv, uv);
+ normal = -normalize(nor); /* blender render normal is negated */
+ vcol_attribute(attvcol, vcol);
+ frontback = 1.0;
+}
+
+void mapping(vec3 vec, mat4 mat, vec3 minvec, vec3 maxvec, float domin, float domax, out vec3 outvec)
+{
+ outvec = (mat * vec4(vec, 1.0)).xyz;
+ if(domin == 1.0)
+ outvec = max(outvec, minvec);
+ if(domax == 1.0)
+ outvec = min(outvec, maxvec);
+}
+
+void camera(vec3 co, out vec3 outview, out float outdepth, out float outdist)
+{
+ outdepth = abs(co.z);
+ outdist = length(co);
+ outview = normalize(co);
+}
+
+void math_add(float val1, float val2, out float outval)
+{
+ outval = val1 + val2;
+}
+
+void math_subtract(float val1, float val2, out float outval)
+{
+ outval = val1 - val2;
+}
+
+void math_multiply(float val1, float val2, out float outval)
+{
+ outval = val1 * val2;
+}
+
+void math_divide(float val1, float val2, out float outval)
+{
+ if (val2 == 0.0)
+ outval = 0.0;
+ else
+ outval = val1 / val2;
+}
+
+void math_sine(float val, out float outval)
+{
+ outval = sin(val);
+}
+
+void math_cosine(float val, out float outval)
+{
+ outval = cos(val);
+}
+
+void math_tangent(float val, out float outval)
+{
+ outval = tan(val);
+}
+
+void math_asin(float val, out float outval)
+{
+ if (val <= 1.0 && val >= -1.0)
+ outval = asin(val);
+ else
+ outval = 0.0;
+}
+
+void math_acos(float val, out float outval)
+{
+ if (val <= 1.0 && val >= -1.0)
+ outval = acos(val);
+ else
+ outval = 0.0;
+}
+
+void math_atan(float val, out float outval)
+{
+ outval = atan(val);
+}
+
+void math_pow(float val1, float val2, out float outval)
+{
+ if (val1 >= 0.0)
+ outval = pow(val1, val2);
+ else
+ outval = 0.0;
+}
+
+void math_log(float val1, float val2, out float outval)
+{
+ if(val1 > 0.0 && val2 > 0.0)
+ outval= log2(val1) / log2(val2);
+ else
+ outval= 0.0;
+}
+
+void math_max(float val1, float val2, out float outval)
+{
+ outval = max(val1, val2);
+}
+
+void math_min(float val1, float val2, out float outval)
+{
+ outval = min(val1, val2);
+}
+
+void math_round(float val, out float outval)
+{
+ outval= floor(val + 0.5);
+}
+
+void math_less_than(float val1, float val2, out float outval)
+{
+ if(val1 < val2)
+ outval = 1.0;
+ else
+ outval = 0.0;
+}
+
+void math_greater_than(float val1, float val2, out float outval)
+{
+ if(val1 > val2)
+ outval = 1.0;
+ else
+ outval = 0.0;
+}
+
+void squeeze(float val, float width, float center, out float outval)
+{
+ outval = 1.0/(1.0 + pow(2.71828183, -((val-center)*width)));
+}
+
+void vec_math_add(vec3 v1, vec3 v2, out vec3 outvec, out float outval)
+{
+ outvec = v1 + v2;
+ outval = (abs(outvec[0]) + abs(outvec[1]) + abs(outvec[2]))/3.0;
+}
+
+void vec_math_sub(vec3 v1, vec3 v2, out vec3 outvec, out float outval)
+{
+ outvec = v1 - v2;
+ outval = (abs(outvec[0]) + abs(outvec[1]) + abs(outvec[2]))/3.0;
+}
+
+void vec_math_average(vec3 v1, vec3 v2, out vec3 outvec, out float outval)
+{
+ outvec = v1 + v2;
+ outval = length(outvec);
+ outvec = normalize(outvec);
+}
+
+void vec_math_dot(vec3 v1, vec3 v2, out vec3 outvec, out float outval)
+{
+ outvec = vec3(0, 0, 0);
+ outval = dot(v1, v2);
+}
+
+void vec_math_cross(vec3 v1, vec3 v2, out vec3 outvec, out float outval)
+{
+ outvec = cross(v1, v2);
+ outval = length(outvec);
+}
+
+void vec_math_normalize(vec3 v, out vec3 outvec, out float outval)
+{
+ outval = length(v);
+ outvec = normalize(v);
+}
+
+void vec_math_negate(vec3 v, out vec3 outv)
+{
+ outv = -v;
+}
+
+void normal(vec3 dir, vec3 nor, out vec3 outnor, out float outdot)
+{
+ outnor = dir;
+ outdot = -dot(dir, nor);
+}
+
+void curves_vec(vec3 vec, sampler1D curvemap, out vec3 outvec)
+{
+ outvec.x = texture1D(curvemap, (vec.x + 1.0)*0.5).x;
+ outvec.y = texture1D(curvemap, (vec.y + 1.0)*0.5).y;
+ outvec.z = texture1D(curvemap, (vec.z + 1.0)*0.5).z;
+}
+
+void curves_rgb(vec4 col, sampler1D curvemap, out vec4 outcol)
+{
+ outcol.r = texture1D(curvemap, texture1D(curvemap, col.r).a).r;
+ outcol.g = texture1D(curvemap, texture1D(curvemap, col.g).a).g;
+ outcol.b = texture1D(curvemap, texture1D(curvemap, col.b).a).b;
+ outcol.a = col.a;
+}
+
+void set_value(float val, out float outval)
+{
+ outval = val;
+}
+
+void set_rgb(vec3 col, out vec3 outcol)
+{
+ outcol = col;
+}
+
+void set_rgba(vec4 col, out vec4 outcol)
+{
+ outcol = col;
+}
+
+void set_value_zero(out float outval)
+{
+ outval = 0.0;
+}
+
+void set_value_one(out float outval)
+{
+ outval = 1.0;
+}
+
+void set_rgb_zero(out vec3 outval)
+{
+ outval = vec3(0.0);
+}
+
+void set_rgba_zero(out vec4 outval)
+{
+ outval = vec4(0.0);
+}
+
+void mix_blend(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ outcol = mix(col1, col2, fac);
+ outcol.a = col1.a;
+}
+
+void mix_add(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ outcol = mix(col1, col1 + col2, fac);
+ outcol.a = col1.a;
+}
+
+void mix_mult(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ outcol = mix(col1, col1 * col2, fac);
+ outcol.a = col1.a;
+}
+
+void mix_screen(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ float facm = 1.0 - fac;
+
+ outcol = vec4(1.0) - (vec4(facm) + fac*(vec4(1.0) - col2))*(vec4(1.0) - col1);
+ outcol.a = col1.a;
+}
+
+void mix_overlay(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ float facm = 1.0 - fac;
+
+ outcol = col1;
+
+ if(outcol.r < 0.5)
+ outcol.r *= facm + 2.0*fac*col2.r;
+ else
+ outcol.r = 1.0 - (facm + 2.0*fac*(1.0 - col2.r))*(1.0 - outcol.r);
+
+ if(outcol.g < 0.5)
+ outcol.g *= facm + 2.0*fac*col2.g;
+ else
+ outcol.g = 1.0 - (facm + 2.0*fac*(1.0 - col2.g))*(1.0 - outcol.g);
+
+ if(outcol.b < 0.5)
+ outcol.b *= facm + 2.0*fac*col2.b;
+ else
+ outcol.b = 1.0 - (facm + 2.0*fac*(1.0 - col2.b))*(1.0 - outcol.b);
+}
+
+void mix_sub(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ outcol = mix(col1, col1 - col2, fac);
+ outcol.a = col1.a;
+}
+
+void mix_div(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ float facm = 1.0 - fac;
+
+ outcol = col1;
+
+ if(col2.r != 0.0) outcol.r = facm*outcol.r + fac*outcol.r/col2.r;
+ if(col2.g != 0.0) outcol.g = facm*outcol.g + fac*outcol.g/col2.g;
+ if(col2.b != 0.0) outcol.b = facm*outcol.b + fac*outcol.b/col2.b;
+}
+
+void mix_diff(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ outcol = mix(col1, abs(col1 - col2), fac);
+ outcol.a = col1.a;
+}
+
+void mix_dark(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ outcol.rgb = min(col1.rgb, col2.rgb*fac);
+ outcol.a = col1.a;
+}
+
+void mix_light(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ outcol.rgb = max(col1.rgb, col2.rgb*fac);
+ outcol.a = col1.a;
+}
+
+void mix_dodge(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ outcol = col1;
+
+ if(outcol.r != 0.0) {
+ float tmp = 1.0 - fac*col2.r;
+ if(tmp <= 0.0)
+ outcol.r = 1.0;
+ else if((tmp = outcol.r/tmp) > 1.0)
+ outcol.r = 1.0;
+ else
+ outcol.r = tmp;
+ }
+ if(outcol.g != 0.0) {
+ float tmp = 1.0 - fac*col2.g;
+ if(tmp <= 0.0)
+ outcol.g = 1.0;
+ else if((tmp = outcol.g/tmp) > 1.0)
+ outcol.g = 1.0;
+ else
+ outcol.g = tmp;
+ }
+ if(outcol.b != 0.0) {
+ float tmp = 1.0 - fac*col2.b;
+ if(tmp <= 0.0)
+ outcol.b = 1.0;
+ else if((tmp = outcol.b/tmp) > 1.0)
+ outcol.b = 1.0;
+ else
+ outcol.b = tmp;
+ }
+}
+
+void mix_burn(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ float tmp, facm = 1.0 - fac;
+
+ outcol = col1;
+
+ tmp = facm + fac*col2.r;
+ if(tmp <= 0.0)
+ outcol.r = 0.0;
+ else if((tmp = (1.0 - (1.0 - outcol.r)/tmp)) < 0.0)
+ outcol.r = 0.0;
+ else if(tmp > 1.0)
+ outcol.r = 1.0;
+ else
+ outcol.r = tmp;
+
+ tmp = facm + fac*col2.g;
+ if(tmp <= 0.0)
+ outcol.g = 0.0;
+ else if((tmp = (1.0 - (1.0 - outcol.g)/tmp)) < 0.0)
+ outcol.g = 0.0;
+ else if(tmp > 1.0)
+ outcol.g = 1.0;
+ else
+ outcol.g = tmp;
+
+ tmp = facm + fac*col2.b;
+ if(tmp <= 0.0)
+ outcol.b = 0.0;
+ else if((tmp = (1.0 - (1.0 - outcol.b)/tmp)) < 0.0)
+ outcol.b = 0.0;
+ else if(tmp > 1.0)
+ outcol.b = 1.0;
+ else
+ outcol.b = tmp;
+}
+
+void mix_hue(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ float facm = 1.0 - fac;
+
+ outcol = col1;
+
+ vec4 hsv, hsv2, tmp;
+ rgb_to_hsv(col2, hsv2);
+
+ if(hsv2.y != 0.0) {
+ rgb_to_hsv(outcol, hsv);
+ hsv.x = hsv2.x;
+ hsv_to_rgb(hsv, tmp);
+
+ outcol = mix(outcol, tmp, fac);
+ outcol.a = col1.a;
+ }
+}
+
+void mix_sat(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ float facm = 1.0 - fac;
+
+ outcol = col1;
+
+ vec4 hsv, hsv2;
+ rgb_to_hsv(outcol, hsv);
+
+ if(hsv.y != 0.0) {
+ rgb_to_hsv(col2, hsv2);
+
+ hsv.y = facm*hsv.y + fac*hsv2.y;
+ hsv_to_rgb(hsv, outcol);
+ }
+}
+
+void mix_val(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ float facm = 1.0 - fac;
+
+ vec4 hsv, hsv2;
+ rgb_to_hsv(col1, hsv);
+ rgb_to_hsv(col2, hsv2);
+
+ hsv.z = facm*hsv.z + fac*hsv2.z;
+ hsv_to_rgb(hsv, outcol);
+}
+
+void mix_color(float fac, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ fac = clamp(fac, 0.0, 1.0);
+ float facm = 1.0 - fac;
+
+ outcol = col1;
+
+ vec4 hsv, hsv2, tmp;
+ rgb_to_hsv(col2, hsv2);
+
+ if(hsv2.y != 0.0) {
+ rgb_to_hsv(outcol, hsv);
+ hsv.x = hsv2.x;
+ hsv.y = hsv2.y;
+ hsv_to_rgb(hsv, tmp);
+
+ outcol = mix(outcol, tmp, fac);
+ outcol.a = col1.a;
+ }
+}
+
+void valtorgb(float fac, sampler1D colormap, out vec4 outcol, out float outalpha)
+{
+ outcol = texture1D(colormap, fac);
+ outalpha = outcol.a;
+}
+
+void rgbtobw(vec4 color, out float outval)
+{
+ outval = color.r*0.35 + color.g*0.45 + color.b*0.2;
+}
+
+void invert(float fac, vec4 col, out vec4 outcol)
+{
+ outcol.xyz = mix(col.xyz, vec3(1.0, 1.0, 1.0) - col.xyz, fac);
+ outcol.w = col.w;
+}
+
+void hue_sat(float hue, float sat, float value, float fac, vec4 col, out vec4 outcol)
+{
+ vec4 hsv;
+
+ rgb_to_hsv(col, hsv);
+
+ hsv[0] += (hue - 0.5);
+ if(hsv[0]>1.0) hsv[0]-=1.0; else if(hsv[0]<0.0) hsv[0]+= 1.0;
+ hsv[1] *= sat;
+ if(hsv[1]>1.0) hsv[1]= 1.0; else if(hsv[1]<0.0) hsv[1]= 0.0;
+ hsv[2] *= value;
+ if(hsv[2]>1.0) hsv[2]= 1.0; else if(hsv[2]<0.0) hsv[2]= 0.0;
+
+ hsv_to_rgb(hsv, outcol);
+
+ outcol = mix(col, outcol, fac);
+}
+
+void separate_rgb(vec4 col, out float r, out float g, out float b)
+{
+ r = col.r;
+ g = col.g;
+ b = col.b;
+}
+
+void combine_rgb(float r, float g, float b, out vec4 col)
+{
+ col = vec4(r, g, b, 1.0);
+}
+
+void output_node(vec4 rgb, float alpha, out vec4 outrgb)
+{
+ outrgb = vec4(rgb.rgb, alpha);
+}
+
+/*********** TEXTURES ***************/
+
+void texture_flip_blend(vec3 vec, out vec3 outvec)
+{
+ outvec = vec.yxz;
+}
+
+void texture_blend_lin(vec3 vec, out float outval)
+{
+ outval = (1.0+vec.x)/2.0;
+}
+
+void texture_blend_quad(vec3 vec, out float outval)
+{
+ outval = max((1.0+vec.x)/2.0, 0.0);
+ outval *= outval;
+}
+
+void texture_wood_sin(vec3 vec, out float value, out vec4 color, out vec3 normal)
+{
+ float a = sqrt(vec.x*vec.x + vec.y*vec.y + vec.z*vec.z)*20.0;
+ float wi = 0.5 + 0.5*sin(a);
+
+ value = wi;
+ color = vec4(wi, wi, wi, 1.0);
+ normal = vec3(0.0, 0.0, 0.0);
+}
+
+void texture_image(vec3 vec, sampler2D ima, out float value, out vec4 color, out vec3 normal)
+{
+ color = texture2D(ima, (vec.xy + vec2(1.0, 1.0))*0.5);
+ value = 1.0;
+
+ normal.x = 2.0*(color.r - 0.5);
+ normal.y = 2.0*(0.5 - color.g);
+ normal.z = 2.0*(color.b - 0.5);
+}
+
+/************* MTEX *****************/
+
+void texco_orco(vec3 attorco, out vec3 orco)
+{
+ orco = attorco;
+}
+
+void texco_uv(vec2 attuv, out vec3 uv)
+{
+ /* disabled for now, works together with leaving out mtex_2d_mapping
+ uv = vec3(attuv*2.0 - vec2(1.0, 1.0), 0.0); */
+ uv = vec3(attuv, 0.0);
+}
+
+void texco_norm(vec3 normal, out vec3 outnormal)
+{
+ /* corresponds to shi->orn, which is negated so cancels
+ out blender normal negation */
+ outnormal = normalize(normal);
+}
+
+void texco_tangent(vec3 tangent, out vec3 outtangent)
+{
+ outtangent = normalize(tangent);
+}
+
+void texco_global(mat4 viewinvmat, vec3 co, out vec3 global)
+{
+ global = (viewinvmat*vec4(co, 1.0)).xyz;
+}
+
+void texco_object(mat4 viewinvmat, mat4 obinvmat, vec3 co, out vec3 object)
+{
+ object = (obinvmat*(viewinvmat*vec4(co, 1.0))).xyz;
+}
+
+void texco_refl(vec3 vn, vec3 view, out vec3 ref)
+{
+ ref = view - 2.0*dot(vn, view)*vn;
+}
+
+void shade_norm(vec3 normal, out vec3 outnormal)
+{
+ /* blender render normal is negated */
+ outnormal = -normalize(normal);
+}
+
+void mtex_rgb_blend(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ float facm;
+
+ fact *= facg;
+ facm = 1.0-fact;
+
+ incol = fact*texcol + facm*outcol;
+}
+
+void mtex_rgb_mul(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ float facm;
+
+ fact *= facg;
+ facm = 1.0-facg;
+
+ incol = (facm + fact*texcol)*outcol;
+}
+
+void mtex_rgb_screen(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ float facm;
+
+ fact *= facg;
+ facm = 1.0-facg;
+
+ incol = vec3(1.0) - (vec3(facm) + fact*(vec3(1.0) - texcol))*(vec3(1.0) - outcol);
+}
+
+void mtex_rgb_overlay(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ float facm;
+
+ fact *= facg;
+ facm = 1.0-facg;
+
+ if(outcol.r < 0.5)
+ incol.r = outcol.r*(facm + 2.0*fact*texcol.r);
+ else
+ incol.r = 1.0 - (facm + 2.0*fact*(1.0 - texcol.r))*(1.0 - outcol.r);
+
+ if(outcol.g < 0.5)
+ incol.g = outcol.g*(facm + 2.0*fact*texcol.g);
+ else
+ incol.g = 1.0 - (facm + 2.0*fact*(1.0 - texcol.g))*(1.0 - outcol.g);
+
+ if(outcol.b < 0.5)
+ incol.b = outcol.b*(facm + 2.0*fact*texcol.b);
+ else
+ incol.b = 1.0 - (facm + 2.0*fact*(1.0 - texcol.b))*(1.0 - outcol.b);
+}
+
+void mtex_rgb_sub(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ incol = -fact*facg*texcol + outcol;
+}
+
+void mtex_rgb_add(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ incol = fact*facg*texcol + outcol;
+}
+
+void mtex_rgb_div(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ float facm;
+
+ fact *= facg;
+ facm = 1.0-fact;
+
+ if(texcol.r != 0.0) incol.r = facm*outcol.r + fact*outcol.r/texcol.r;
+ if(texcol.g != 0.0) incol.g = facm*outcol.g + fact*outcol.g/texcol.g;
+ if(texcol.b != 0.0) incol.b = facm*outcol.b + fact*outcol.b/texcol.b;
+}
+
+void mtex_rgb_diff(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ float facm;
+
+ fact *= facg;
+ facm = 1.0-fact;
+
+ incol = facm*outcol + fact*abs(texcol - outcol);
+}
+
+void mtex_rgb_dark(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ float facm, col;
+
+ fact *= facg;
+ facm = 1.0-fact;
+
+ col = fact*texcol.r;
+ if(col < outcol.r) incol.r = col; else incol.r = outcol.r;
+ col = fact*texcol.g;
+ if(col < outcol.g) incol.g = col; else incol.g = outcol.g;
+ col = fact*texcol.b;
+ if(col < outcol.b) incol.b = col; else incol.b = outcol.b;
+}
+
+void mtex_rgb_light(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ float facm, col;
+
+ fact *= facg;
+ facm = 1.0-fact;
+
+ col = fact*texcol.r;
+ if(col > outcol.r) incol.r = col; else incol.r = outcol.r;
+ col = fact*texcol.g;
+ if(col > outcol.g) incol.g = col; else incol.g = outcol.g;
+ col = fact*texcol.b;
+ if(col > outcol.b) incol.b = col; else incol.b = outcol.b;
+}
+
+void mtex_rgb_hue(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ vec4 col;
+
+ mix_hue(fact*facg, vec4(outcol, 1.0), vec4(texcol, 1.0), col);
+ incol.rgb = col.rgb;
+}
+
+void mtex_rgb_sat(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ vec4 col;
+
+ mix_sat(fact*facg, vec4(outcol, 1.0), vec4(texcol, 1.0), col);
+ incol.rgb = col.rgb;
+}
+
+void mtex_rgb_val(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ vec4 col;
+
+ mix_val(fact*facg, vec4(outcol, 1.0), vec4(texcol, 1.0), col);
+ incol.rgb = col.rgb;
+}
+
+void mtex_rgb_color(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol)
+{
+ vec4 col;
+
+ mix_color(fact*facg, vec4(outcol, 1.0), vec4(texcol, 1.0), col);
+ incol.rgb = col.rgb;
+}
+
+void mtex_value_vars(inout float fact, float facg, out float facm, float flip)
+{
+ fact *= facg;
+ facm = 1.0-fact;
+
+ if(flip != 0.0) {
+ float tmp = fact;
+ fact = facm;
+ facm = tmp;
+ }
+}
+
+void mtex_value_blend(float outcol, float texcol, float fact, float facg, float flip, out float incol)
+{
+ float facm;
+ mtex_value_vars(fact, facg, facm, flip);
+
+ incol = fact*texcol + facm*outcol;
+}
+
+void mtex_value_mul(float outcol, float texcol, float fact, float facg, float flip, out float incol)
+{
+ float facm;
+ mtex_value_vars(fact, facg, facm, flip);
+
+ facm = 1.0 - facg;
+ incol = (facm + fact*texcol)*outcol;
+}
+
+void mtex_value_screen(float outcol, float texcol, float fact, float facg, float flip, out float incol)
+{
+ float facm;
+ mtex_value_vars(fact, facg, facm, flip);
+
+ facm = 1.0 - facg;
+ incol = 1.0 - (facm + fact*(1.0 - texcol))*(1.0 - outcol);
+}
+
+void mtex_value_sub(float outcol, float texcol, float fact, float facg, float flip, out float incol)
+{
+ float facm;
+ mtex_value_vars(fact, facg, facm, flip);
+
+ fact = -fact;
+ incol = fact*texcol + outcol;
+}
+
+void mtex_value_add(float outcol, float texcol, float fact, float facg, float flip, out float incol)
+{
+ float facm;
+ mtex_value_vars(fact, facg, facm, flip);
+
+ fact = fact;
+ incol = fact*texcol + outcol;
+}
+
+void mtex_value_div(float outcol, float texcol, float fact, float facg, float flip, out float incol)
+{
+ float facm;
+ mtex_value_vars(fact, facg, facm, flip);
+
+ if(texcol != 0.0)
+ incol = facm*outcol + fact*outcol/texcol;
+ else
+ incol = 0.0;
+}
+
+void mtex_value_diff(float outcol, float texcol, float fact, float facg, float flip, out float incol)
+{
+ float facm;
+ mtex_value_vars(fact, facg, facm, flip);
+
+ incol = facm*outcol + fact*abs(texcol - outcol);
+}
+
+void mtex_value_dark(float outcol, float texcol, float fact, float facg, float flip, out float incol)
+{
+ float facm;
+ mtex_value_vars(fact, facg, facm, flip);
+
+ float col = fact*texcol;
+ if(col < outcol) incol = col; else incol = outcol;
+}
+
+void mtex_value_light(float outcol, float texcol, float fact, float facg, float flip, out float incol)
+{
+ float facm;
+ mtex_value_vars(fact, facg, facm, flip);
+
+ float col = fact*texcol;
+ if(col > outcol) incol = col; else incol = outcol;
+}
+
+void mtex_value_clamp_positive(float fac, out float outfac)
+{
+ outfac = max(fac, 0.0);
+}
+
+void mtex_value_clamp(float fac, out float outfac)
+{
+ outfac = clamp(fac, 0.0, 1.0);
+}
+
+void mtex_har_divide(float har, out float outhar)
+{
+ outhar = har/128.0;
+}
+
+void mtex_har_multiply_clamp(float har, out float outhar)
+{
+ har *= 128.0;
+
+ if(har < 1.0) outhar = 1.0;
+ else if(har > 511.0) outhar = 511.0;
+ else outhar = har;
+}
+
+void mtex_alpha_from_col(vec4 col, out float alpha)
+{
+ alpha = col.a;
+}
+
+void mtex_alpha_to_col(vec4 col, float alpha, out vec4 outcol)
+{
+ outcol = vec4(col.rgb, alpha);
+}
+
+void mtex_rgbtoint(vec4 rgb, out float intensity)
+{
+ intensity = dot(vec3(0.35, 0.45, 0.2), rgb.rgb);
+}
+
+void mtex_value_invert(float invalue, out float outvalue)
+{
+ outvalue = 1.0 - invalue;
+}
+
+void mtex_rgb_invert(vec4 inrgb, out vec4 outrgb)
+{
+ outrgb = vec4(vec3(1.0) - inrgb.rgb, inrgb.a);
+}
+
+void mtex_value_stencil(float stencil, float intensity, out float outstencil, out float outintensity)
+{
+ float fact = intensity;
+ outintensity = intensity*stencil;
+ outstencil = stencil*fact;
+}
+
+void mtex_rgb_stencil(float stencil, vec4 rgb, out float outstencil, out vec4 outrgb)
+{
+ float fact = rgb.a;
+ outrgb = vec4(rgb.rgb, rgb.a*stencil);
+ outstencil = stencil*fact;
+}
+
+void mtex_mapping_ofs(vec3 texco, vec3 ofs, out vec3 outtexco)
+{
+ outtexco = texco + ofs;
+}
+
+void mtex_mapping_size(vec3 texco, vec3 size, out vec3 outtexco)
+{
+ outtexco = size*texco;
+}
+
+void mtex_2d_mapping(vec3 vec, out vec3 outvec)
+{
+ outvec = vec3(vec.xy*0.5 + vec2(0.5, 0.5), vec.z);
+}
+
+void mtex_image(vec3 vec, sampler2D ima, out float value, out vec4 color, out vec3 normal)
+{
+ color = texture2D(ima, vec.xy);
+ value = 1.0;
+
+ normal = 2.0*(vec3(color.r, -color.g, color.b) - vec3(0.5, -0.5, 0.5));
+}
+
+void mtex_negate_texnormal(vec3 normal, out vec3 outnormal)
+{
+ outnormal = vec3(-normal.x, -normal.y, normal.z);
+}
+
+void mtex_nspace_tangent(vec3 tangent, vec3 normal, vec3 texnormal, out vec3 outnormal)
+{
+ tangent = normalize(tangent);
+ vec3 B = cross(normal, tangent);
+
+ outnormal = texnormal.x*tangent + texnormal.y*B + texnormal.z*normal;
+ outnormal = normalize(outnormal);
+}
+
+void mtex_blend_normal(float norfac, vec3 normal, vec3 newnormal, out vec3 outnormal)
+{
+ outnormal = (1.0 - norfac)*normal + norfac*newnormal;
+ outnormal = normalize(outnormal);
+}
+
+/******* MATERIAL *********/
+
+void lamp_visibility_sun_hemi(vec3 lampvec, out vec3 lv, out float dist, out float visifac)
+{
+ lv = lampvec;
+ dist = 1.0;
+ visifac = 1.0;
+}
+
+void lamp_visibility_other(vec3 co, vec3 lampco, out vec3 lv, out float dist, out float visifac)
+{
+ lv = co - lampco;
+ dist = length(lv);
+ lv = normalize(lv);
+ visifac = 1.0;
+}
+
+void lamp_falloff_invlinear(float lampdist, float dist, out float visifac)
+{
+ visifac = lampdist/(lampdist + dist);
+}
+
+void lamp_falloff_invsquare(float lampdist, float dist, out float visifac)
+{
+ visifac = lampdist/(lampdist + dist*dist);
+}
+
+void lamp_falloff_sliders(float lampdist, float ld1, float ld2, float dist, out float visifac)
+{
+ float lampdistkw = lampdist*lampdist;
+
+ visifac = lampdist/(lampdist + ld1*dist);
+ visifac *= lampdistkw/(lampdistkw + ld2*dist*dist);
+}
+
+void lamp_falloff_curve(float lampdist, sampler1D curvemap, float dist, out float visifac)
+{
+ visifac = texture1D(curvemap, dist/lampdist).x;
+}
+
+void lamp_visibility_sphere(float lampdist, float dist, float visifac, out float outvisifac)
+{
+ float t= lampdist - dist;
+
+ outvisifac= visifac*max(t, 0.0)/lampdist;
+}
+
+void lamp_visibility_spot_square(vec3 lampvec, mat4 lampimat, vec3 lv, out float inpr)
+{
+ if(dot(lv, lampvec) > 0.0) {
+ vec3 lvrot = (lampimat*vec4(lv, 0.0)).xyz;
+ float x = max(abs(lvrot.x/lvrot.z), abs(lvrot.y/lvrot.z));
+
+ inpr = 1.0/sqrt(1.0 + x*x);
+ }
+ else
+ inpr = 0.0;
+}
+
+void lamp_visibility_spot_circle(vec3 lampvec, vec3 lv, out float inpr)
+{
+ inpr = dot(lv, lampvec);
+}
+
+void lamp_visibility_spot(float spotsi, float spotbl, float inpr, float visifac, out float outvisifac)
+{
+ float t = spotsi;
+
+ if(inpr <= t) {
+ outvisifac = 0.0;
+ }
+ else {
+ t = inpr - t;
+
+ /* soft area */
+ if(spotbl != 0.0)
+ inpr *= smoothstep(0.0, 1.0, t/spotbl);
+
+ outvisifac = visifac*inpr;
+ }
+}
+
+void lamp_visibility_clamp(float visifac, out float outvisifac)
+{
+ outvisifac = (visifac < 0.001)? 0.0: visifac;
+}
+
+void shade_view(vec3 co, out vec3 view)
+{
+ /* handle perspective/orthographic */
+ view = (gl_ProjectionMatrix[3][3] == 0.0)? normalize(co): vec3(0.0, 0.0, -1.0);
+}
+
+void shade_tangent_v(vec3 lv, vec3 tang, out vec3 vn)
+{
+ vec3 c = cross(lv, tang);
+ vec3 vnor = cross(c, tang);
+
+ vn = -normalize(vnor);
+}
+
+void shade_inp(vec3 vn, vec3 lv, out float inp)
+{
+ inp = dot(vn, lv);
+}
+
+void shade_is_no_diffuse(out float is)
+{
+ is = 0.0;
+}
+
+void shade_is_hemi(float inp, out float is)
+{
+ is = 0.5*inp + 0.5;
+}
+
+float area_lamp_energy(mat4 area, vec3 co, vec3 vn)
+{
+ vec3 vec[4], c[4];
+ float rad[4], fac;
+
+ vec[0] = normalize(co - area[0].xyz);
+ vec[1] = normalize(co - area[1].xyz);
+ vec[2] = normalize(co - area[2].xyz);
+ vec[3] = normalize(co - area[3].xyz);
+
+ c[0] = normalize(cross(vec[0], vec[1]));
+ c[1] = normalize(cross(vec[1], vec[2]));
+ c[2] = normalize(cross(vec[2], vec[3]));
+ c[3] = normalize(cross(vec[3], vec[0]));
+
+ rad[0] = acos(dot(vec[0], vec[1]));
+ rad[1] = acos(dot(vec[1], vec[2]));
+ rad[2] = acos(dot(vec[2], vec[3]));
+ rad[3] = acos(dot(vec[3], vec[0]));
+
+ fac= rad[0]*dot(vn, c[0]);
+ fac+= rad[1]*dot(vn, c[1]);
+ fac+= rad[2]*dot(vn, c[2]);
+ fac+= rad[3]*dot(vn, c[3]);
+
+ return max(fac, 0.0);
+}
+
+void shade_inp_area(vec3 position, vec3 lampco, vec3 lampvec, vec3 vn, mat4 area, float areasize, float k, out float inp)
+{
+ vec3 co = position;
+ vec3 vec = co - lampco;
+
+ if(dot(vec, lampvec) < 0.0) {
+ inp = 0.0;
+ }
+ else {
+ float intens = area_lamp_energy(area, co, vn);
+
+ inp = pow(intens*areasize, k);
+ }
+}
+
+void shade_diffuse_oren_nayer(float nl, vec3 n, vec3 l, vec3 v, float rough, out float is)
+{
+ vec3 h = normalize(v + l);
+ float nh = max(dot(n, h), 0.0);
+ float nv = max(dot(n, v), 0.0);
+ float realnl = dot(n, l);
+
+ if(realnl < 0.0) {
+ is = 0.0;
+ }
+ else if(nl < 0.0) {
+ is = 0.0;
+ }
+ else {
+ float vh = max(dot(v, h), 0.0);
+ float Lit_A = acos(realnl);
+ float View_A = acos(nv);
+
+ vec3 Lit_B = normalize(l - realnl*n);
+ vec3 View_B = normalize(v - nv*n);
+
+ float t = max(dot(Lit_B, View_B), 0.0);
+
+ float a, b;
+
+ if(Lit_A > View_A) {
+ a = Lit_A;
+ b = View_A;
+ }
+ else {
+ a = View_A;
+ b = Lit_A;
+ }
+
+ float A = 1.0 - (0.5*((rough*rough)/((rough*rough) + 0.33)));
+ float B = 0.45*((rough*rough)/((rough*rough) + 0.09));
+
+ b *= 0.95;
+ is = nl*(A + (B * t * sin(a) * tan(b)));
+ }
+}
+
+void shade_diffuse_toon(vec3 n, vec3 l, vec3 v, float size, float tsmooth, out float is)
+{
+ float rslt = dot(n, l);
+ float ang = acos(rslt);
+
+ if(ang < size) is = 1.0;
+ else if(ang > (size + tsmooth) || tsmooth == 0.0) is = 0.0;
+ else is = 1.0 - ((ang - size)/tsmooth);
+}
+
+void shade_diffuse_minnaert(float nl, vec3 n, vec3 v, float darkness, out float is)
+{
+ if(nl <= 0.0) {
+ is = 0.0;
+ }
+ else {
+ float nv = max(dot(n, v), 0.0);
+
+ if(darkness <= 1.0)
+ is = nl*pow(max(nv*nl, 0.1), darkness - 1.0);
+ else
+ is = nl*pow(1.0001 - nv, darkness - 1.0);
+ }
+}
+
+float fresnel_fac(vec3 view, vec3 vn, float grad, float fac)
+{
+ float t1, t2;
+ float ffac;
+
+ if(fac==0.0) {
+ ffac = 1.0;
+ }
+ else {
+ t1= dot(view, vn);
+ if(t1>0.0) t2= 1.0+t1;
+ else t2= 1.0-t1;
+
+ t2= grad + (1.0-grad)*pow(t2, fac);
+
+ if(t2<0.0) ffac = 0.0;
+ else if(t2>1.0) ffac = 1.0;
+ else ffac = t2;
+ }
+
+ return ffac;
+}
+
+void shade_diffuse_fresnel(vec3 vn, vec3 lv, vec3 view, float fac_i, float fac, out float is)
+{
+ is = fresnel_fac(lv, vn, fac_i, fac);
+}
+
+void shade_cubic(float is, out float outis)
+{
+ if(is>0.0 && is<1.0)
+ outis= smoothstep(0.0, 1.0, is);
+ else
+ outis= is;
+}
+
+void shade_visifac(float i, float visifac, float refl, out float outi)
+{
+ /*if(i > 0.0)*/
+ outi = max(i*visifac*refl, 0.0);
+ /*else
+ outi = i;*/
+}
+
+void shade_tangent_v_spec(vec3 tang, out vec3 vn)
+{
+ vn = tang;
+}
+
+void shade_add_to_diffuse(float i, vec3 lampcol, vec3 col, out vec3 outcol)
+{
+ if(i > 0.0)
+ outcol = i*lampcol*col;
+ else
+ outcol = vec3(0.0, 0.0, 0.0);
+}
+
+void shade_hemi_spec(vec3 vn, vec3 lv, vec3 view, float spec, float hard, float visifac, out float t)
+{
+ lv += view;
+ lv = normalize(lv);
+
+ t = dot(vn, lv);
+ t = 0.5*t + 0.5;
+
+ t = visifac*spec*pow(t, hard);
+}
+
+void shade_phong_spec(vec3 n, vec3 l, vec3 v, float hard, out float specfac)
+{
+ vec3 h = normalize(l + v);
+ float rslt = max(dot(h, n), 0.0);
+
+ specfac = pow(rslt, hard);
+}
+
+void shade_cooktorr_spec(vec3 n, vec3 l, vec3 v, float hard, out float specfac)
+{
+ vec3 h = normalize(v + l);
+ float nh = dot(n, h);
+
+ if(nh < 0.0) {
+ specfac = 0.0;
+ }
+ else {
+ float nv = max(dot(n, v), 0.0);
+ float i = pow(nh, hard);
+
+ i = i/(0.1+nv);
+ specfac = i;
+ }
+}
+
+void shade_blinn_spec(vec3 n, vec3 l, vec3 v, float refrac, float spec_power, out float specfac)
+{
+ if(refrac < 1.0) {
+ specfac = 0.0;
+ }
+ else if(spec_power == 0.0) {
+ specfac = 0.0;
+ }
+ else {
+ if(spec_power<100.0)
+ spec_power= sqrt(1.0/spec_power);
+ else
+ spec_power= 10.0/spec_power;
+
+ vec3 h = normalize(v + l);
+ float nh = dot(n, h);
+ if(nh < 0.0) {
+ specfac = 0.0;
+ }
+ else {
+ float nv = max(dot(n, v), 0.01);
+ float nl = dot(n, l);
+ if(nl <= 0.01) {
+ specfac = 0.0;
+ }
+ else {
+ float vh = max(dot(v, h), 0.01);
+
+ float a = 1.0;
+ float b = (2.0*nh*nv)/vh;
+ float c = (2.0*nh*nl)/vh;
+
+ float g = 0.0;
+
+ if(a < b && a < c) g = a;
+ else if(b < a && b < c) g = b;
+ else if(c < a && c < b) g = c;
+
+ float p = sqrt(((refrac * refrac)+(vh*vh)-1.0));
+ float f = (((p-vh)*(p-vh))/((p+vh)*(p+vh)))*(1.0+((((vh*(p+vh))-1.0)*((vh*(p+vh))-1.0))/(((vh*(p-vh))+1.0)*((vh*(p-vh))+1.0))));
+ float ang = acos(nh);
+
+ specfac = max(f*g*exp_blender((-(ang*ang)/(2.0*spec_power*spec_power))), 0.0);
+ }
+ }
+ }
+}
+
+void shade_wardiso_spec(vec3 n, vec3 l, vec3 v, float rms, out float specfac)
+{
+ vec3 h = normalize(l + v);
+ float nh = max(dot(n, h), 0.001);
+ float nv = max(dot(n, v), 0.001);
+ float nl = max(dot(n, l), 0.001);
+ float angle = tan(acos(nh));
+ float alpha = max(rms, 0.001);
+
+ specfac= nl * (1.0/(4.0*M_PI*alpha*alpha))*(exp_blender(-(angle*angle)/(alpha*alpha))/(sqrt(nv*nl)));
+}
+
+void shade_toon_spec(vec3 n, vec3 l, vec3 v, float size, float tsmooth, out float specfac)
+{
+ vec3 h = normalize(l + v);
+ float rslt = dot(h, n);
+ float ang = acos(rslt);
+
+ if(ang < size) rslt = 1.0;
+ else if(ang >= (size + tsmooth) || tsmooth == 0.0) rslt = 0.0;
+ else rslt = 1.0 - ((ang - size)/tsmooth);
+
+ specfac = rslt;
+}
+
+void shade_spec_area_inp(float specfac, float inp, out float outspecfac)
+{
+ outspecfac = specfac*inp;
+}
+
+void shade_spec_t(float shadfac, float spec, float visifac, float specfac, out float t)
+{
+ t = shadfac*spec*visifac*specfac;
+}
+
+void shade_add_spec(float t, vec3 lampcol, vec3 speccol, out vec3 outcol)
+{
+ outcol = t*lampcol*speccol;
+}
+
+void shade_add(vec4 col1, vec4 col2, out vec4 outcol)
+{
+ outcol = col1 + col2;
+}
+
+void shade_madd(vec4 col, vec4 col1, vec4 col2, out vec4 outcol)
+{
+ outcol = col + col1*col2;
+}
+
+void shade_maddf(vec4 col, float f, vec4 col1, out vec4 outcol)
+{
+ outcol = col + f*col1;
+}
+
+void shade_mul(vec4 col1, vec4 col2, out vec4 outcol)
+{
+ outcol = col1*col2;
+}
+
+void shade_mul_value(float fac, vec4 col, out vec4 outcol)
+{
+ outcol = col*fac;
+}
+
+void shade_obcolor(vec4 col, vec4 obcol, out vec4 outcol)
+{
+ outcol = vec4(col.rgb*obcol.rgb, col.a);
+}
+
+void ramp_rgbtobw(vec3 color, out float outval)
+{
+ outval = color.r*0.3 + color.g*0.58 + color.b*0.12;
+}
+
+void shade_only_shadow(float i, float shadfac, float energy, out float outshadfac)
+{
+ outshadfac = i*energy*(1.0 - shadfac);
+}
+
+void shade_only_shadow_diffuse(float shadfac, vec3 rgb, vec4 diff, out vec4 outdiff)
+{
+ outdiff = diff - vec4(rgb*shadfac, 0.0);
+}
+
+void shade_only_shadow_specular(float shadfac, vec3 specrgb, vec4 spec, out vec4 outspec)
+{
+ outspec = spec - vec4(specrgb*shadfac, 0.0);
+}
+
+void test_shadowbuf(vec3 rco, sampler2DShadow shadowmap, mat4 shadowpersmat, float shadowbias, float inp, out float result)
+{
+ if(inp <= 0.0) {
+ result = 0.0;
+ }
+ else {
+ vec4 co = shadowpersmat*vec4(rco, 1.0);
+
+ //float bias = (1.5 - inp*inp)*shadowbias;
+ co.z -= shadowbias*co.w;
+
+ result = shadow2DProj(shadowmap, co).x;
+ }
+}
+
+void shade_exposure_correct(vec3 col, float linfac, float logfac, out vec3 outcol)
+{
+ outcol = linfac*(1.0 - exp(col*logfac));
+}
+
+void shade_mist_factor(vec3 co, float miststa, float mistdist, float misttype, float misi, out float outfac)
+{
+ float fac, zcor;
+
+ zcor = (gl_ProjectionMatrix[3][3] == 0.0)? length(co): -co[2];
+
+ fac = clamp((zcor-miststa)/mistdist, 0.0, 1.0);
+ if(misttype == 0.0) fac *= fac;
+ else if(misttype == 1.0);
+ else fac = sqrt(fac);
+
+ outfac = 1.0 - (1.0-fac)*(1.0-misi);
+}
+
+void shade_world_mix(vec3 hor, vec4 col, out vec4 outcol)
+{
+ float fac = clamp(col.a, 0.0, 1.0);
+ outcol = vec4(mix(hor, col.rgb, fac), col.a);
+}
+
+void shade_alpha_opaque(vec4 col, out vec4 outcol)
+{
+ outcol = vec4(col.rgb, 1.0);
+}
+
+void shade_alpha_obcolor(vec4 col, vec4 obcol, out vec4 outcol)
+{
+ outcol = vec4(col.rgb, col.a*obcol.a);
+}
+
diff --git a/source/blender/gpu/intern/gpu_shader_material.glsl.c b/source/blender/gpu/intern/gpu_shader_material.glsl.c
new file mode 100644
index 00000000000..8287efe84ea
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_shader_material.glsl.c
@@ -0,0 +1,1032 @@
+/* DataToC output of file <gpu_shader_material_glsl> */
+
+int datatoc_gpu_shader_material_glsl_size= 32828;
+char datatoc_gpu_shader_material_glsl[]= {
+ 10,102,108,111, 97,116, 32,101,120,112, 95, 98,108,101,110,100,101,114, 40,102,108,111, 97,116, 32,102, 41, 10,
+123, 10, 9,114,101,116,117,114,110, 32,112,111,119, 40, 50, 46, 55, 49, 56, 50, 56, 49, 56, 50, 56, 52, 54, 44, 32,102, 41, 59,
+ 10,125, 10, 10,118,111,105,100, 32,114,103, 98, 95,116,111, 95,104,115,118, 40,118,101, 99, 52, 32,114,103, 98, 44, 32,111,117,
+116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32, 99,109, 97,120, 44, 32, 99,109,
+105,110, 44, 32,104, 44, 32,115, 44, 32,118, 44, 32, 99,100,101,108,116, 97, 59, 10, 9,118,101, 99, 51, 32, 99, 59, 10, 10, 9,
+ 99,109, 97,120, 32, 61, 32,109, 97,120, 40,114,103, 98, 91, 48, 93, 44, 32,109, 97,120, 40,114,103, 98, 91, 49, 93, 44, 32,114,
+103, 98, 91, 50, 93, 41, 41, 59, 10, 9, 99,109,105,110, 32, 61, 32,109,105,110, 40,114,103, 98, 91, 48, 93, 44, 32,109,105,110,
+ 40,114,103, 98, 91, 49, 93, 44, 32,114,103, 98, 91, 50, 93, 41, 41, 59, 10, 9, 99,100,101,108,116, 97, 32, 61, 32, 99,109, 97,
+120, 45, 99,109,105,110, 59, 10, 10, 9,118, 32, 61, 32, 99,109, 97,120, 59, 10, 9,105,102, 32, 40, 99,109, 97,120, 33, 61, 48,
+ 46, 48, 41, 10, 9, 9,115, 32, 61, 32, 99,100,101,108,116, 97, 47, 99,109, 97,120, 59, 10, 9,101,108,115,101, 32,123, 10, 9,
+ 9,115, 32, 61, 32, 48, 46, 48, 59, 10, 9, 9,104, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 10, 9,105,102, 32, 40,115, 32,
+ 61, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,104, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10,
+ 9, 9, 99, 32, 61, 32, 40,118,101, 99, 51, 40, 99,109, 97,120, 44, 32, 99,109, 97,120, 44, 32, 99,109, 97,120, 41, 32, 45, 32,
+114,103, 98, 46,120,121,122, 41, 47, 99,100,101,108,116, 97, 59, 10, 10, 9, 9,105,102, 32, 40,114,103, 98, 46,120, 61, 61, 99,
+109, 97,120, 41, 32,104, 32, 61, 32, 99, 91, 50, 93, 32, 45, 32, 99, 91, 49, 93, 59, 10, 9, 9,101,108,115,101, 32,105,102, 32,
+ 40,114,103, 98, 46,121, 61, 61, 99,109, 97,120, 41, 32,104, 32, 61, 32, 50, 46, 48, 32, 43, 32, 99, 91, 48, 93, 32, 45, 32, 32,
+ 99, 91, 50, 93, 59, 10, 9, 9,101,108,115,101, 32,104, 32, 61, 32, 52, 46, 48, 32, 43, 32, 99, 91, 49, 93, 32, 45, 32, 99, 91,
+ 48, 93, 59, 10, 10, 9, 9,104, 32, 47, 61, 32, 54, 46, 48, 59, 10, 10, 9, 9,105,102, 32, 40,104, 60, 48, 46, 48, 41, 10, 9,
+ 9, 9,104, 32, 43, 61, 32, 49, 46, 48, 59, 10, 9,125, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32,118,101, 99, 52, 40,104,
+ 44, 32,115, 44, 32,118, 44, 32,114,103, 98, 46,119, 41, 59, 10,125, 10, 10,118,111,105,100, 32,104,115,118, 95,116,111, 95,114,
+103, 98, 40,118,101, 99, 52, 32,104,115,118, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10,
+ 9,102,108,111, 97,116, 32,105, 44, 32,102, 44, 32,112, 44, 32,113, 44, 32,116, 44, 32,104, 44, 32,115, 44, 32,118, 59, 10, 9,
+118,101, 99, 51, 32,114,103, 98, 59, 10, 10, 9,104, 32, 61, 32,104,115,118, 91, 48, 93, 59, 10, 9,115, 32, 61, 32,104,115,118,
+ 91, 49, 93, 59, 10, 9,118, 32, 61, 32,104,115,118, 91, 50, 93, 59, 10, 10, 9,105,102, 40,115, 61, 61, 48, 46, 48, 41, 32,123,
+ 10, 9, 9,114,103, 98, 32, 61, 32,118,101, 99, 51, 40,118, 44, 32,118, 44, 32,118, 41, 59, 10, 9,125, 10, 9,101,108,115,101,
+ 32,123, 10, 9, 9,105,102, 40,104, 61, 61, 49, 46, 48, 41, 10, 9, 9, 9,104, 32, 61, 32, 48, 46, 48, 59, 10, 9, 9, 10, 9,
+ 9,104, 32, 42, 61, 32, 54, 46, 48, 59, 10, 9, 9,105, 32, 61, 32,102,108,111,111,114, 40,104, 41, 59, 10, 9, 9,102, 32, 61,
+ 32,104, 32, 45, 32,105, 59, 10, 9, 9,114,103, 98, 32, 61, 32,118,101, 99, 51, 40,102, 44, 32,102, 44, 32,102, 41, 59, 10, 9,
+ 9,112, 32, 61, 32,118, 42, 40, 49, 46, 48, 45,115, 41, 59, 10, 9, 9,113, 32, 61, 32,118, 42, 40, 49, 46, 48, 45, 40,115, 42,
+102, 41, 41, 59, 10, 9, 9,116, 32, 61, 32,118, 42, 40, 49, 46, 48, 45, 40,115, 42, 40, 49, 46, 48, 45,102, 41, 41, 41, 59, 10,
+ 9, 9, 10, 9, 9,105,102, 32, 40,105, 32, 61, 61, 32, 48, 46, 48, 41, 32,114,103, 98, 32, 61, 32,118,101, 99, 51, 40,118, 44,
+ 32,116, 44, 32,112, 41, 59, 10, 9, 9,101,108,115,101, 32,105,102, 32, 40,105, 32, 61, 61, 32, 49, 46, 48, 41, 32,114,103, 98,
+ 32, 61, 32,118,101, 99, 51, 40,113, 44, 32,118, 44, 32,112, 41, 59, 10, 9, 9,101,108,115,101, 32,105,102, 32, 40,105, 32, 61,
+ 61, 32, 50, 46, 48, 41, 32,114,103, 98, 32, 61, 32,118,101, 99, 51, 40,112, 44, 32,118, 44, 32,116, 41, 59, 10, 9, 9,101,108,
+115,101, 32,105,102, 32, 40,105, 32, 61, 61, 32, 51, 46, 48, 41, 32,114,103, 98, 32, 61, 32,118,101, 99, 51, 40,112, 44, 32,113,
+ 44, 32,118, 41, 59, 10, 9, 9,101,108,115,101, 32,105,102, 32, 40,105, 32, 61, 61, 32, 52, 46, 48, 41, 32,114,103, 98, 32, 61,
+ 32,118,101, 99, 51, 40,116, 44, 32,112, 44, 32,118, 41, 59, 10, 9, 9,101,108,115,101, 32,114,103, 98, 32, 61, 32,118,101, 99,
+ 51, 40,118, 44, 32,112, 44, 32,113, 41, 59, 10, 9,125, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32,118,101, 99, 52, 40,114,
+103, 98, 44, 32,104,115,118, 46,119, 41, 59, 10,125, 10, 10, 35,100,101,102,105,110,101, 32, 77, 95, 80, 73, 32, 51, 46, 49, 52,
+ 49, 53, 57, 50, 54, 53, 51, 53, 56, 57, 55, 57, 51, 50, 51, 56, 52, 54, 10, 10, 47, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42,
+ 32, 83, 72, 65, 68, 69, 82, 32, 78, 79, 68, 69, 83, 32, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 47, 10, 10,
+118,111,105,100, 32,118, 99,111,108, 95, 97,116,116,114,105, 98,117,116,101, 40,118,101, 99, 52, 32, 97,116,116,118, 99,111,108,
+ 44, 32,111,117,116, 32,118,101, 99, 52, 32,118, 99,111,108, 41, 10,123, 10, 9,118, 99,111,108, 32, 61, 32,118,101, 99, 52, 40,
+ 97,116,116,118, 99,111,108, 46,120, 47, 50, 53, 53, 46, 48, 44, 32, 97,116,116,118, 99,111,108, 46,121, 47, 50, 53, 53, 46, 48,
+ 44, 32, 97,116,116,118, 99,111,108, 46,122, 47, 50, 53, 53, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100,
+ 32,117,118, 95, 97,116,116,114,105, 98,117,116,101, 40,118,101, 99, 50, 32, 97,116,116,117,118, 44, 32,111,117,116, 32,118,101,
+ 99, 51, 32,117,118, 41, 10,123, 10, 9,117,118, 32, 61, 32,118,101, 99, 51, 40, 97,116,116,117,118, 42, 50, 46, 48, 32, 45, 32,
+118,101, 99, 50, 40, 49, 46, 48, 44, 32, 49, 46, 48, 41, 44, 32, 48, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,103,101,
+111,109, 40,118,101, 99, 51, 32, 99,111, 44, 32,118,101, 99, 51, 32,110,111,114, 44, 32,109, 97,116, 52, 32,118,105,101,119,105,
+110,118,109, 97,116, 44, 32,118,101, 99, 51, 32, 97,116,116,111,114, 99,111, 44, 32,118,101, 99, 50, 32, 97,116,116,117,118, 44,
+ 32,118,101, 99, 52, 32, 97,116,116,118, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,103,108,111, 98, 97,108, 44, 32,
+111,117,116, 32,118,101, 99, 51, 32,108,111, 99, 97,108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,118,105,101,119, 44, 32,111,
+117,116, 32,118,101, 99, 51, 32,111,114, 99,111, 44, 32,111,117,116, 32,118,101, 99, 51, 32,117,118, 44, 32,111,117,116, 32,118,
+101, 99, 51, 32,110,111,114,109, 97,108, 44, 32,111,117,116, 32,118,101, 99, 52, 32,118, 99,111,108, 44, 32,111,117,116, 32,102,
+108,111, 97,116, 32,102,114,111,110,116, 98, 97, 99,107, 41, 10,123, 10, 9,108,111, 99, 97,108, 32, 61, 32, 99,111, 59, 10, 9,
+118,105,101,119, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,108,111, 99, 97,108, 41, 59, 10, 9,103,108,111, 98, 97,108,
+ 32, 61, 32, 40,118,105,101,119,105,110,118,109, 97,116, 42,118,101, 99, 52, 40,108,111, 99, 97,108, 44, 32, 49, 46, 48, 41, 41,
+ 46,120,121,122, 59, 10, 9,111,114, 99,111, 32, 61, 32, 97,116,116,111,114, 99,111, 59, 10, 9,117,118, 95, 97,116,116,114,105,
+ 98,117,116,101, 40, 97,116,116,117,118, 44, 32,117,118, 41, 59, 10, 9,110,111,114,109, 97,108, 32, 61, 32, 45,110,111,114,109,
+ 97,108,105,122,101, 40,110,111,114, 41, 59, 9, 47, 42, 32, 98,108,101,110,100,101,114, 32,114,101,110,100,101,114, 32,110,111,
+114,109, 97,108, 32,105,115, 32,110,101,103, 97,116,101,100, 32, 42, 47, 10, 9,118, 99,111,108, 95, 97,116,116,114,105, 98,117,
+116,101, 40, 97,116,116,118, 99,111,108, 44, 32,118, 99,111,108, 41, 59, 10, 9,102,114,111,110,116, 98, 97, 99,107, 32, 61, 32,
+ 49, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,112,112,105,110,103, 40,118,101, 99, 51, 32,118,101, 99, 44, 32,109,
+ 97,116, 52, 32,109, 97,116, 44, 32,118,101, 99, 51, 32,109,105,110,118,101, 99, 44, 32,118,101, 99, 51, 32,109, 97,120,118,101,
+ 99, 44, 32,102,108,111, 97,116, 32,100,111,109,105,110, 44, 32,102,108,111, 97,116, 32,100,111,109, 97,120, 44, 32,111,117,116,
+ 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32, 40,109, 97,116, 32, 42,
+ 32,118,101, 99, 52, 40,118,101, 99, 44, 32, 49, 46, 48, 41, 41, 46,120,121,122, 59, 10, 9,105,102, 40,100,111,109,105,110, 32,
+ 61, 61, 32, 49, 46, 48, 41, 10, 9, 9,111,117,116,118,101, 99, 32, 61, 32,109, 97,120, 40,111,117,116,118,101, 99, 44, 32,109,
+105,110,118,101, 99, 41, 59, 10, 9,105,102, 40,100,111,109, 97,120, 32, 61, 61, 32, 49, 46, 48, 41, 10, 9, 9,111,117,116,118,
+101, 99, 32, 61, 32,109,105,110, 40,111,117,116,118,101, 99, 44, 32,109, 97,120,118,101, 99, 41, 59, 10,125, 10, 10,118,111,105,
+100, 32, 99, 97,109,101,114, 97, 40,118,101, 99, 51, 32, 99,111, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,105,
+101,119, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,100,101,112,116,104, 44, 32,111,117,116, 32,102,108,111, 97,
+116, 32,111,117,116,100,105,115,116, 41, 10,123, 10, 9,111,117,116,100,101,112,116,104, 32, 61, 32, 97, 98,115, 40, 99,111, 46,
+122, 41, 59, 10, 9,111,117,116,100,105,115,116, 32, 61, 32,108,101,110,103,116,104, 40, 99,111, 41, 59, 10, 9,111,117,116,118,
+105,101,119, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40, 99,111, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,
+104, 95, 97,100,100, 40,102,108,111, 97,116, 32,118, 97,108, 49, 44, 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,
+116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,118, 97,108, 49,
+ 32, 43, 32,118, 97,108, 50, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,115,117, 98,116,114, 97, 99,116, 40,102,
+108,111, 97,116, 32,118, 97,108, 49, 44, 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116,
+ 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,118, 97,108, 49, 32, 45, 32,118, 97,108, 50,
+ 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,109,117,108,116,105,112,108,121, 40,102,108,111, 97,116, 32,118, 97,
+108, 49, 44, 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108,
+ 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,118, 97,108, 49, 32, 42, 32,118, 97,108, 50, 59, 10,125, 10, 10,118,111,
+105,100, 32,109, 97,116,104, 95,100,105,118,105,100,101, 40,102,108,111, 97,116, 32,118, 97,108, 49, 44, 32,102,108,111, 97,116,
+ 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,105,102, 32, 40,
+118, 97,108, 50, 32, 61, 61, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116,118, 97,108, 32, 61, 32, 48, 46, 48, 59, 10, 9,101,108,
+115,101, 10, 9, 9,111,117,116,118, 97,108, 32, 61, 32,118, 97,108, 49, 32, 47, 32,118, 97,108, 50, 59, 10,125, 10, 10,118,111,
+105,100, 32,109, 97,116,104, 95,115,105,110,101, 40,102,108,111, 97,116, 32,118, 97,108, 44, 32,111,117,116, 32,102,108,111, 97,
+116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,115,105,110, 40,118, 97,108, 41, 59, 10,
+125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95, 99,111,115,105,110,101, 40,102,108,111, 97,116, 32,118, 97,108, 44, 32,111,
+117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32, 99,111,115,
+ 40,118, 97,108, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,116, 97,110,103,101,110,116, 40,102,108,111, 97,
+116, 32,118, 97,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118,
+ 97,108, 32, 61, 32,116, 97,110, 40,118, 97,108, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95, 97,115,105,110,
+ 40,102,108,111, 97,116, 32,118, 97,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10,
+ 9,105,102, 32, 40,118, 97,108, 32, 60, 61, 32, 49, 46, 48, 32, 38, 38, 32,118, 97,108, 32, 62, 61, 32, 45, 49, 46, 48, 41, 10,
+ 9, 9,111,117,116,118, 97,108, 32, 61, 32, 97,115,105,110, 40,118, 97,108, 41, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,
+116,118, 97,108, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95, 97, 99,111,115, 40,102,108,
+111, 97,116, 32,118, 97,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,105,102,
+ 32, 40,118, 97,108, 32, 60, 61, 32, 49, 46, 48, 32, 38, 38, 32,118, 97,108, 32, 62, 61, 32, 45, 49, 46, 48, 41, 10, 9, 9,111,
+117,116,118, 97,108, 32, 61, 32, 97, 99,111,115, 40,118, 97,108, 41, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116,118, 97,
+108, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95, 97,116, 97,110, 40,102,108,111, 97,116,
+ 32,118, 97,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,
+108, 32, 61, 32, 97,116, 97,110, 40,118, 97,108, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,112,111,119, 40,
+102,108,111, 97,116, 32,118, 97,108, 49, 44, 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,
+116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,105,102, 32, 40,118, 97,108, 49, 32, 62, 61, 32, 48, 46, 48, 41, 10, 9, 9,
+111,117,116,118, 97,108, 32, 61, 32,112,111,119, 40,118, 97,108, 49, 44, 32,118, 97,108, 50, 41, 59, 10, 9,101,108,115,101, 10,
+ 9, 9,111,117,116,118, 97,108, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,108,111,103,
+ 40,102,108,111, 97,116, 32,118, 97,108, 49, 44, 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111,
+ 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,105,102, 40,118, 97,108, 49, 32, 62, 32, 48, 46, 48, 32, 32, 38, 38, 32,
+118, 97,108, 50, 32, 62, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116,118, 97,108, 61, 32,108,111,103, 50, 40,118, 97,108, 49, 41,
+ 32, 47, 32,108,111,103, 50, 40,118, 97,108, 50, 41, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116,118, 97,108, 61, 32, 48,
+ 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,109, 97,120, 40,102,108,111, 97,116, 32,118, 97,108, 49, 44,
+ 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123,
+ 10, 9,111,117,116,118, 97,108, 32, 61, 32,109, 97,120, 40,118, 97,108, 49, 44, 32,118, 97,108, 50, 41, 59, 10,125, 10, 10,118,
+111,105,100, 32,109, 97,116,104, 95,109,105,110, 40,102,108,111, 97,116, 32,118, 97,108, 49, 44, 32,102,108,111, 97,116, 32,118,
+ 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108,
+ 32, 61, 32,109,105,110, 40,118, 97,108, 49, 44, 32,118, 97,108, 50, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104,
+ 95,114,111,117,110,100, 40,102,108,111, 97,116, 32,118, 97,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118,
+ 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 61, 32,102,108,111,111,114, 40,118, 97,108, 32, 43, 32, 48, 46, 53, 41, 59,
+ 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,108,101,115,115, 95,116,104, 97,110, 40,102,108,111, 97,116, 32,118, 97,
+108, 49, 44, 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108,
+ 41, 10,123, 10, 9,105,102, 40,118, 97,108, 49, 32, 60, 32,118, 97,108, 50, 41, 10, 9, 9,111,117,116,118, 97,108, 32, 61, 32,
+ 49, 46, 48, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116,118, 97,108, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,
+105,100, 32,109, 97,116,104, 95,103,114,101, 97,116,101,114, 95,116,104, 97,110, 40,102,108,111, 97,116, 32,118, 97,108, 49, 44,
+ 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123,
+ 10, 9,105,102, 40,118, 97,108, 49, 32, 62, 32,118, 97,108, 50, 41, 10, 9, 9,111,117,116,118, 97,108, 32, 61, 32, 49, 46, 48,
+ 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116,118, 97,108, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,
+115,113,117,101,101,122,101, 40,102,108,111, 97,116, 32,118, 97,108, 44, 32,102,108,111, 97,116, 32,119,105,100,116,104, 44, 32,
+102,108,111, 97,116, 32, 99,101,110,116,101,114, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,
+123, 10, 9,111,117,116,118, 97,108, 32, 61, 32, 49, 46, 48, 47, 40, 49, 46, 48, 32, 43, 32,112,111,119, 40, 50, 46, 55, 49, 56,
+ 50, 56, 49, 56, 51, 44, 32, 45, 40, 40,118, 97,108, 45, 99,101,110,116,101,114, 41, 42,119,105,100,116,104, 41, 41, 41, 59, 10,
+125, 10, 10,118,111,105,100, 32,118,101, 99, 95,109, 97,116,104, 95, 97,100,100, 40,118,101, 99, 51, 32,118, 49, 44, 32,118,101,
+ 99, 51, 32,118, 50, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 44, 32,111,117,116, 32,102,108,111, 97,
+116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32,118, 49, 32, 43, 32,118, 50, 59, 10, 9,
+111,117,116,118, 97,108, 32, 61, 32, 40, 97, 98,115, 40,111,117,116,118,101, 99, 91, 48, 93, 41, 32, 43, 32, 97, 98,115, 40,111,
+117,116,118,101, 99, 91, 49, 93, 41, 32, 43, 32, 97, 98,115, 40,111,117,116,118,101, 99, 91, 50, 93, 41, 41, 47, 51, 46, 48, 59,
+ 10,125, 10, 10,118,111,105,100, 32,118,101, 99, 95,109, 97,116,104, 95,115,117, 98, 40,118,101, 99, 51, 32,118, 49, 44, 32,118,
+101, 99, 51, 32,118, 50, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 44, 32,111,117,116, 32,102,108,111,
+ 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32,118, 49, 32, 45, 32,118, 50, 59, 10,
+ 9,111,117,116,118, 97,108, 32, 61, 32, 40, 97, 98,115, 40,111,117,116,118,101, 99, 91, 48, 93, 41, 32, 43, 32, 97, 98,115, 40,
+111,117,116,118,101, 99, 91, 49, 93, 41, 32, 43, 32, 97, 98,115, 40,111,117,116,118,101, 99, 91, 50, 93, 41, 41, 47, 51, 46, 48,
+ 59, 10,125, 10, 10,118,111,105,100, 32,118,101, 99, 95,109, 97,116,104, 95, 97,118,101,114, 97,103,101, 40,118,101, 99, 51, 32,
+118, 49, 44, 32,118,101, 99, 51, 32,118, 50, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 44, 32,111,117,
+116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32,118, 49, 32, 43,
+ 32,118, 50, 59, 10, 9,111,117,116,118, 97,108, 32, 61, 32,108,101,110,103,116,104, 40,111,117,116,118,101, 99, 41, 59, 10, 9,
+111,117,116,118,101, 99, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,111,117,116,118,101, 99, 41, 59, 10,125, 10, 10,118,
+111,105,100, 32,118,101, 99, 95,109, 97,116,104, 95,100,111,116, 40,118,101, 99, 51, 32,118, 49, 44, 32,118,101, 99, 51, 32,118,
+ 50, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,
+116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32,118,101, 99, 51, 40, 48, 44, 32, 48, 44, 32, 48, 41, 59,
+ 10, 9,111,117,116,118, 97,108, 32, 61, 32,100,111,116, 40,118, 49, 44, 32,118, 50, 41, 59, 10,125, 10, 10,118,111,105,100, 32,
+118,101, 99, 95,109, 97,116,104, 95, 99,114,111,115,115, 40,118,101, 99, 51, 32,118, 49, 44, 32,118,101, 99, 51, 32,118, 50, 44,
+ 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118,
+ 97,108, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32, 99,114,111,115,115, 40,118, 49, 44, 32,118, 50, 41, 59, 10, 9,
+111,117,116,118, 97,108, 32, 61, 32,108,101,110,103,116,104, 40,111,117,116,118,101, 99, 41, 59, 10,125, 10, 10,118,111,105,100,
+ 32,118,101, 99, 95,109, 97,116,104, 95,110,111,114,109, 97,108,105,122,101, 40,118,101, 99, 51, 32,118, 44, 32,111,117,116, 32,
+118,101, 99, 51, 32,111,117,116,118,101, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123,
+ 10, 9,111,117,116,118, 97,108, 32, 61, 32,108,101,110,103,116,104, 40,118, 41, 59, 10, 9,111,117,116,118,101, 99, 32, 61, 32,
+110,111,114,109, 97,108,105,122,101, 40,118, 41, 59, 10,125, 10, 10,118,111,105,100, 32,118,101, 99, 95,109, 97,116,104, 95,110,
+101,103, 97,116,101, 40,118,101, 99, 51, 32,118, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118, 41, 10,123, 10, 9,
+111,117,116,118, 32, 61, 32, 45,118, 59, 10,125, 10, 10,118,111,105,100, 32,110,111,114,109, 97,108, 40,118,101, 99, 51, 32,100,
+105,114, 44, 32,118,101, 99, 51, 32,110,111,114, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,110,111,114, 44, 32,111,
+117,116, 32,102,108,111, 97,116, 32,111,117,116,100,111,116, 41, 10,123, 10, 9,111,117,116,110,111,114, 32, 61, 32,100,105,114,
+ 59, 10, 9,111,117,116,100,111,116, 32, 61, 32, 45,100,111,116, 40,100,105,114, 44, 32,110,111,114, 41, 59, 10,125, 10, 10,118,
+111,105,100, 32, 99,117,114,118,101,115, 95,118,101, 99, 40,118,101, 99, 51, 32,118,101, 99, 44, 32,115, 97,109,112,108,101,114,
+ 49, 68, 32, 99,117,114,118,101,109, 97,112, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 41, 10,123, 10,
+ 9,111,117,116,118,101, 99, 46,120, 32, 61, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118,101,109, 97,112, 44, 32,
+ 40,118,101, 99, 46,120, 32, 43, 32, 49, 46, 48, 41, 42, 48, 46, 53, 41, 46,120, 59, 10, 9,111,117,116,118,101, 99, 46,121, 32,
+ 61, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118,101,109, 97,112, 44, 32, 40,118,101, 99, 46,121, 32, 43, 32, 49,
+ 46, 48, 41, 42, 48, 46, 53, 41, 46,121, 59, 10, 9,111,117,116,118,101, 99, 46,122, 32, 61, 32,116,101,120,116,117,114,101, 49,
+ 68, 40, 99,117,114,118,101,109, 97,112, 44, 32, 40,118,101, 99, 46,122, 32, 43, 32, 49, 46, 48, 41, 42, 48, 46, 53, 41, 46,122,
+ 59, 10,125, 10, 10,118,111,105,100, 32, 99,117,114,118,101,115, 95,114,103, 98, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,115,
+ 97,109,112,108,101,114, 49, 68, 32, 99,117,114,118,101,109, 97,112, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,
+111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 46,114, 32, 61, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118,
+101,109, 97,112, 44, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118,101,109, 97,112, 44, 32, 99,111,108, 46,114, 41,
+ 46, 97, 41, 46,114, 59, 10, 9,111,117,116, 99,111,108, 46,103, 32, 61, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,
+118,101,109, 97,112, 44, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118,101,109, 97,112, 44, 32, 99,111,108, 46,103,
+ 41, 46, 97, 41, 46,103, 59, 10, 9,111,117,116, 99,111,108, 46, 98, 32, 61, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,
+114,118,101,109, 97,112, 44, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118,101,109, 97,112, 44, 32, 99,111,108, 46,
+ 98, 41, 46, 97, 41, 46, 98, 59, 10, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 46, 97, 59, 10,125, 10, 10,118,
+111,105,100, 32,115,101,116, 95,118, 97,108,117,101, 40,102,108,111, 97,116, 32,118, 97,108, 44, 32,111,117,116, 32,102,108,111,
+ 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,118, 97,108, 59, 10,125, 10, 10,118,
+111,105,100, 32,115,101,116, 95,114,103, 98, 40,118,101, 99, 51, 32, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,
+117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,
+115,101,116, 95,114,103, 98, 97, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,
+111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,115,101,116,
+ 95,118, 97,108,117,101, 95,122,101,114,111, 40,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10,
+ 9,111,117,116,118, 97,108, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,115,101,116, 95,118, 97,108,117,101,
+ 95,111,110,101, 40,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108,
+ 32, 61, 32, 49, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,115,101,116, 95,114,103, 98, 95,122,101,114,111, 40,111,117,116,
+ 32,118,101, 99, 51, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,118,101, 99, 51, 40, 48,
+ 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,101,116, 95,114,103, 98, 97, 95,122,101,114,111, 40,111,117,116, 32,118,
+101, 99, 52, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,118,101, 99, 52, 40, 48, 46, 48,
+ 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95, 98,108,101,110,100, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,
+118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,
+117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32,
+ 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 32, 61, 32,109,105,120, 40, 99,111,108, 49, 44, 32, 99,111,108, 50, 44, 32,
+102, 97, 99, 41, 59, 10, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,
+100, 32,109,105,120, 95, 97,100,100, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,
+118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102,
+ 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,
+111,108, 32, 61, 32,109,105,120, 40, 99,111,108, 49, 44, 32, 99,111,108, 49, 32, 43, 32, 99,111,108, 50, 44, 32,102, 97, 99, 41,
+ 59, 10, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,
+120, 95,109,117,108,116, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99,
+ 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32,
+ 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 32,
+ 61, 32,109,105,120, 40, 99,111,108, 49, 44, 32, 99,111,108, 49, 32, 42, 32, 99,111,108, 50, 44, 32,102, 97, 99, 41, 59, 10, 9,
+111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,115,
+ 99,114,101,101,110, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52,
+ 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61,
+ 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,102,108,111, 97,116, 32,102, 97,
+ 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32,118,101, 99, 52, 40,
+ 49, 46, 48, 41, 32, 45, 32, 40,118,101, 99, 52, 40,102, 97, 99,109, 41, 32, 43, 32,102, 97, 99, 42, 40,118,101, 99, 52, 40, 49,
+ 46, 48, 41, 32, 45, 32, 99,111,108, 50, 41, 41, 42, 40,118,101, 99, 52, 40, 49, 46, 48, 41, 32, 45, 32, 99,111,108, 49, 41, 59,
+ 10, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120,
+ 95,111,118,101,114,108, 97,121, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,
+101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97,
+ 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,102,108,111, 97,116,
+ 32,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,
+108, 49, 59, 10, 10, 9,105,102, 40,111,117,116, 99,111,108, 46,114, 32, 60, 32, 48, 46, 53, 41, 10, 9, 9,111,117,116, 99,111,
+108, 46,114, 32, 42, 61, 32,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99, 42, 99,111,108, 50, 46,114, 59, 10, 9,101,
+108,115,101, 10, 9, 9,111,117,116, 99,111,108, 46,114, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40,102, 97, 99,109, 32, 43, 32, 50,
+ 46, 48, 42,102, 97, 99, 42, 40, 49, 46, 48, 32, 45, 32, 99,111,108, 50, 46,114, 41, 41, 42, 40, 49, 46, 48, 32, 45, 32,111,117,
+116, 99,111,108, 46,114, 41, 59, 10, 10, 9,105,102, 40,111,117,116, 99,111,108, 46,103, 32, 60, 32, 48, 46, 53, 41, 10, 9, 9,
+111,117,116, 99,111,108, 46,103, 32, 42, 61, 32,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99, 42, 99,111,108, 50, 46,
+103, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116, 99,111,108, 46,103, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40,102, 97, 99,
+109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99, 42, 40, 49, 46, 48, 32, 45, 32, 99,111,108, 50, 46,103, 41, 41, 42, 40, 49, 46, 48,
+ 32, 45, 32,111,117,116, 99,111,108, 46,103, 41, 59, 10, 10, 9,105,102, 40,111,117,116, 99,111,108, 46, 98, 32, 60, 32, 48, 46,
+ 53, 41, 10, 9, 9,111,117,116, 99,111,108, 46, 98, 32, 42, 61, 32,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99, 42,
+ 99,111,108, 50, 46, 98, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116, 99,111,108, 46, 98, 32, 61, 32, 49, 46, 48, 32, 45,
+ 32, 40,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99, 42, 40, 49, 46, 48, 32, 45, 32, 99,111,108, 50, 46, 98, 41, 41,
+ 42, 40, 49, 46, 48, 32, 45, 32,111,117,116, 99,111,108, 46, 98, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,115,
+117, 98, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,
+108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108,
+ 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 32, 61, 32,109,105,
+120, 40, 99,111,108, 49, 44, 32, 99,111,108, 49, 32, 45, 32, 99,111,108, 50, 44, 32,102, 97, 99, 41, 59, 10, 9,111,117,116, 99,
+111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,100,105,118, 40,102,
+108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,
+111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,
+102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 32, 61, 32, 49, 46,
+ 48, 32, 45, 32,102, 97, 99, 59, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 49, 59, 10, 10, 9,105,102, 40, 99,
+111,108, 50, 46,114, 32, 33, 61, 32, 48, 46, 48, 41, 32,111,117,116, 99,111,108, 46,114, 32, 61, 32,102, 97, 99,109, 42,111,117,
+116, 99,111,108, 46,114, 32, 43, 32,102, 97, 99, 42,111,117,116, 99,111,108, 46,114, 47, 99,111,108, 50, 46,114, 59, 10, 9,105,
+102, 40, 99,111,108, 50, 46,103, 32, 33, 61, 32, 48, 46, 48, 41, 32,111,117,116, 99,111,108, 46,103, 32, 61, 32,102, 97, 99,109,
+ 42,111,117,116, 99,111,108, 46,103, 32, 43, 32,102, 97, 99, 42,111,117,116, 99,111,108, 46,103, 47, 99,111,108, 50, 46,103, 59,
+ 10, 9,105,102, 40, 99,111,108, 50, 46, 98, 32, 33, 61, 32, 48, 46, 48, 41, 32,111,117,116, 99,111,108, 46, 98, 32, 61, 32,102,
+ 97, 99,109, 42,111,117,116, 99,111,108, 46, 98, 32, 43, 32,102, 97, 99, 42,111,117,116, 99,111,108, 46, 98, 47, 99,111,108, 50,
+ 46, 98, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,100,105,102,102, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,
+118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,
+117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32,
+ 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 32, 61, 32,109,105,120, 40, 99,111,108, 49, 44, 32, 97, 98,115, 40, 99,111,
+108, 49, 32, 45, 32, 99,111,108, 50, 41, 44, 32,102, 97, 99, 41, 59, 10, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,
+108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,100, 97,114,107, 40,102,108,111, 97,116, 32,102, 97, 99,
+ 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52,
+ 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48,
+ 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 46,114,103, 98, 32, 61, 32,109,105,110, 40, 99,111,108, 49, 46,114,
+103, 98, 44, 32, 99,111,108, 50, 46,114,103, 98, 42,102, 97, 99, 41, 59, 10, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,
+111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,108,105,103,104,116, 40,102,108,111, 97,116, 32,102,
+ 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101,
+ 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48,
+ 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 46,114,103, 98, 32, 61, 32,109, 97,120, 40, 99,111,108, 49,
+ 46,114,103, 98, 44, 32, 99,111,108, 50, 46,114,103, 98, 42,102, 97, 99, 41, 59, 10, 9,111,117,116, 99,111,108, 46, 97, 32, 61,
+ 32, 99,111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,100,111,100,103,101, 40,102,108,111, 97,116,
+ 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,
+118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44,
+ 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 49, 59, 10, 10, 9,105,102,
+ 40,111,117,116, 99,111,108, 46,114, 32, 33, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,102,108,111, 97,116, 32,116,109,112, 32,
+ 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 42, 99,111,108, 50, 46,114, 59, 10, 9, 9,105,102, 40,116,109,112, 32, 60, 61, 32,
+ 48, 46, 48, 41, 10, 9, 9, 9,111,117,116, 99,111,108, 46,114, 32, 61, 32, 49, 46, 48, 59, 10, 9, 9,101,108,115,101, 32,105,
+102, 40, 40,116,109,112, 32, 61, 32,111,117,116, 99,111,108, 46,114, 47,116,109,112, 41, 32, 62, 32, 49, 46, 48, 41, 10, 9, 9,
+ 9,111,117,116, 99,111,108, 46,114, 32, 61, 32, 49, 46, 48, 59, 10, 9, 9,101,108,115,101, 10, 9, 9, 9,111,117,116, 99,111,
+108, 46,114, 32, 61, 32,116,109,112, 59, 10, 9,125, 10, 9,105,102, 40,111,117,116, 99,111,108, 46,103, 32, 33, 61, 32, 48, 46,
+ 48, 41, 32,123, 10, 9, 9,102,108,111, 97,116, 32,116,109,112, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 42, 99,111,108,
+ 50, 46,103, 59, 10, 9, 9,105,102, 40,116,109,112, 32, 60, 61, 32, 48, 46, 48, 41, 10, 9, 9, 9,111,117,116, 99,111,108, 46,
+103, 32, 61, 32, 49, 46, 48, 59, 10, 9, 9,101,108,115,101, 32,105,102, 40, 40,116,109,112, 32, 61, 32,111,117,116, 99,111,108,
+ 46,103, 47,116,109,112, 41, 32, 62, 32, 49, 46, 48, 41, 10, 9, 9, 9,111,117,116, 99,111,108, 46,103, 32, 61, 32, 49, 46, 48,
+ 59, 10, 9, 9,101,108,115,101, 10, 9, 9, 9,111,117,116, 99,111,108, 46,103, 32, 61, 32,116,109,112, 59, 10, 9,125, 10, 9,
+105,102, 40,111,117,116, 99,111,108, 46, 98, 32, 33, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,102,108,111, 97,116, 32,116,109,
+112, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 42, 99,111,108, 50, 46, 98, 59, 10, 9, 9,105,102, 40,116,109,112, 32, 60,
+ 61, 32, 48, 46, 48, 41, 10, 9, 9, 9,111,117,116, 99,111,108, 46, 98, 32, 61, 32, 49, 46, 48, 59, 10, 9, 9,101,108,115,101,
+ 32,105,102, 40, 40,116,109,112, 32, 61, 32,111,117,116, 99,111,108, 46, 98, 47,116,109,112, 41, 32, 62, 32, 49, 46, 48, 41, 10,
+ 9, 9, 9,111,117,116, 99,111,108, 46, 98, 32, 61, 32, 49, 46, 48, 59, 10, 9, 9,101,108,115,101, 10, 9, 9, 9,111,117,116,
+ 99,111,108, 46, 98, 32, 61, 32,116,109,112, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95, 98,117,114,110,
+ 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50,
+ 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,
+112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,102,108,111, 97,116, 32,116,109,112, 44, 32,102, 97,
+ 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 49, 59,
+ 10, 10, 9,116,109,112, 32, 61, 32,102, 97, 99,109, 32, 43, 32,102, 97, 99, 42, 99,111,108, 50, 46,114, 59, 10, 9,105,102, 40,
+116,109,112, 32, 60, 61, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,108, 46,114, 32, 61, 32, 48, 46, 48, 59, 10, 9,101,
+108,115,101, 32,105,102, 40, 40,116,109,112, 32, 61, 32, 40, 49, 46, 48, 32, 45, 32, 40, 49, 46, 48, 32, 45, 32,111,117,116, 99,
+111,108, 46,114, 41, 47,116,109,112, 41, 41, 32, 60, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,108, 46,114, 32, 61, 32,
+ 48, 46, 48, 59, 10, 9,101,108,115,101, 32,105,102, 40,116,109,112, 32, 62, 32, 49, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,
+108, 46,114, 32, 61, 32, 49, 46, 48, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116, 99,111,108, 46,114, 32, 61, 32,116,109,
+112, 59, 10, 10, 9,116,109,112, 32, 61, 32,102, 97, 99,109, 32, 43, 32,102, 97, 99, 42, 99,111,108, 50, 46,103, 59, 10, 9,105,
+102, 40,116,109,112, 32, 60, 61, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,108, 46,103, 32, 61, 32, 48, 46, 48, 59, 10,
+ 9,101,108,115,101, 32,105,102, 40, 40,116,109,112, 32, 61, 32, 40, 49, 46, 48, 32, 45, 32, 40, 49, 46, 48, 32, 45, 32,111,117,
+116, 99,111,108, 46,103, 41, 47,116,109,112, 41, 41, 32, 60, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,108, 46,103, 32,
+ 61, 32, 48, 46, 48, 59, 10, 9,101,108,115,101, 32,105,102, 40,116,109,112, 32, 62, 32, 49, 46, 48, 41, 10, 9, 9,111,117,116,
+ 99,111,108, 46,103, 32, 61, 32, 49, 46, 48, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116, 99,111,108, 46,103, 32, 61, 32,
+116,109,112, 59, 10, 10, 9,116,109,112, 32, 61, 32,102, 97, 99,109, 32, 43, 32,102, 97, 99, 42, 99,111,108, 50, 46, 98, 59, 10,
+ 9,105,102, 40,116,109,112, 32, 60, 61, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,108, 46, 98, 32, 61, 32, 48, 46, 48,
+ 59, 10, 9,101,108,115,101, 32,105,102, 40, 40,116,109,112, 32, 61, 32, 40, 49, 46, 48, 32, 45, 32, 40, 49, 46, 48, 32, 45, 32,
+111,117,116, 99,111,108, 46, 98, 41, 47,116,109,112, 41, 41, 32, 60, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,108, 46,
+ 98, 32, 61, 32, 48, 46, 48, 59, 10, 9,101,108,115,101, 32,105,102, 40,116,109,112, 32, 62, 32, 49, 46, 48, 41, 10, 9, 9,111,
+117,116, 99,111,108, 46, 98, 32, 61, 32, 49, 46, 48, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116, 99,111,108, 46, 98, 32,
+ 61, 32,116,109,112, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,104,117,101, 40,102,108,111, 97,116, 32,102, 97, 99,
+ 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52,
+ 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48,
+ 44, 32, 49, 46, 48, 41, 59, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59,
+ 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 49, 59, 10, 10, 9,118,101, 99, 52, 32,104,115,118, 44, 32,104,115,
+118, 50, 44, 32,116,109,112, 59, 10, 9,114,103, 98, 95,116,111, 95,104,115,118, 40, 99,111,108, 50, 44, 32,104,115,118, 50, 41,
+ 59, 10, 10, 9,105,102, 40,104,115,118, 50, 46,121, 32, 33, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,114,103, 98, 95,116,111,
+ 95,104,115,118, 40,111,117,116, 99,111,108, 44, 32,104,115,118, 41, 59, 10, 9, 9,104,115,118, 46,120, 32, 61, 32,104,115,118,
+ 50, 46,120, 59, 10, 9, 9,104,115,118, 95,116,111, 95,114,103, 98, 40,104,115,118, 44, 32,116,109,112, 41, 59, 32, 10, 10, 9,
+ 9,111,117,116, 99,111,108, 32, 61, 32,109,105,120, 40,111,117,116, 99,111,108, 44, 32,116,109,112, 44, 32,102, 97, 99, 41, 59,
+ 10, 9, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100,
+ 32,109,105,120, 95,115, 97,116, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,
+101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97,
+ 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,102,108,111, 97,116,
+ 32,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,
+108, 49, 59, 10, 10, 9,118,101, 99, 52, 32,104,115,118, 44, 32,104,115,118, 50, 59, 10, 9,114,103, 98, 95,116,111, 95,104,115,
+118, 40,111,117,116, 99,111,108, 44, 32,104,115,118, 41, 59, 10, 10, 9,105,102, 40,104,115,118, 46,121, 32, 33, 61, 32, 48, 46,
+ 48, 41, 32,123, 10, 9, 9,114,103, 98, 95,116,111, 95,104,115,118, 40, 99,111,108, 50, 44, 32,104,115,118, 50, 41, 59, 10, 10,
+ 9, 9,104,115,118, 46,121, 32, 61, 32,102, 97, 99,109, 42,104,115,118, 46,121, 32, 43, 32,102, 97, 99, 42,104,115,118, 50, 46,
+121, 59, 10, 9, 9,104,115,118, 95,116,111, 95,114,103, 98, 40,104,115,118, 44, 32,111,117,116, 99,111,108, 41, 59, 10, 9,125,
+ 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,118, 97,108, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52,
+ 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,
+108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41,
+ 59, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59, 10, 10, 9,118,101, 99,
+ 52, 32,104,115,118, 44, 32,104,115,118, 50, 59, 10, 9,114,103, 98, 95,116,111, 95,104,115,118, 40, 99,111,108, 49, 44, 32,104,
+115,118, 41, 59, 10, 9,114,103, 98, 95,116,111, 95,104,115,118, 40, 99,111,108, 50, 44, 32,104,115,118, 50, 41, 59, 10, 10, 9,
+104,115,118, 46,122, 32, 61, 32,102, 97, 99,109, 42,104,115,118, 46,122, 32, 43, 32,102, 97, 99, 42,104,115,118, 50, 46,122, 59,
+ 10, 9,104,115,118, 95,116,111, 95,114,103, 98, 40,104,115,118, 44, 32,111,117,116, 99,111,108, 41, 59, 10,125, 10, 10,118,111,
+105,100, 32,109,105,120, 95, 99,111,108,111,114, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108,
+ 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123,
+ 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,102,
+108,111, 97,116, 32,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59, 10, 10, 9,111,117,116, 99,111,108, 32,
+ 61, 32, 99,111,108, 49, 59, 10, 10, 9,118,101, 99, 52, 32,104,115,118, 44, 32,104,115,118, 50, 44, 32,116,109,112, 59, 10, 9,
+114,103, 98, 95,116,111, 95,104,115,118, 40, 99,111,108, 50, 44, 32,104,115,118, 50, 41, 59, 10, 10, 9,105,102, 40,104,115,118,
+ 50, 46,121, 32, 33, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,114,103, 98, 95,116,111, 95,104,115,118, 40,111,117,116, 99,111,
+108, 44, 32,104,115,118, 41, 59, 10, 9, 9,104,115,118, 46,120, 32, 61, 32,104,115,118, 50, 46,120, 59, 10, 9, 9,104,115,118,
+ 46,121, 32, 61, 32,104,115,118, 50, 46,121, 59, 10, 9, 9,104,115,118, 95,116,111, 95,114,103, 98, 40,104,115,118, 44, 32,116,
+109,112, 41, 59, 32, 10, 10, 9, 9,111,117,116, 99,111,108, 32, 61, 32,109,105,120, 40,111,117,116, 99,111,108, 44, 32,116,109,
+112, 44, 32,102, 97, 99, 41, 59, 10, 9, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10, 9,125,
+ 10,125, 10, 10,118,111,105,100, 32,118, 97,108,116,111,114,103, 98, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,115, 97,109,
+112,108,101,114, 49, 68, 32, 99,111,108,111,114,109, 97,112, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108,
+ 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116, 97,108,112,104, 97, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32,
+ 61, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,111,108,111,114,109, 97,112, 44, 32,102, 97, 99, 41, 59, 10, 9,111,117,116,
+ 97,108,112,104, 97, 32, 61, 32,111,117,116, 99,111,108, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,114,103, 98,116,111, 98,
+119, 40,118,101, 99, 52, 32, 99,111,108,111,114, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,
+123, 10, 9,111,117,116,118, 97,108, 32, 61, 32, 99,111,108,111,114, 46,114, 42, 48, 46, 51, 53, 32, 43, 32, 99,111,108,111,114,
+ 46,103, 42, 48, 46, 52, 53, 32, 43, 32, 99,111,108,111,114, 46, 98, 42, 48, 46, 50, 59, 10,125, 10, 10,118,111,105,100, 32,105,
+110,118,101,114,116, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 44, 32,111,117,116, 32,118,
+101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 46,120,121,122, 32, 61, 32,109,105,120, 40,
+ 99,111,108, 46,120,121,122, 44, 32,118,101, 99, 51, 40, 49, 46, 48, 44, 32, 49, 46, 48, 44, 32, 49, 46, 48, 41, 32, 45, 32, 99,
+111,108, 46,120,121,122, 44, 32,102, 97, 99, 41, 59, 10, 9,111,117,116, 99,111,108, 46,119, 32, 61, 32, 99,111,108, 46,119, 59,
+ 10,125, 10, 10,118,111,105,100, 32,104,117,101, 95,115, 97,116, 40,102,108,111, 97,116, 32,104,117,101, 44, 32,102,108,111, 97,
+116, 32,115, 97,116, 44, 32,102,108,111, 97,116, 32,118, 97,108,117,101, 44, 32,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,
+101, 99, 52, 32, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,118,101, 99,
+ 52, 32,104,115,118, 59, 10, 10, 9,114,103, 98, 95,116,111, 95,104,115,118, 40, 99,111,108, 44, 32,104,115,118, 41, 59, 10, 10,
+ 9,104,115,118, 91, 48, 93, 32, 43, 61, 32, 40,104,117,101, 32, 45, 32, 48, 46, 53, 41, 59, 10, 9,105,102, 40,104,115,118, 91,
+ 48, 93, 62, 49, 46, 48, 41, 32,104,115,118, 91, 48, 93, 45, 61, 49, 46, 48, 59, 32,101,108,115,101, 32,105,102, 40,104,115,118,
+ 91, 48, 93, 60, 48, 46, 48, 41, 32,104,115,118, 91, 48, 93, 43, 61, 32, 49, 46, 48, 59, 10, 9,104,115,118, 91, 49, 93, 32, 42,
+ 61, 32,115, 97,116, 59, 10, 9,105,102, 40,104,115,118, 91, 49, 93, 62, 49, 46, 48, 41, 32,104,115,118, 91, 49, 93, 61, 32, 49,
+ 46, 48, 59, 32,101,108,115,101, 32,105,102, 40,104,115,118, 91, 49, 93, 60, 48, 46, 48, 41, 32,104,115,118, 91, 49, 93, 61, 32,
+ 48, 46, 48, 59, 10, 9,104,115,118, 91, 50, 93, 32, 42, 61, 32,118, 97,108,117,101, 59, 10, 9,105,102, 40,104,115,118, 91, 50,
+ 93, 62, 49, 46, 48, 41, 32,104,115,118, 91, 50, 93, 61, 32, 49, 46, 48, 59, 32,101,108,115,101, 32,105,102, 40,104,115,118, 91,
+ 50, 93, 60, 48, 46, 48, 41, 32,104,115,118, 91, 50, 93, 61, 32, 48, 46, 48, 59, 10, 10, 9,104,115,118, 95,116,111, 95,114,103,
+ 98, 40,104,115,118, 44, 32,111,117,116, 99,111,108, 41, 59, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32,109,105,120, 40, 99,
+111,108, 44, 32,111,117,116, 99,111,108, 44, 32,102, 97, 99, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,101,112, 97,114, 97,
+116,101, 95,114,103, 98, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,114, 44, 32,111,117,
+116, 32,102,108,111, 97,116, 32,103, 44, 32,111,117,116, 32,102,108,111, 97,116, 32, 98, 41, 10,123, 10, 9,114, 32, 61, 32, 99,
+111,108, 46,114, 59, 10, 9,103, 32, 61, 32, 99,111,108, 46,103, 59, 10, 9, 98, 32, 61, 32, 99,111,108, 46, 98, 59, 10,125, 10,
+ 10,118,111,105,100, 32, 99,111,109, 98,105,110,101, 95,114,103, 98, 40,102,108,111, 97,116, 32,114, 44, 32,102,108,111, 97,116,
+ 32,103, 44, 32,102,108,111, 97,116, 32, 98, 44, 32,111,117,116, 32,118,101, 99, 52, 32, 99,111,108, 41, 10,123, 10, 9, 99,111,
+108, 32, 61, 32,118,101, 99, 52, 40,114, 44, 32,103, 44, 32, 98, 44, 32, 49, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,
+111,117,116,112,117,116, 95,110,111,100,101, 40,118,101, 99, 52, 32,114,103, 98, 44, 32,102,108,111, 97,116, 32, 97,108,112,104,
+ 97, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116,114,103, 98, 41, 10,123, 10, 9,111,117,116,114,103, 98, 32, 61, 32,
+118,101, 99, 52, 40,114,103, 98, 46,114,103, 98, 44, 32, 97,108,112,104, 97, 41, 59, 10,125, 10, 10, 47, 42, 42, 42, 42, 42, 42,
+ 42, 42, 42, 42, 42, 32, 84, 69, 88, 84, 85, 82, 69, 83, 32, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 47, 10,
+ 10,118,111,105,100, 32,116,101,120,116,117,114,101, 95,102,108,105,112, 95, 98,108,101,110,100, 40,118,101, 99, 51, 32,118,101,
+ 99, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32,
+118,101, 99, 46,121,120,122, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120,116,117,114,101, 95, 98,108,101,110,100, 95,108,
+105,110, 40,118,101, 99, 51, 32,118,101, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123,
+ 10, 9,111,117,116,118, 97,108, 32, 61, 32, 40, 49, 46, 48, 43,118,101, 99, 46,120, 41, 47, 50, 46, 48, 59, 10,125, 10, 10,118,
+111,105,100, 32,116,101,120,116,117,114,101, 95, 98,108,101,110,100, 95,113,117, 97,100, 40,118,101, 99, 51, 32,118,101, 99, 44,
+ 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,109,
+ 97,120, 40, 40, 49, 46, 48, 43,118,101, 99, 46,120, 41, 47, 50, 46, 48, 44, 32, 48, 46, 48, 41, 59, 10, 9,111,117,116,118, 97,
+108, 32, 42, 61, 32,111,117,116,118, 97,108, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120,116,117,114,101, 95,119,111,111,
+100, 95,115,105,110, 40,118,101, 99, 51, 32,118,101, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,118, 97,108,117,101, 44,
+ 32,111,117,116, 32,118,101, 99, 52, 32, 99,111,108,111,114, 44, 32,111,117,116, 32,118,101, 99, 51, 32,110,111,114,109, 97,108,
+ 41, 10,123, 10, 9,102,108,111, 97,116, 32, 97, 32, 61, 32,115,113,114,116, 40,118,101, 99, 46,120, 42,118,101, 99, 46,120, 32,
+ 43, 32,118,101, 99, 46,121, 42,118,101, 99, 46,121, 32, 43, 32,118,101, 99, 46,122, 42,118,101, 99, 46,122, 41, 42, 50, 48, 46,
+ 48, 59, 10, 9,102,108,111, 97,116, 32,119,105, 32, 61, 32, 48, 46, 53, 32, 43, 32, 48, 46, 53, 42,115,105,110, 40, 97, 41, 59,
+ 10, 10, 9,118, 97,108,117,101, 32, 61, 32,119,105, 59, 10, 9, 99,111,108,111,114, 32, 61, 32,118,101, 99, 52, 40,119,105, 44,
+ 32,119,105, 44, 32,119,105, 44, 32, 49, 46, 48, 41, 59, 10, 9,110,111,114,109, 97,108, 32, 61, 32,118,101, 99, 51, 40, 48, 46,
+ 48, 44, 32, 48, 46, 48, 44, 32, 48, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120,116,117,114,101, 95,105,109,
+ 97,103,101, 40,118,101, 99, 51, 32,118,101, 99, 44, 32,115, 97,109,112,108,101,114, 50, 68, 32,105,109, 97, 44, 32,111,117,116,
+ 32,102,108,111, 97,116, 32,118, 97,108,117,101, 44, 32,111,117,116, 32,118,101, 99, 52, 32, 99,111,108,111,114, 44, 32,111,117,
+116, 32,118,101, 99, 51, 32,110,111,114,109, 97,108, 41, 10,123, 10, 9, 99,111,108,111,114, 32, 61, 32,116,101,120,116,117,114,
+101, 50, 68, 40,105,109, 97, 44, 32, 40,118,101, 99, 46,120,121, 32, 43, 32,118,101, 99, 50, 40, 49, 46, 48, 44, 32, 49, 46, 48,
+ 41, 41, 42, 48, 46, 53, 41, 59, 10, 9,118, 97,108,117,101, 32, 61, 32, 49, 46, 48, 59, 10, 10, 9,110,111,114,109, 97,108, 46,
+120, 32, 61, 32, 50, 46, 48, 42, 40, 99,111,108,111,114, 46,114, 32, 45, 32, 48, 46, 53, 41, 59, 10, 9,110,111,114,109, 97,108,
+ 46,121, 32, 61, 32, 50, 46, 48, 42, 40, 48, 46, 53, 32, 45, 32, 99,111,108,111,114, 46,103, 41, 59, 10, 9,110,111,114,109, 97,
+108, 46,122, 32, 61, 32, 50, 46, 48, 42, 40, 99,111,108,111,114, 46, 98, 32, 45, 32, 48, 46, 53, 41, 59, 10,125, 10, 10, 47, 42,
+ 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 32, 77, 84, 69, 88, 32, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42,
+ 42, 42, 42, 47, 10, 10,118,111,105,100, 32,116,101,120, 99,111, 95,111,114, 99,111, 40,118,101, 99, 51, 32, 97,116,116,111,114,
+ 99,111, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,114, 99,111, 41, 10,123, 10, 9,111,114, 99,111, 32, 61, 32, 97,116,116,
+111,114, 99,111, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120, 99,111, 95,117,118, 40,118,101, 99, 50, 32, 97,116,116,117,
+118, 44, 32,111,117,116, 32,118,101, 99, 51, 32,117,118, 41, 10,123, 10, 9, 47, 42, 32,100,105,115, 97, 98,108,101,100, 32,102,
+111,114, 32,110,111,119, 44, 32,119,111,114,107,115, 32,116,111,103,101,116,104,101,114, 32,119,105,116,104, 32,108,101, 97,118,
+105,110,103, 32,111,117,116, 32,109,116,101,120, 95, 50,100, 95,109, 97,112,112,105,110,103, 10, 9, 32, 32, 32,117,118, 32, 61,
+ 32,118,101, 99, 51, 40, 97,116,116,117,118, 42, 50, 46, 48, 32, 45, 32,118,101, 99, 50, 40, 49, 46, 48, 44, 32, 49, 46, 48, 41,
+ 44, 32, 48, 46, 48, 41, 59, 32, 42, 47, 10, 9,117,118, 32, 61, 32,118,101, 99, 51, 40, 97,116,116,117,118, 44, 32, 48, 46, 48,
+ 41, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120, 99,111, 95,110,111,114,109, 40,118,101, 99, 51, 32,110,111,114,109, 97,
+108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,110,111,114,109, 97,108, 41, 10,123, 10, 9, 47, 42, 32, 99,111,114,
+114,101,115,112,111,110,100,115, 32,116,111, 32,115,104,105, 45, 62,111,114,110, 44, 32,119,104,105, 99,104, 32,105,115, 32,110,
+101,103, 97,116,101,100, 32,115,111, 32, 99, 97,110, 99,101,108,115, 10, 9, 32, 32, 32,111,117,116, 32, 98,108,101,110,100,101,
+114, 32,110,111,114,109, 97,108, 32,110,101,103, 97,116,105,111,110, 32, 42, 47, 10, 9,111,117,116,110,111,114,109, 97,108, 32,
+ 61, 32,110,111,114,109, 97,108,105,122,101, 40,110,111,114,109, 97,108, 41, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120,
+ 99,111, 95,116, 97,110,103,101,110,116, 40,118,101, 99, 51, 32,116, 97,110,103,101,110,116, 44, 32,111,117,116, 32,118,101, 99,
+ 51, 32,111,117,116,116, 97,110,103,101,110,116, 41, 10,123, 10, 9,111,117,116,116, 97,110,103,101,110,116, 32, 61, 32,110,111,
+114,109, 97,108,105,122,101, 40,116, 97,110,103,101,110,116, 41, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120, 99,111, 95,
+103,108,111, 98, 97,108, 40,109, 97,116, 52, 32,118,105,101,119,105,110,118,109, 97,116, 44, 32,118,101, 99, 51, 32, 99,111, 44,
+ 32,111,117,116, 32,118,101, 99, 51, 32,103,108,111, 98, 97,108, 41, 10,123, 10, 9,103,108,111, 98, 97,108, 32, 61, 32, 40,118,
+105,101,119,105,110,118,109, 97,116, 42,118,101, 99, 52, 40, 99,111, 44, 32, 49, 46, 48, 41, 41, 46,120,121,122, 59, 10,125, 10,
+ 10,118,111,105,100, 32,116,101,120, 99,111, 95,111, 98,106,101, 99,116, 40,109, 97,116, 52, 32,118,105,101,119,105,110,118,109,
+ 97,116, 44, 32,109, 97,116, 52, 32,111, 98,105,110,118,109, 97,116, 44, 32,118,101, 99, 51, 32, 99,111, 44, 32,111,117,116, 32,
+118,101, 99, 51, 32,111, 98,106,101, 99,116, 41, 10,123, 10, 9,111, 98,106,101, 99,116, 32, 61, 32, 40,111, 98,105,110,118,109,
+ 97,116, 42, 40,118,105,101,119,105,110,118,109, 97,116, 42,118,101, 99, 52, 40, 99,111, 44, 32, 49, 46, 48, 41, 41, 41, 46,120,
+121,122, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120, 99,111, 95,114,101,102,108, 40,118,101, 99, 51, 32,118,110, 44, 32,
+118,101, 99, 51, 32,118,105,101,119, 44, 32,111,117,116, 32,118,101, 99, 51, 32,114,101,102, 41, 10,123, 10, 9,114,101,102, 32,
+ 61, 32,118,105,101,119, 32, 45, 32, 50, 46, 48, 42,100,111,116, 40,118,110, 44, 32,118,105,101,119, 41, 42,118,110, 59, 10,125,
+ 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,110,111,114,109, 40,118,101, 99, 51, 32,110,111,114,109, 97,108, 44, 32,111,
+117,116, 32,118,101, 99, 51, 32,111,117,116,110,111,114,109, 97,108, 41, 10,123, 10, 9, 47, 42, 32, 98,108,101,110,100,101,114,
+ 32,114,101,110,100,101,114, 32,110,111,114,109, 97,108, 32,105,115, 32,110,101,103, 97,116,101,100, 32, 42, 47, 10, 9,111,117,
+116,110,111,114,109, 97,108, 32, 61, 32, 45,110,111,114,109, 97,108,105,122,101, 40,110,111,114,109, 97,108, 41, 59, 10,125, 10,
+ 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95, 98,108,101,110,100, 40,118,101, 99, 51, 32,111,117,116, 99,111,108,
+ 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116,
+ 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,
+102, 97, 99,109, 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, 32, 49, 46,
+ 48, 45,102, 97, 99,116, 59, 10, 10, 9,105,110, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 32, 43, 32,
+102, 97, 99,109, 42,111,117,116, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,109,117,
+108, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,
+116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,
+111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,
+103, 59, 10, 9,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 45,102, 97, 99,103, 59, 10, 10, 9,105,110, 99,111,108, 32, 61, 32, 40,
+102, 97, 99,109, 32, 43, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 41, 42,111,117,116, 99,111,108, 59, 10,125, 10, 10,118,
+111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,115, 99,114,101,101,110, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44,
+ 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,
+102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102,
+ 97, 99,109, 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, 32, 49, 46, 48,
+ 45,102, 97, 99,103, 59, 10, 10, 9,105,110, 99,111,108, 32, 61, 32,118,101, 99, 51, 40, 49, 46, 48, 41, 32, 45, 32, 40,118,101,
+ 99, 51, 40,102, 97, 99,109, 41, 32, 43, 32,102, 97, 99,116, 42, 40,118,101, 99, 51, 40, 49, 46, 48, 41, 32, 45, 32,116,101,120,
+ 99,111,108, 41, 41, 42, 40,118,101, 99, 51, 40, 49, 46, 48, 41, 32, 45, 32,111,117,116, 99,111,108, 41, 59, 10,125, 10, 10,118,
+111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,111,118,101,114,108, 97,121, 40,118,101, 99, 51, 32,111,117,116, 99,111,108,
+ 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116,
+ 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,
+102, 97, 99,109, 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, 32, 49, 46,
+ 48, 45,102, 97, 99,103, 59, 10, 10, 9,105,102, 40,111,117,116, 99,111,108, 46,114, 32, 60, 32, 48, 46, 53, 41, 10, 9, 9,105,
+110, 99,111,108, 46,114, 32, 61, 32,111,117,116, 99,111,108, 46,114, 42, 40,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97,
+ 99,116, 42,116,101,120, 99,111,108, 46,114, 41, 59, 10, 9,101,108,115,101, 10, 9, 9,105,110, 99,111,108, 46,114, 32, 61, 32,
+ 49, 46, 48, 32, 45, 32, 40,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99,116, 42, 40, 49, 46, 48, 32, 45, 32,116,101,
+120, 99,111,108, 46,114, 41, 41, 42, 40, 49, 46, 48, 32, 45, 32,111,117,116, 99,111,108, 46,114, 41, 59, 10, 10, 9,105,102, 40,
+111,117,116, 99,111,108, 46,103, 32, 60, 32, 48, 46, 53, 41, 10, 9, 9,105,110, 99,111,108, 46,103, 32, 61, 32,111,117,116, 99,
+111,108, 46,103, 42, 40,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99,116, 42,116,101,120, 99,111,108, 46,103, 41, 59,
+ 10, 9,101,108,115,101, 10, 9, 9,105,110, 99,111,108, 46,103, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40,102, 97, 99,109, 32, 43,
+ 32, 50, 46, 48, 42,102, 97, 99,116, 42, 40, 49, 46, 48, 32, 45, 32,116,101,120, 99,111,108, 46,103, 41, 41, 42, 40, 49, 46, 48,
+ 32, 45, 32,111,117,116, 99,111,108, 46,103, 41, 59, 10, 10, 9,105,102, 40,111,117,116, 99,111,108, 46, 98, 32, 60, 32, 48, 46,
+ 53, 41, 10, 9, 9,105,110, 99,111,108, 46, 98, 32, 61, 32,111,117,116, 99,111,108, 46, 98, 42, 40,102, 97, 99,109, 32, 43, 32,
+ 50, 46, 48, 42,102, 97, 99,116, 42,116,101,120, 99,111,108, 46, 98, 41, 59, 10, 9,101,108,115,101, 10, 9, 9,105,110, 99,111,
+108, 46, 98, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99,116, 42, 40, 49, 46,
+ 48, 32, 45, 32,116,101,120, 99,111,108, 46, 98, 41, 41, 42, 40, 49, 46, 48, 32, 45, 32,111,117,116, 99,111,108, 46, 98, 41, 59,
+ 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,115,117, 98, 40,118,101, 99, 51, 32,111,117,116, 99,111,
+108, 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,
+116, 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,105,110, 99,111,108,
+ 32, 61, 32, 45,102, 97, 99,116, 42,102, 97, 99,103, 42,116,101,120, 99,111,108, 32, 43, 32,111,117,116, 99,111,108, 59, 10,125,
+ 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95, 97,100,100, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44,
+ 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,
+102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,105,110, 99,111,108, 32, 61,
+ 32,102, 97, 99,116, 42,102, 97, 99,103, 42,116,101,120, 99,111,108, 32, 43, 32,111,117,116, 99,111,108, 59, 10,125, 10, 10,118,
+111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,100,105,118, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44, 32,118,101,
+ 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,
+103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109,
+ 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 45,102, 97,
+ 99,116, 59, 10, 10, 9,105,102, 40,116,101,120, 99,111,108, 46,114, 32, 33, 61, 32, 48, 46, 48, 41, 32,105,110, 99,111,108, 46,
+114, 32, 61, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 46,114, 32, 43, 32,102, 97, 99,116, 42,111,117,116, 99,111,108, 46,
+114, 47,116,101,120, 99,111,108, 46,114, 59, 10, 9,105,102, 40,116,101,120, 99,111,108, 46,103, 32, 33, 61, 32, 48, 46, 48, 41,
+ 32,105,110, 99,111,108, 46,103, 32, 61, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 46,103, 32, 43, 32,102, 97, 99,116, 42,
+111,117,116, 99,111,108, 46,103, 47,116,101,120, 99,111,108, 46,103, 59, 10, 9,105,102, 40,116,101,120, 99,111,108, 46, 98, 32,
+ 33, 61, 32, 48, 46, 48, 41, 32,105,110, 99,111,108, 46, 98, 32, 61, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 46, 98, 32,
+ 43, 32,102, 97, 99,116, 42,111,117,116, 99,111,108, 46, 98, 47,116,101,120, 99,111,108, 46, 98, 59, 10,125, 10, 10,118,111,105,
+100, 32,109,116,101,120, 95,114,103, 98, 95,100,105,102,102, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44, 32,118,101, 99,
+ 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103,
+ 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59,
+ 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 45,102, 97, 99,
+116, 59, 10, 10, 9,105,110, 99,111,108, 32, 61, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 32, 43, 32,102, 97, 99,116, 42,
+ 97, 98,115, 40,116,101,120, 99,111,108, 32, 45, 32,111,117,116, 99,111,108, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,
+101,120, 95,114,103, 98, 95,100, 97,114,107, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44, 32,118,101, 99, 51, 32,116,101,
+120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,111,117,
+116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 44, 32, 99,111,108,
+ 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 45,102, 97,
+ 99,116, 59, 10, 10, 9, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 46,114, 59, 10, 9,105,102, 40, 99,
+111,108, 32, 60, 32,111,117,116, 99,111,108, 46,114, 41, 32,105,110, 99,111,108, 46,114, 32, 61, 32, 99,111,108, 59, 32,101,108,
+115,101, 32,105,110, 99,111,108, 46,114, 32, 61, 32,111,117,116, 99,111,108, 46,114, 59, 10, 9, 99,111,108, 32, 61, 32,102, 97,
+ 99,116, 42,116,101,120, 99,111,108, 46,103, 59, 10, 9,105,102, 40, 99,111,108, 32, 60, 32,111,117,116, 99,111,108, 46,103, 41,
+ 32,105,110, 99,111,108, 46,103, 32, 61, 32, 99,111,108, 59, 32,101,108,115,101, 32,105,110, 99,111,108, 46,103, 32, 61, 32,111,
+117,116, 99,111,108, 46,103, 59, 10, 9, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 46, 98, 59, 10, 9,
+105,102, 40, 99,111,108, 32, 60, 32,111,117,116, 99,111,108, 46, 98, 41, 32,105,110, 99,111,108, 46, 98, 32, 61, 32, 99,111,108,
+ 59, 32,101,108,115,101, 32,105,110, 99,111,108, 46, 98, 32, 61, 32,111,117,116, 99,111,108, 46, 98, 59, 10,125, 10, 10,118,111,
+105,100, 32,109,116,101,120, 95,114,103, 98, 95,108,105,103,104,116, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44, 32,118,
+101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97,
+ 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,
+109, 44, 32, 99,111,108, 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, 32,
+ 49, 46, 48, 45,102, 97, 99,116, 59, 10, 10, 9, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 46,114, 59,
+ 10, 9,105,102, 40, 99,111,108, 32, 62, 32,111,117,116, 99,111,108, 46,114, 41, 32,105,110, 99,111,108, 46,114, 32, 61, 32, 99,
+111,108, 59, 32,101,108,115,101, 32,105,110, 99,111,108, 46,114, 32, 61, 32,111,117,116, 99,111,108, 46,114, 59, 10, 9, 99,111,
+108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 46,103, 59, 10, 9,105,102, 40, 99,111,108, 32, 62, 32,111,117,116,
+ 99,111,108, 46,103, 41, 32,105,110, 99,111,108, 46,103, 32, 61, 32, 99,111,108, 59, 32,101,108,115,101, 32,105,110, 99,111,108,
+ 46,103, 32, 61, 32,111,117,116, 99,111,108, 46,103, 59, 10, 9, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,
+108, 46, 98, 59, 10, 9,105,102, 40, 99,111,108, 32, 62, 32,111,117,116, 99,111,108, 46, 98, 41, 32,105,110, 99,111,108, 46, 98,
+ 32, 61, 32, 99,111,108, 59, 32,101,108,115,101, 32,105,110, 99,111,108, 46, 98, 32, 61, 32,111,117,116, 99,111,108, 46, 98, 59,
+ 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,104,117,101, 40,118,101, 99, 51, 32,111,117,116, 99,111,
+108, 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,
+116, 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,118,101, 99, 52, 32,
+ 99,111,108, 59, 10, 10, 9,109,105,120, 95,104,117,101, 40,102, 97, 99,116, 42,102, 97, 99,103, 44, 32,118,101, 99, 52, 40,111,
+117,116, 99,111,108, 44, 32, 49, 46, 48, 41, 44, 32,118,101, 99, 52, 40,116,101,120, 99,111,108, 44, 32, 49, 46, 48, 41, 44, 32,
+ 99,111,108, 41, 59, 10, 9,105,110, 99,111,108, 46,114,103, 98, 32, 61, 32, 99,111,108, 46,114,103, 98, 59, 10,125, 10, 10,118,
+111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,115, 97,116, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44, 32,118,101,
+ 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,
+103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,118,101, 99, 52, 32, 99,111,108, 59, 10,
+ 10, 9,109,105,120, 95,115, 97,116, 40,102, 97, 99,116, 42,102, 97, 99,103, 44, 32,118,101, 99, 52, 40,111,117,116, 99,111,108,
+ 44, 32, 49, 46, 48, 41, 44, 32,118,101, 99, 52, 40,116,101,120, 99,111,108, 44, 32, 49, 46, 48, 41, 44, 32, 99,111,108, 41, 59,
+ 10, 9,105,110, 99,111,108, 46,114,103, 98, 32, 61, 32, 99,111,108, 46,114,103, 98, 59, 10,125, 10, 10,118,111,105,100, 32,109,
+116,101,120, 95,114,103, 98, 95,118, 97,108, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44, 32,118,101, 99, 51, 32,116,101,
+120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,111,117,
+116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,118,101, 99, 52, 32, 99,111,108, 59, 10, 10, 9,109,105,120,
+ 95,118, 97,108, 40,102, 97, 99,116, 42,102, 97, 99,103, 44, 32,118,101, 99, 52, 40,111,117,116, 99,111,108, 44, 32, 49, 46, 48,
+ 41, 44, 32,118,101, 99, 52, 40,116,101,120, 99,111,108, 44, 32, 49, 46, 48, 41, 44, 32, 99,111,108, 41, 59, 10, 9,105,110, 99,
+111,108, 46,114,103, 98, 32, 61, 32, 99,111,108, 46,114,103, 98, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,
+103, 98, 95, 99,111,108,111,114, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,
+108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,
+101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,118,101, 99, 52, 32, 99,111,108, 59, 10, 10, 9,109,105,120, 95, 99,111,
+108,111,114, 40,102, 97, 99,116, 42,102, 97, 99,103, 44, 32,118,101, 99, 52, 40,111,117,116, 99,111,108, 44, 32, 49, 46, 48, 41,
+ 44, 32,118,101, 99, 52, 40,116,101,120, 99,111,108, 44, 32, 49, 46, 48, 41, 44, 32, 99,111,108, 41, 59, 10, 9,105,110, 99,111,
+108, 46,114,103, 98, 32, 61, 32, 99,111,108, 46,114,103, 98, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,
+108,117,101, 95,118, 97,114,115, 40,105,110,111,117,116, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116,
+ 32,102, 97, 99,103, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,102, 97, 99,109, 44, 32,102,108,111, 97,116, 32,102,108,105,
+112, 41, 10,123, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 45,
+102, 97, 99,116, 59, 10, 10, 9,105,102, 40,102,108,105,112, 32, 33, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,102,108,111, 97,
+116, 32,116,109,112, 32, 61, 32,102, 97, 99,116, 59, 10, 9, 9,102, 97, 99,116, 32, 61, 32,102, 97, 99,109, 59, 10, 9, 9,102,
+ 97, 99,109, 32, 61, 32,116,109,112, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,108,117,101,
+ 95, 98,108,101,110,100, 40,102,108,111, 97,116, 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97,116, 32,116,101,120, 99,111,
+108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,102,108,111, 97,116,
+ 32,102,108,105,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116,
+ 32,102, 97, 99,109, 59, 10, 9,109,116,101,120, 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102, 97, 99,116, 44, 32,102, 97,
+ 99,103, 44, 32,102, 97, 99,109, 44, 32,102,108,105,112, 41, 59, 10, 10, 9,105,110, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,
+116,101,120, 99,111,108, 32, 43, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,
+101,120, 95,118, 97,108,117,101, 95,109,117,108, 40,102,108,111, 97,116, 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97,116,
+ 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44,
+ 32,102,108,111, 97,116, 32,102,108,105,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123, 10,
+ 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 9,109,116,101,120, 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102, 97,
+ 99,116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99,109, 44, 32,102,108,105,112, 41, 59, 10, 10, 9,102, 97, 99,109, 32, 61, 32,
+ 49, 46, 48, 32, 45, 32,102, 97, 99,103, 59, 10, 9,105,110, 99,111,108, 32, 61, 32, 40,102, 97, 99,109, 32, 43, 32,102, 97, 99,
+116, 42,116,101,120, 99,111,108, 41, 42,111,117,116, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118,
+ 97,108,117,101, 95,115, 99,114,101,101,110, 40,102,108,111, 97,116, 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97,116, 32,
+116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,
+102,108,111, 97,116, 32,102,108,105,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123, 10, 9,
+102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 9,109,116,101,120, 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102, 97, 99,
+116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99,109, 44, 32,102,108,105,112, 41, 59, 10, 10, 9,102, 97, 99,109, 32, 61, 32, 49,
+ 46, 48, 32, 45, 32,102, 97, 99,103, 59, 10, 9,105,110, 99,111,108, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40,102, 97, 99,109, 32,
+ 43, 32,102, 97, 99,116, 42, 40, 49, 46, 48, 32, 45, 32,116,101,120, 99,111,108, 41, 41, 42, 40, 49, 46, 48, 32, 45, 32,111,117,
+116, 99,111,108, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,108,117,101, 95,115,117, 98, 40,102,108,
+111, 97,116, 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97,116, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,
+102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,102,108,111, 97,116, 32,102,108,105,112, 44, 32,111,117,
+116, 32,102,108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 9,109,
+116,101,120, 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102, 97, 99,116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99,109, 44,
+ 32,102,108,105,112, 41, 59, 10, 10, 9,102, 97, 99,116, 32, 61, 32, 45,102, 97, 99,116, 59, 10, 9,105,110, 99,111,108, 32, 61,
+ 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 32, 43, 32,111,117,116, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,109,
+116,101,120, 95,118, 97,108,117,101, 95, 97,100,100, 40,102,108,111, 97,116, 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97,
+116, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103,
+ 44, 32,102,108,111, 97,116, 32,102,108,105,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123,
+ 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 9,109,116,101,120, 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102,
+ 97, 99,116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99,109, 44, 32,102,108,105,112, 41, 59, 10, 10, 9,102, 97, 99,116, 32, 61,
+ 32,102, 97, 99,116, 59, 10, 9,105,110, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 32, 43, 32,111,117,
+116, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,108,117,101, 95,100,105,118, 40,102,108,111,
+ 97,116, 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97,116, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102,
+ 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,102,108,111, 97,116, 32,102,108,105,112, 44, 32,111,117,116,
+ 32,102,108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 9,109,116,
+101,120, 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102, 97, 99,116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99,109, 44, 32,
+102,108,105,112, 41, 59, 10, 10, 9,105,102, 40,116,101,120, 99,111,108, 32, 33, 61, 32, 48, 46, 48, 41, 10, 9, 9,105,110, 99,
+111,108, 32, 61, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 32, 43, 32,102, 97, 99,116, 42,111,117,116, 99,111,108, 47,116,
+101,120, 99,111,108, 59, 10, 9,101,108,115,101, 10, 9, 9,105,110, 99,111,108, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,
+111,105,100, 32,109,116,101,120, 95,118, 97,108,117,101, 95,100,105,102,102, 40,102,108,111, 97,116, 32,111,117,116, 99,111,108,
+ 44, 32,102,108,111, 97,116, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,
+116, 32,102, 97, 99,103, 44, 32,102,108,111, 97,116, 32,102,108,105,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110,
+ 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 9,109,116,101,120, 95,118, 97,108,117,101, 95,
+118, 97,114,115, 40,102, 97, 99,116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99,109, 44, 32,102,108,105,112, 41, 59, 10, 10, 9,
+105,110, 99,111,108, 32, 61, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 32, 43, 32,102, 97, 99,116, 42, 97, 98,115, 40,116,
+101,120, 99,111,108, 32, 45, 32,111,117,116, 99,111,108, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,
+108,117,101, 95,100, 97,114,107, 40,102,108,111, 97,116, 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97,116, 32,116,101,120,
+ 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,102,108,111,
+ 97,116, 32,102,108,105,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111,
+ 97,116, 32,102, 97, 99,109, 59, 10, 9,109,116,101,120, 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102, 97, 99,116, 44, 32,
+102, 97, 99,103, 44, 32,102, 97, 99,109, 44, 32,102,108,105,112, 41, 59, 10, 10, 9,102,108,111, 97,116, 32, 99,111,108, 32, 61,
+ 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 59, 10, 9,105,102, 40, 99,111,108, 32, 60, 32,111,117,116, 99,111,108, 41, 32,
+105,110, 99,111,108, 32, 61, 32, 99,111,108, 59, 32,101,108,115,101, 32,105,110, 99,111,108, 32, 61, 32,111,117,116, 99,111,108,
+ 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,108,117,101, 95,108,105,103,104,116, 40,102,108,111, 97,116,
+ 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97,116, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,
+116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,102,108,111, 97,116, 32,102,108,105,112, 44, 32,111,117,116, 32,102,
+108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 9,109,116,101,120,
+ 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102, 97, 99,116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99,109, 44, 32,102,108,
+105,112, 41, 59, 10, 10, 9,102,108,111, 97,116, 32, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 59, 10,
+ 9,105,102, 40, 99,111,108, 32, 62, 32,111,117,116, 99,111,108, 41, 32,105,110, 99,111,108, 32, 61, 32, 99,111,108, 59, 32,101,
+108,115,101, 32,105,110, 99,111,108, 32, 61, 32,111,117,116, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120,
+ 95,118, 97,108,117,101, 95, 99,108, 97,109,112, 95,112,111,115,105,116,105,118,101, 40,102,108,111, 97,116, 32,102, 97, 99, 44,
+ 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,102, 97, 99, 41, 10,123, 10, 9,111,117,116,102, 97, 99, 32, 61, 32,109,
+ 97,120, 40,102, 97, 99, 44, 32, 48, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,108,117,101,
+ 95, 99,108, 97,109,112, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,102,
+ 97, 99, 41, 10,123, 10, 9,111,117,116,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32,
+ 49, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,104, 97,114, 95,100,105,118,105,100,101, 40,102,108,
+111, 97,116, 32,104, 97,114, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,104, 97,114, 41, 10,123, 10, 9,111,117,
+116,104, 97,114, 32, 61, 32,104, 97,114, 47, 49, 50, 56, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,104,
+ 97,114, 95,109,117,108,116,105,112,108,121, 95, 99,108, 97,109,112, 40,102,108,111, 97,116, 32,104, 97,114, 44, 32,111,117,116,
+ 32,102,108,111, 97,116, 32,111,117,116,104, 97,114, 41, 10,123, 10, 9,104, 97,114, 32, 42, 61, 32, 49, 50, 56, 46, 48, 59, 10,
+ 10, 9,105,102, 40,104, 97,114, 32, 60, 32, 49, 46, 48, 41, 32,111,117,116,104, 97,114, 32, 61, 32, 49, 46, 48, 59, 10, 9,101,
+108,115,101, 32,105,102, 40,104, 97,114, 32, 62, 32, 53, 49, 49, 46, 48, 41, 32,111,117,116,104, 97,114, 32, 61, 32, 53, 49, 49,
+ 46, 48, 59, 10, 9,101,108,115,101, 32,111,117,116,104, 97,114, 32, 61, 32,104, 97,114, 59, 10,125, 10, 10,118,111,105,100, 32,
+109,116,101,120, 95, 97,108,112,104, 97, 95,102,114,111,109, 95, 99,111,108, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,111,117,
+116, 32,102,108,111, 97,116, 32, 97,108,112,104, 97, 41, 10,123, 10, 9, 97,108,112,104, 97, 32, 61, 32, 99,111,108, 46, 97, 59,
+ 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95, 97,108,112,104, 97, 95,116,111, 95, 99,111,108, 40,118,101, 99, 52, 32,
+ 99,111,108, 44, 32,102,108,111, 97,116, 32, 97,108,112,104, 97, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,
+108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32,118,101, 99, 52, 40, 99,111,108, 46,114,103, 98, 44, 32, 97,108,112,
+104, 97, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98,116,111,105,110,116, 40,118,101, 99, 52, 32,
+114,103, 98, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110,116,101,110,115,105,116,121, 41, 10,123, 10, 9,105,110,116,
+101,110,115,105,116,121, 32, 61, 32,100,111,116, 40,118,101, 99, 51, 40, 48, 46, 51, 53, 44, 32, 48, 46, 52, 53, 44, 32, 48, 46,
+ 50, 41, 44, 32,114,103, 98, 46,114,103, 98, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,108,117,101,
+ 95,105,110,118,101,114,116, 40,102,108,111, 97,116, 32,105,110,118, 97,108,117,101, 44, 32,111,117,116, 32,102,108,111, 97,116,
+ 32,111,117,116,118, 97,108,117,101, 41, 10,123, 10, 9,111,117,116,118, 97,108,117,101, 32, 61, 32, 49, 46, 48, 32, 45, 32,105,
+110,118, 97,108,117,101, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,105,110,118,101,114,116, 40,
+118,101, 99, 52, 32,105,110,114,103, 98, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116,114,103, 98, 41, 10,123, 10, 9,
+111,117,116,114,103, 98, 32, 61, 32,118,101, 99, 52, 40,118,101, 99, 51, 40, 49, 46, 48, 41, 32, 45, 32,105,110,114,103, 98, 46,
+114,103, 98, 44, 32,105,110,114,103, 98, 46, 97, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,108,117,
+101, 95,115,116,101,110, 99,105,108, 40,102,108,111, 97,116, 32,115,116,101,110, 99,105,108, 44, 32,102,108,111, 97,116, 32,105,
+110,116,101,110,115,105,116,121, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,115,116,101,110, 99,105,108, 44, 32,
+111,117,116, 32,102,108,111, 97,116, 32,111,117,116,105,110,116,101,110,115,105,116,121, 41, 10,123, 10, 9,102,108,111, 97,116,
+ 32,102, 97, 99,116, 32, 61, 32,105,110,116,101,110,115,105,116,121, 59, 10, 9,111,117,116,105,110,116,101,110,115,105,116,121,
+ 32, 61, 32,105,110,116,101,110,115,105,116,121, 42,115,116,101,110, 99,105,108, 59, 10, 9,111,117,116,115,116,101,110, 99,105,
+108, 32, 61, 32,115,116,101,110, 99,105,108, 42,102, 97, 99,116, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,
+103, 98, 95,115,116,101,110, 99,105,108, 40,102,108,111, 97,116, 32,115,116,101,110, 99,105,108, 44, 32,118,101, 99, 52, 32,114,
+103, 98, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,115,116,101,110, 99,105,108, 44, 32,111,117,116, 32,118,101,
+ 99, 52, 32,111,117,116,114,103, 98, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,116, 32, 61, 32,114,103, 98, 46, 97,
+ 59, 10, 9,111,117,116,114,103, 98, 32, 61, 32,118,101, 99, 52, 40,114,103, 98, 46,114,103, 98, 44, 32,114,103, 98, 46, 97, 42,
+115,116,101,110, 99,105,108, 41, 59, 10, 9,111,117,116,115,116,101,110, 99,105,108, 32, 61, 32,115,116,101,110, 99,105,108, 42,
+102, 97, 99,116, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,109, 97,112,112,105,110,103, 95,111,102,115, 40,118,
+101, 99, 51, 32,116,101,120, 99,111, 44, 32,118,101, 99, 51, 32,111,102,115, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,
+116,116,101,120, 99,111, 41, 10,123, 10, 9,111,117,116,116,101,120, 99,111, 32, 61, 32,116,101,120, 99,111, 32, 43, 32,111,102,
+115, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,109, 97,112,112,105,110,103, 95,115,105,122,101, 40,118,101, 99,
+ 51, 32,116,101,120, 99,111, 44, 32,118,101, 99, 51, 32,115,105,122,101, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,
+116,101,120, 99,111, 41, 10,123, 10, 9,111,117,116,116,101,120, 99,111, 32, 61, 32,115,105,122,101, 42,116,101,120, 99,111, 59,
+ 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95, 50,100, 95,109, 97,112,112,105,110,103, 40,118,101, 99, 51, 32,118,101,
+ 99, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32,
+118,101, 99, 51, 40,118,101, 99, 46,120,121, 42, 48, 46, 53, 32, 43, 32,118,101, 99, 50, 40, 48, 46, 53, 44, 32, 48, 46, 53, 41,
+ 44, 32,118,101, 99, 46,122, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,105,109, 97,103,101, 40,118,101, 99,
+ 51, 32,118,101, 99, 44, 32,115, 97,109,112,108,101,114, 50, 68, 32,105,109, 97, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,
+118, 97,108,117,101, 44, 32,111,117,116, 32,118,101, 99, 52, 32, 99,111,108,111,114, 44, 32,111,117,116, 32,118,101, 99, 51, 32,
+110,111,114,109, 97,108, 41, 10,123, 10, 9, 99,111,108,111,114, 32, 61, 32,116,101,120,116,117,114,101, 50, 68, 40,105,109, 97,
+ 44, 32,118,101, 99, 46,120,121, 41, 59, 10, 9,118, 97,108,117,101, 32, 61, 32, 49, 46, 48, 59, 10, 9, 10, 9,110,111,114,109,
+ 97,108, 32, 61, 32, 50, 46, 48, 42, 40,118,101, 99, 51, 40, 99,111,108,111,114, 46,114, 44, 32, 45, 99,111,108,111,114, 46,103,
+ 44, 32, 99,111,108,111,114, 46, 98, 41, 32, 45, 32,118,101, 99, 51, 40, 48, 46, 53, 44, 32, 45, 48, 46, 53, 44, 32, 48, 46, 53,
+ 41, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,110,101,103, 97,116,101, 95,116,101,120,110,111,114,109, 97,
+108, 40,118,101, 99, 51, 32,110,111,114,109, 97,108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,110,111,114,109, 97,
+108, 41, 10,123, 10, 9,111,117,116,110,111,114,109, 97,108, 32, 61, 32,118,101, 99, 51, 40, 45,110,111,114,109, 97,108, 46,120,
+ 44, 32, 45,110,111,114,109, 97,108, 46,121, 44, 32,110,111,114,109, 97,108, 46,122, 41, 59, 10,125, 10, 10,118,111,105,100, 32,
+109,116,101,120, 95,110,115,112, 97, 99,101, 95,116, 97,110,103,101,110,116, 40,118,101, 99, 51, 32,116, 97,110,103,101,110,116,
+ 44, 32,118,101, 99, 51, 32,110,111,114,109, 97,108, 44, 32,118,101, 99, 51, 32,116,101,120,110,111,114,109, 97,108, 44, 32,111,
+117,116, 32,118,101, 99, 51, 32,111,117,116,110,111,114,109, 97,108, 41, 10,123, 10, 9,116, 97,110,103,101,110,116, 32, 61, 32,
+110,111,114,109, 97,108,105,122,101, 40,116, 97,110,103,101,110,116, 41, 59, 10, 9,118,101, 99, 51, 32, 66, 32, 61, 32, 99,114,
+111,115,115, 40,110,111,114,109, 97,108, 44, 32,116, 97,110,103,101,110,116, 41, 59, 10, 10, 9,111,117,116,110,111,114,109, 97,
+108, 32, 61, 32,116,101,120,110,111,114,109, 97,108, 46,120, 42,116, 97,110,103,101,110,116, 32, 43, 32,116,101,120,110,111,114,
+109, 97,108, 46,121, 42, 66, 32, 43, 32,116,101,120,110,111,114,109, 97,108, 46,122, 42,110,111,114,109, 97,108, 59, 10, 9,111,
+117,116,110,111,114,109, 97,108, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,111,117,116,110,111,114,109, 97,108, 41, 59,
+ 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95, 98,108,101,110,100, 95,110,111,114,109, 97,108, 40,102,108,111, 97,116,
+ 32,110,111,114,102, 97, 99, 44, 32,118,101, 99, 51, 32,110,111,114,109, 97,108, 44, 32,118,101, 99, 51, 32,110,101,119,110,111,
+114,109, 97,108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,110,111,114,109, 97,108, 41, 10,123, 10, 9,111,117,116,
+110,111,114,109, 97,108, 32, 61, 32, 40, 49, 46, 48, 32, 45, 32,110,111,114,102, 97, 99, 41, 42,110,111,114,109, 97,108, 32, 43,
+ 32,110,111,114,102, 97, 99, 42,110,101,119,110,111,114,109, 97,108, 59, 10, 9,111,117,116,110,111,114,109, 97,108, 32, 61, 32,
+110,111,114,109, 97,108,105,122,101, 40,111,117,116,110,111,114,109, 97,108, 41, 59, 10,125, 10, 10, 47, 42, 42, 42, 42, 42, 42,
+ 42, 32, 77, 65, 84, 69, 82, 73, 65, 76, 32, 42, 42, 42, 42, 42, 42, 42, 42, 42, 47, 10, 10,118,111,105,100, 32,108, 97,109,112,
+ 95,118,105,115,105, 98,105,108,105,116,121, 95,115,117,110, 95,104,101,109,105, 40,118,101, 99, 51, 32,108, 97,109,112,118,101,
+ 99, 44, 32,111,117,116, 32,118,101, 99, 51, 32,108,118, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,100,105,115,116, 44, 32,
+111,117,116, 32,102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 41, 10,123, 10, 9,108,118, 32, 61, 32,108, 97,109,112,118,
+101, 99, 59, 10, 9,100,105,115,116, 32, 61, 32, 49, 46, 48, 59, 10, 9,118,105,115,105,102, 97, 99, 32, 61, 32, 49, 46, 48, 59,
+ 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,118,105,115,105, 98,105,108,105,116,121, 95,111,116,104,101,114, 40,118,
+101, 99, 51, 32, 99,111, 44, 32,118,101, 99, 51, 32,108, 97,109,112, 99,111, 44, 32,111,117,116, 32,118,101, 99, 51, 32,108,118,
+ 44, 32,111,117,116, 32,102,108,111, 97,116, 32,100,105,115,116, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,118,105,115,105,
+102, 97, 99, 41, 10,123, 10, 9,108,118, 32, 61, 32, 99,111, 32, 45, 32,108, 97,109,112, 99,111, 59, 10, 9,100,105,115,116, 32,
+ 61, 32,108,101,110,103,116,104, 40,108,118, 41, 59, 10, 9,108,118, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,108,118,
+ 41, 59, 10, 9,118,105,115,105,102, 97, 99, 32, 61, 32, 49, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,
+102, 97,108,108,111,102,102, 95,105,110,118,108,105,110,101, 97,114, 40,102,108,111, 97,116, 32,108, 97,109,112,100,105,115,116,
+ 44, 32,102,108,111, 97,116, 32,100,105,115,116, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 41,
+ 10,123, 10, 9,118,105,115,105,102, 97, 99, 32, 61, 32,108, 97,109,112,100,105,115,116, 47, 40,108, 97,109,112,100,105,115,116,
+ 32, 43, 32,100,105,115,116, 41, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,102, 97,108,108,111,102,102, 95,105,
+110,118,115,113,117, 97,114,101, 40,102,108,111, 97,116, 32,108, 97,109,112,100,105,115,116, 44, 32,102,108,111, 97,116, 32,100,
+105,115,116, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 41, 10,123, 10, 9,118,105,115,105,102,
+ 97, 99, 32, 61, 32,108, 97,109,112,100,105,115,116, 47, 40,108, 97,109,112,100,105,115,116, 32, 43, 32,100,105,115,116, 42,100,
+105,115,116, 41, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,102, 97,108,108,111,102,102, 95,115,108,105,100,101,
+114,115, 40,102,108,111, 97,116, 32,108, 97,109,112,100,105,115,116, 44, 32,102,108,111, 97,116, 32,108,100, 49, 44, 32,102,108,
+111, 97,116, 32,108,100, 50, 44, 32,102,108,111, 97,116, 32,100,105,115,116, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,118,
+105,115,105,102, 97, 99, 41, 10,123, 10, 9,102,108,111, 97,116, 32,108, 97,109,112,100,105,115,116,107,119, 32, 61, 32,108, 97,
+109,112,100,105,115,116, 42,108, 97,109,112,100,105,115,116, 59, 10, 10, 9,118,105,115,105,102, 97, 99, 32, 61, 32,108, 97,109,
+112,100,105,115,116, 47, 40,108, 97,109,112,100,105,115,116, 32, 43, 32,108,100, 49, 42,100,105,115,116, 41, 59, 10, 9,118,105,
+115,105,102, 97, 99, 32, 42, 61, 32,108, 97,109,112,100,105,115,116,107,119, 47, 40,108, 97,109,112,100,105,115,116,107,119, 32,
+ 43, 32,108,100, 50, 42,100,105,115,116, 42,100,105,115,116, 41, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,102,
+ 97,108,108,111,102,102, 95, 99,117,114,118,101, 40,102,108,111, 97,116, 32,108, 97,109,112,100,105,115,116, 44, 32,115, 97,109,
+112,108,101,114, 49, 68, 32, 99,117,114,118,101,109, 97,112, 44, 32,102,108,111, 97,116, 32,100,105,115,116, 44, 32,111,117,116,
+ 32,102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 41, 10,123, 10, 9,118,105,115,105,102, 97, 99, 32, 61, 32,116,101,120,
+116,117,114,101, 49, 68, 40, 99,117,114,118,101,109, 97,112, 44, 32,100,105,115,116, 47,108, 97,109,112,100,105,115,116, 41, 46,
+120, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,118,105,115,105, 98,105,108,105,116,121, 95,115,112,104,101,114,
+101, 40,102,108,111, 97,116, 32,108, 97,109,112,100,105,115,116, 44, 32,102,108,111, 97,116, 32,100,105,115,116, 44, 32,102,108,
+111, 97,116, 32,118,105,115,105,102, 97, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118,105,115,105,102, 97,
+ 99, 41, 10,123, 10, 9,102,108,111, 97,116, 32,116, 61, 32,108, 97,109,112,100,105,115,116, 32, 45, 32,100,105,115,116, 59, 10,
+ 10, 9,111,117,116,118,105,115,105,102, 97, 99, 61, 32,118,105,115,105,102, 97, 99, 42,109, 97,120, 40,116, 44, 32, 48, 46, 48,
+ 41, 47,108, 97,109,112,100,105,115,116, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,118,105,115,105, 98,105,108,
+105,116,121, 95,115,112,111,116, 95,115,113,117, 97,114,101, 40,118,101, 99, 51, 32,108, 97,109,112,118,101, 99, 44, 32,109, 97,
+116, 52, 32,108, 97,109,112,105,109, 97,116, 44, 32,118,101, 99, 51, 32,108,118, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,
+105,110,112,114, 41, 10,123, 10, 9,105,102, 40,100,111,116, 40,108,118, 44, 32,108, 97,109,112,118,101, 99, 41, 32, 62, 32, 48,
+ 46, 48, 41, 32,123, 10, 9, 9,118,101, 99, 51, 32,108,118,114,111,116, 32, 61, 32, 40,108, 97,109,112,105,109, 97,116, 42,118,
+101, 99, 52, 40,108,118, 44, 32, 48, 46, 48, 41, 41, 46,120,121,122, 59, 10, 9, 9,102,108,111, 97,116, 32,120, 32, 61, 32,109,
+ 97,120, 40, 97, 98,115, 40,108,118,114,111,116, 46,120, 47,108,118,114,111,116, 46,122, 41, 44, 32, 97, 98,115, 40,108,118,114,
+111,116, 46,121, 47,108,118,114,111,116, 46,122, 41, 41, 59, 10, 10, 9, 9,105,110,112,114, 32, 61, 32, 49, 46, 48, 47,115,113,
+114,116, 40, 49, 46, 48, 32, 43, 32,120, 42,120, 41, 59, 10, 9,125, 10, 9,101,108,115,101, 10, 9, 9,105,110,112,114, 32, 61,
+ 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,118,105,115,105, 98,105,108,105,116,121, 95,115,112,
+111,116, 95, 99,105,114, 99,108,101, 40,118,101, 99, 51, 32,108, 97,109,112,118,101, 99, 44, 32,118,101, 99, 51, 32,108,118, 44,
+ 32,111,117,116, 32,102,108,111, 97,116, 32,105,110,112,114, 41, 10,123, 10, 9,105,110,112,114, 32, 61, 32,100,111,116, 40,108,
+118, 44, 32,108, 97,109,112,118,101, 99, 41, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,118,105,115,105, 98,105,
+108,105,116,121, 95,115,112,111,116, 40,102,108,111, 97,116, 32,115,112,111,116,115,105, 44, 32,102,108,111, 97,116, 32,115,112,
+111,116, 98,108, 44, 32,102,108,111, 97,116, 32,105,110,112,114, 44, 32,102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 44,
+ 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118,105,115,105,102, 97, 99, 41, 10,123, 10, 9,102,108,111, 97,116, 32,
+116, 32, 61, 32,115,112,111,116,115,105, 59, 10, 10, 9,105,102, 40,105,110,112,114, 32, 60, 61, 32,116, 41, 32,123, 10, 9, 9,
+111,117,116,118,105,115,105,102, 97, 99, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10, 9, 9,116,
+ 32, 61, 32,105,110,112,114, 32, 45, 32,116, 59, 10, 10, 9, 9, 47, 42, 32,115,111,102,116, 32, 97,114,101, 97, 32, 42, 47, 10,
+ 9, 9,105,102, 40,115,112,111,116, 98,108, 32, 33, 61, 32, 48, 46, 48, 41, 10, 9, 9, 9,105,110,112,114, 32, 42, 61, 32,115,
+109,111,111,116,104,115,116,101,112, 40, 48, 46, 48, 44, 32, 49, 46, 48, 44, 32,116, 47,115,112,111,116, 98,108, 41, 59, 10, 10,
+ 9, 9,111,117,116,118,105,115,105,102, 97, 99, 32, 61, 32,118,105,115,105,102, 97, 99, 42,105,110,112,114, 59, 10, 9,125, 10,
+125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,118,105,115,105, 98,105,108,105,116,121, 95, 99,108, 97,109,112, 40,102,108,
+111, 97,116, 32,118,105,115,105,102, 97, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118,105,115,105,102, 97,
+ 99, 41, 10,123, 10, 9,111,117,116,118,105,115,105,102, 97, 99, 32, 61, 32, 40,118,105,115,105,102, 97, 99, 32, 60, 32, 48, 46,
+ 48, 48, 49, 41, 63, 32, 48, 46, 48, 58, 32,118,105,115,105,102, 97, 99, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,
+101, 95,118,105,101,119, 40,118,101, 99, 51, 32, 99,111, 44, 32,111,117,116, 32,118,101, 99, 51, 32,118,105,101,119, 41, 10,123,
+ 10, 9, 47, 42, 32,104, 97,110,100,108,101, 32,112,101,114,115,112,101, 99,116,105,118,101, 47,111,114,116,104,111,103,114, 97,
+112,104,105, 99, 32, 42, 47, 10, 9,118,105,101,119, 32, 61, 32, 40,103,108, 95, 80,114,111,106,101, 99,116,105,111,110, 77, 97,
+116,114,105,120, 91, 51, 93, 91, 51, 93, 32, 61, 61, 32, 48, 46, 48, 41, 63, 32,110,111,114,109, 97,108,105,122,101, 40, 99,111,
+ 41, 58, 32,118,101, 99, 51, 40, 48, 46, 48, 44, 32, 48, 46, 48, 44, 32, 45, 49, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100,
+ 32,115,104, 97,100,101, 95,116, 97,110,103,101,110,116, 95,118, 40,118,101, 99, 51, 32,108,118, 44, 32,118,101, 99, 51, 32,116,
+ 97,110,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,118,110, 41, 10,123, 10, 9,118,101, 99, 51, 32, 99, 32, 61, 32, 99,114,
+111,115,115, 40,108,118, 44, 32,116, 97,110,103, 41, 59, 10, 9,118,101, 99, 51, 32,118,110,111,114, 32, 61, 32, 99,114,111,115,
+115, 40, 99, 44, 32,116, 97,110,103, 41, 59, 10, 10, 9,118,110, 32, 61, 32, 45,110,111,114,109, 97,108,105,122,101, 40,118,110,
+111,114, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,105,110,112, 40,118,101, 99, 51, 32,118,110, 44, 32,
+118,101, 99, 51, 32,108,118, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110,112, 41, 10,123, 10, 9,105,110,112, 32, 61,
+ 32,100,111,116, 40,118,110, 44, 32,108,118, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,105,115, 95,110,
+111, 95,100,105,102,102,117,115,101, 40,111,117,116, 32,102,108,111, 97,116, 32,105,115, 41, 10,123, 10, 9,105,115, 32, 61, 32,
+ 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,105,115, 95,104,101,109,105, 40,102,108,111, 97,116,
+ 32,105,110,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,115, 41, 10,123, 10, 9,105,115, 32, 61, 32, 48, 46, 53, 42,
+105,110,112, 32, 43, 32, 48, 46, 53, 59, 10,125, 10, 10,102,108,111, 97,116, 32, 97,114,101, 97, 95,108, 97,109,112, 95,101,110,
+101,114,103,121, 40,109, 97,116, 52, 32, 97,114,101, 97, 44, 32,118,101, 99, 51, 32, 99,111, 44, 32,118,101, 99, 51, 32,118,110,
+ 41, 10,123, 10, 9,118,101, 99, 51, 32,118,101, 99, 91, 52, 93, 44, 32, 99, 91, 52, 93, 59, 10, 9,102,108,111, 97,116, 32,114,
+ 97,100, 91, 52, 93, 44, 32,102, 97, 99, 59, 10, 9, 10, 9,118,101, 99, 91, 48, 93, 32, 61, 32,110,111,114,109, 97,108,105,122,
+101, 40, 99,111, 32, 45, 32, 97,114,101, 97, 91, 48, 93, 46,120,121,122, 41, 59, 10, 9,118,101, 99, 91, 49, 93, 32, 61, 32,110,
+111,114,109, 97,108,105,122,101, 40, 99,111, 32, 45, 32, 97,114,101, 97, 91, 49, 93, 46,120,121,122, 41, 59, 10, 9,118,101, 99,
+ 91, 50, 93, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40, 99,111, 32, 45, 32, 97,114,101, 97, 91, 50, 93, 46,120,121,122,
+ 41, 59, 10, 9,118,101, 99, 91, 51, 93, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40, 99,111, 32, 45, 32, 97,114,101, 97,
+ 91, 51, 93, 46,120,121,122, 41, 59, 10, 10, 9, 99, 91, 48, 93, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40, 99,114,111,
+115,115, 40,118,101, 99, 91, 48, 93, 44, 32,118,101, 99, 91, 49, 93, 41, 41, 59, 10, 9, 99, 91, 49, 93, 32, 61, 32,110,111,114,
+109, 97,108,105,122,101, 40, 99,114,111,115,115, 40,118,101, 99, 91, 49, 93, 44, 32,118,101, 99, 91, 50, 93, 41, 41, 59, 10, 9,
+ 99, 91, 50, 93, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40, 99,114,111,115,115, 40,118,101, 99, 91, 50, 93, 44, 32,118,
+101, 99, 91, 51, 93, 41, 41, 59, 10, 9, 99, 91, 51, 93, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40, 99,114,111,115,115,
+ 40,118,101, 99, 91, 51, 93, 44, 32,118,101, 99, 91, 48, 93, 41, 41, 59, 10, 10, 9,114, 97,100, 91, 48, 93, 32, 61, 32, 97, 99,
+111,115, 40,100,111,116, 40,118,101, 99, 91, 48, 93, 44, 32,118,101, 99, 91, 49, 93, 41, 41, 59, 10, 9,114, 97,100, 91, 49, 93,
+ 32, 61, 32, 97, 99,111,115, 40,100,111,116, 40,118,101, 99, 91, 49, 93, 44, 32,118,101, 99, 91, 50, 93, 41, 41, 59, 10, 9,114,
+ 97,100, 91, 50, 93, 32, 61, 32, 97, 99,111,115, 40,100,111,116, 40,118,101, 99, 91, 50, 93, 44, 32,118,101, 99, 91, 51, 93, 41,
+ 41, 59, 10, 9,114, 97,100, 91, 51, 93, 32, 61, 32, 97, 99,111,115, 40,100,111,116, 40,118,101, 99, 91, 51, 93, 44, 32,118,101,
+ 99, 91, 48, 93, 41, 41, 59, 10, 10, 9,102, 97, 99, 61, 32, 32,114, 97,100, 91, 48, 93, 42,100,111,116, 40,118,110, 44, 32, 99,
+ 91, 48, 93, 41, 59, 10, 9,102, 97, 99, 43, 61, 32,114, 97,100, 91, 49, 93, 42,100,111,116, 40,118,110, 44, 32, 99, 91, 49, 93,
+ 41, 59, 10, 9,102, 97, 99, 43, 61, 32,114, 97,100, 91, 50, 93, 42,100,111,116, 40,118,110, 44, 32, 99, 91, 50, 93, 41, 59, 10,
+ 9,102, 97, 99, 43, 61, 32,114, 97,100, 91, 51, 93, 42,100,111,116, 40,118,110, 44, 32, 99, 91, 51, 93, 41, 59, 10, 10, 9,114,
+101,116,117,114,110, 32,109, 97,120, 40,102, 97, 99, 44, 32, 48, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,
+100,101, 95,105,110,112, 95, 97,114,101, 97, 40,118,101, 99, 51, 32,112,111,115,105,116,105,111,110, 44, 32,118,101, 99, 51, 32,
+108, 97,109,112, 99,111, 44, 32,118,101, 99, 51, 32,108, 97,109,112,118,101, 99, 44, 32,118,101, 99, 51, 32,118,110, 44, 32,109,
+ 97,116, 52, 32, 97,114,101, 97, 44, 32,102,108,111, 97,116, 32, 97,114,101, 97,115,105,122,101, 44, 32,102,108,111, 97,116, 32,
+107, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110,112, 41, 10,123, 10, 9,118,101, 99, 51, 32, 99,111, 32, 61, 32,112,
+111,115,105,116,105,111,110, 59, 10, 9,118,101, 99, 51, 32,118,101, 99, 32, 61, 32, 99,111, 32, 45, 32,108, 97,109,112, 99,111,
+ 59, 10, 10, 9,105,102, 40,100,111,116, 40,118,101, 99, 44, 32,108, 97,109,112,118,101, 99, 41, 32, 60, 32, 48, 46, 48, 41, 32,
+123, 10, 9, 9,105,110,112, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10, 9, 9,102,108,111, 97,
+116, 32,105,110,116,101,110,115, 32, 61, 32, 97,114,101, 97, 95,108, 97,109,112, 95,101,110,101,114,103,121, 40, 97,114,101, 97,
+ 44, 32, 99,111, 44, 32,118,110, 41, 59, 10, 10, 9, 9,105,110,112, 32, 61, 32,112,111,119, 40,105,110,116,101,110,115, 42, 97,
+114,101, 97,115,105,122,101, 44, 32,107, 41, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,100,105,
+102,102,117,115,101, 95,111,114,101,110, 95,110, 97,121,101,114, 40,102,108,111, 97,116, 32,110,108, 44, 32,118,101, 99, 51, 32,
+110, 44, 32,118,101, 99, 51, 32,108, 44, 32,118,101, 99, 51, 32,118, 44, 32,102,108,111, 97,116, 32,114,111,117,103,104, 44, 32,
+111,117,116, 32,102,108,111, 97,116, 32,105,115, 41, 10,123, 10, 9,118,101, 99, 51, 32,104, 32, 61, 32,110,111,114,109, 97,108,
+105,122,101, 40,118, 32, 43, 32,108, 41, 59, 10, 9,102,108,111, 97,116, 32,110,104, 32, 61, 32,109, 97,120, 40,100,111,116, 40,
+110, 44, 32,104, 41, 44, 32, 48, 46, 48, 41, 59, 10, 9,102,108,111, 97,116, 32,110,118, 32, 61, 32,109, 97,120, 40,100,111,116,
+ 40,110, 44, 32,118, 41, 44, 32, 48, 46, 48, 41, 59, 10, 9,102,108,111, 97,116, 32,114,101, 97,108,110,108, 32, 61, 32,100,111,
+116, 40,110, 44, 32,108, 41, 59, 10, 10, 9,105,102, 40,114,101, 97,108,110,108, 32, 60, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,
+105,115, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,105,102, 40,110,108, 32, 60, 32, 48, 46, 48, 41, 32,
+123, 10, 9, 9,105,115, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10, 9, 9,102,108,111, 97,116,
+ 32,118,104, 32, 61, 32,109, 97,120, 40,100,111,116, 40,118, 44, 32,104, 41, 44, 32, 48, 46, 48, 41, 59, 10, 9, 9,102,108,111,
+ 97,116, 32, 76,105,116, 95, 65, 32, 61, 32, 97, 99,111,115, 40,114,101, 97,108,110,108, 41, 59, 10, 9, 9,102,108,111, 97,116,
+ 32, 86,105,101,119, 95, 65, 32, 61, 32, 97, 99,111,115, 40,110,118, 41, 59, 10, 10, 9, 9,118,101, 99, 51, 32, 76,105,116, 95,
+ 66, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,108, 32, 45, 32,114,101, 97,108,110,108, 42,110, 41, 59, 10, 9, 9,118,
+101, 99, 51, 32, 86,105,101,119, 95, 66, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,118, 32, 45, 32,110,118, 42,110, 41,
+ 59, 10, 10, 9, 9,102,108,111, 97,116, 32,116, 32, 61, 32,109, 97,120, 40,100,111,116, 40, 76,105,116, 95, 66, 44, 32, 86,105,
+101,119, 95, 66, 41, 44, 32, 48, 46, 48, 41, 59, 10, 10, 9, 9,102,108,111, 97,116, 32, 97, 44, 32, 98, 59, 10, 10, 9, 9,105,
+102, 40, 76,105,116, 95, 65, 32, 62, 32, 86,105,101,119, 95, 65, 41, 32,123, 10, 9, 9, 9, 97, 32, 61, 32, 76,105,116, 95, 65,
+ 59, 10, 9, 9, 9, 98, 32, 61, 32, 86,105,101,119, 95, 65, 59, 10, 9, 9,125, 10, 9, 9,101,108,115,101, 32,123, 10, 9, 9,
+ 9, 97, 32, 61, 32, 86,105,101,119, 95, 65, 59, 10, 9, 9, 9, 98, 32, 61, 32, 76,105,116, 95, 65, 59, 10, 9, 9,125, 10, 10,
+ 9, 9,102,108,111, 97,116, 32, 65, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40, 48, 46, 53, 42, 40, 40,114,111,117,103,104, 42,114,
+111,117,103,104, 41, 47, 40, 40,114,111,117,103,104, 42,114,111,117,103,104, 41, 32, 43, 32, 48, 46, 51, 51, 41, 41, 41, 59, 10,
+ 9, 9,102,108,111, 97,116, 32, 66, 32, 61, 32, 48, 46, 52, 53, 42, 40, 40,114,111,117,103,104, 42,114,111,117,103,104, 41, 47,
+ 40, 40,114,111,117,103,104, 42,114,111,117,103,104, 41, 32, 43, 32, 48, 46, 48, 57, 41, 41, 59, 10, 10, 9, 9, 98, 32, 42, 61,
+ 32, 48, 46, 57, 53, 59, 10, 9, 9,105,115, 32, 61, 32,110,108, 42, 40, 65, 32, 43, 32, 40, 66, 32, 42, 32,116, 32, 42, 32,115,
+105,110, 40, 97, 41, 32, 42, 32,116, 97,110, 40, 98, 41, 41, 41, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,
+100,101, 95,100,105,102,102,117,115,101, 95,116,111,111,110, 40,118,101, 99, 51, 32,110, 44, 32,118,101, 99, 51, 32,108, 44, 32,
+118,101, 99, 51, 32,118, 44, 32,102,108,111, 97,116, 32,115,105,122,101, 44, 32,102,108,111, 97,116, 32,116,115,109,111,111,116,
+104, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,115, 41, 10,123, 10, 9,102,108,111, 97,116, 32,114,115,108,116, 32, 61,
+ 32,100,111,116, 40,110, 44, 32,108, 41, 59, 10, 9,102,108,111, 97,116, 32, 97,110,103, 32, 61, 32, 97, 99,111,115, 40,114,115,
+108,116, 41, 59, 10, 10, 9,105,102, 40, 97,110,103, 32, 60, 32,115,105,122,101, 41, 32,105,115, 32, 61, 32, 49, 46, 48, 59, 10,
+ 9,101,108,115,101, 32,105,102, 40, 97,110,103, 32, 62, 32, 40,115,105,122,101, 32, 43, 32,116,115,109,111,111,116,104, 41, 32,
+124,124, 32,116,115,109,111,111,116,104, 32, 61, 61, 32, 48, 46, 48, 41, 32,105,115, 32, 61, 32, 48, 46, 48, 59, 10, 9,101,108,
+115,101, 32,105,115, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40, 40, 97,110,103, 32, 45, 32,115,105,122,101, 41, 47,116,115,109,111,
+111,116,104, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,100,105,102,102,117,115,101, 95,109,105,110,110,
+ 97,101,114,116, 40,102,108,111, 97,116, 32,110,108, 44, 32,118,101, 99, 51, 32,110, 44, 32,118,101, 99, 51, 32,118, 44, 32,102,
+108,111, 97,116, 32,100, 97,114,107,110,101,115,115, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,115, 41, 10,123, 10, 9,
+105,102, 40,110,108, 32, 60, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,105,115, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,
+101,108,115,101, 32,123, 10, 9, 9,102,108,111, 97,116, 32,110,118, 32, 61, 32,109, 97,120, 40,100,111,116, 40,110, 44, 32,118,
+ 41, 44, 32, 48, 46, 48, 41, 59, 10, 10, 9, 9,105,102, 40,100, 97,114,107,110,101,115,115, 32, 60, 61, 32, 49, 46, 48, 41, 10,
+ 9, 9, 9,105,115, 32, 61, 32,110,108, 42,112,111,119, 40,109, 97,120, 40,110,118, 42,110,108, 44, 32, 48, 46, 49, 41, 44, 32,
+100, 97,114,107,110,101,115,115, 32, 45, 32, 49, 46, 48, 41, 59, 10, 9, 9,101,108,115,101, 10, 9, 9, 9,105,115, 32, 61, 32,
+110,108, 42,112,111,119, 40, 49, 46, 48, 48, 48, 49, 32, 45, 32,110,118, 44, 32,100, 97,114,107,110,101,115,115, 32, 45, 32, 49,
+ 46, 48, 41, 59, 10, 9,125, 10,125, 10, 10,102,108,111, 97,116, 32,102,114,101,115,110,101,108, 95,102, 97, 99, 40,118,101, 99,
+ 51, 32,118,105,101,119, 44, 32,118,101, 99, 51, 32,118,110, 44, 32,102,108,111, 97,116, 32,103,114, 97,100, 44, 32,102,108,111,
+ 97,116, 32,102, 97, 99, 41, 10,123, 10, 9,102,108,111, 97,116, 32,116, 49, 44, 32,116, 50, 59, 10, 9,102,108,111, 97,116, 32,
+102,102, 97, 99, 59, 10, 10, 9,105,102, 40,102, 97, 99, 61, 61, 48, 46, 48, 41, 32,123, 10, 9, 9,102,102, 97, 99, 32, 61, 32,
+ 49, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10, 9, 9,116, 49, 61, 32,100,111,116, 40,118,105,101,119, 44, 32,
+118,110, 41, 59, 10, 9, 9,105,102, 40,116, 49, 62, 48, 46, 48, 41, 32, 32,116, 50, 61, 32, 49, 46, 48, 43,116, 49, 59, 10, 9,
+ 9,101,108,115,101, 32,116, 50, 61, 32, 49, 46, 48, 45,116, 49, 59, 10, 10, 9, 9,116, 50, 61, 32,103,114, 97,100, 32, 43, 32,
+ 40, 49, 46, 48, 45,103,114, 97,100, 41, 42,112,111,119, 40,116, 50, 44, 32,102, 97, 99, 41, 59, 10, 10, 9, 9,105,102, 40,116,
+ 50, 60, 48, 46, 48, 41, 32,102,102, 97, 99, 32, 61, 32, 48, 46, 48, 59, 10, 9, 9,101,108,115,101, 32,105,102, 40,116, 50, 62,
+ 49, 46, 48, 41, 32,102,102, 97, 99, 32, 61, 32, 49, 46, 48, 59, 10, 9, 9,101,108,115,101, 32,102,102, 97, 99, 32, 61, 32,116,
+ 50, 59, 10, 9,125, 10, 10, 9,114,101,116,117,114,110, 32,102,102, 97, 99, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,
+100,101, 95,100,105,102,102,117,115,101, 95,102,114,101,115,110,101,108, 40,118,101, 99, 51, 32,118,110, 44, 32,118,101, 99, 51,
+ 32,108,118, 44, 32,118,101, 99, 51, 32,118,105,101,119, 44, 32,102,108,111, 97,116, 32,102, 97, 99, 95,105, 44, 32,102,108,111,
+ 97,116, 32,102, 97, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,115, 41, 10,123, 10, 9,105,115, 32, 61, 32,102,114,
+101,115,110,101,108, 95,102, 97, 99, 40,108,118, 44, 32,118,110, 44, 32,102, 97, 99, 95,105, 44, 32,102, 97, 99, 41, 59, 10,125,
+ 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95, 99,117, 98,105, 99, 40,102,108,111, 97,116, 32,105,115, 44, 32,111,117,116,
+ 32,102,108,111, 97,116, 32,111,117,116,105,115, 41, 10,123, 10, 9,105,102, 40,105,115, 62, 48, 46, 48, 32, 38, 38, 32,105,115,
+ 60, 49, 46, 48, 41, 10, 9, 9,111,117,116,105,115, 61, 32,115,109,111,111,116,104,115,116,101,112, 40, 48, 46, 48, 44, 32, 49,
+ 46, 48, 44, 32,105,115, 41, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116,105,115, 61, 32,105,115, 59, 10,125, 10, 10,118,
+111,105,100, 32,115,104, 97,100,101, 95,118,105,115,105,102, 97, 99, 40,102,108,111, 97,116, 32,105, 44, 32,102,108,111, 97,116,
+ 32,118,105,115,105,102, 97, 99, 44, 32,102,108,111, 97,116, 32,114,101,102,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,
+111,117,116,105, 41, 10,123, 10, 9, 47, 42,105,102, 40,105, 32, 62, 32, 48, 46, 48, 41, 42, 47, 10, 9, 9,111,117,116,105, 32,
+ 61, 32,109, 97,120, 40,105, 42,118,105,115,105,102, 97, 99, 42,114,101,102,108, 44, 32, 48, 46, 48, 41, 59, 10, 9, 47, 42,101,
+108,115,101, 10, 9, 9,111,117,116,105, 32, 61, 32,105, 59, 42, 47, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,
+116, 97,110,103,101,110,116, 95,118, 95,115,112,101, 99, 40,118,101, 99, 51, 32,116, 97,110,103, 44, 32,111,117,116, 32,118,101,
+ 99, 51, 32,118,110, 41, 10,123, 10, 9,118,110, 32, 61, 32,116, 97,110,103, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,
+100,101, 95, 97,100,100, 95,116,111, 95,100,105,102,102,117,115,101, 40,102,108,111, 97,116, 32,105, 44, 32,118,101, 99, 51, 32,
+108, 97,109,112, 99,111,108, 44, 32,118,101, 99, 51, 32, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116, 99,
+111,108, 41, 10,123, 10, 9,105,102, 40,105, 32, 62, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,108, 32, 61, 32,105, 42,
+108, 97,109,112, 99,111,108, 42, 99,111,108, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116, 99,111,108, 32, 61, 32,118,101,
+ 99, 51, 40, 48, 46, 48, 44, 32, 48, 46, 48, 44, 32, 48, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101,
+ 95,104,101,109,105, 95,115,112,101, 99, 40,118,101, 99, 51, 32,118,110, 44, 32,118,101, 99, 51, 32,108,118, 44, 32,118,101, 99,
+ 51, 32,118,105,101,119, 44, 32,102,108,111, 97,116, 32,115,112,101, 99, 44, 32,102,108,111, 97,116, 32,104, 97,114,100, 44, 32,
+102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,116, 41, 10,123, 10, 9,108,
+118, 32, 43, 61, 32,118,105,101,119, 59, 10, 9,108,118, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,108,118, 41, 59, 10,
+ 10, 9,116, 32, 61, 32,100,111,116, 40,118,110, 44, 32,108,118, 41, 59, 10, 9,116, 32, 61, 32, 48, 46, 53, 42,116, 32, 43, 32,
+ 48, 46, 53, 59, 10, 10, 9,116, 32, 61, 32,118,105,115,105,102, 97, 99, 42,115,112,101, 99, 42,112,111,119, 40,116, 44, 32,104,
+ 97,114,100, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,112,104,111,110,103, 95,115,112,101, 99, 40,118,
+101, 99, 51, 32,110, 44, 32,118,101, 99, 51, 32,108, 44, 32,118,101, 99, 51, 32,118, 44, 32,102,108,111, 97,116, 32,104, 97,114,
+100, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,115,112,101, 99,102, 97, 99, 41, 10,123, 10, 9,118,101, 99, 51, 32,104, 32,
+ 61, 32,110,111,114,109, 97,108,105,122,101, 40,108, 32, 43, 32,118, 41, 59, 10, 9,102,108,111, 97,116, 32,114,115,108,116, 32,
+ 61, 32,109, 97,120, 40,100,111,116, 40,104, 44, 32,110, 41, 44, 32, 48, 46, 48, 41, 59, 10, 10, 9,115,112,101, 99,102, 97, 99,
+ 32, 61, 32,112,111,119, 40,114,115,108,116, 44, 32,104, 97,114,100, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,
+101, 95, 99,111,111,107,116,111,114,114, 95,115,112,101, 99, 40,118,101, 99, 51, 32,110, 44, 32,118,101, 99, 51, 32,108, 44, 32,
+118,101, 99, 51, 32,118, 44, 32,102,108,111, 97,116, 32,104, 97,114,100, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,115,112,
+101, 99,102, 97, 99, 41, 10,123, 10, 9,118,101, 99, 51, 32,104, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,118, 32, 43,
+ 32,108, 41, 59, 10, 9,102,108,111, 97,116, 32,110,104, 32, 61, 32,100,111,116, 40,110, 44, 32,104, 41, 59, 10, 10, 9,105,102,
+ 40,110,104, 32, 60, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,115,112,101, 99,102, 97, 99, 32, 61, 32, 48, 46, 48, 59, 10, 9,125,
+ 10, 9,101,108,115,101, 32,123, 10, 9, 9,102,108,111, 97,116, 32,110,118, 32, 61, 32,109, 97,120, 40,100,111,116, 40,110, 44,
+ 32,118, 41, 44, 32, 48, 46, 48, 41, 59, 10, 9, 9,102,108,111, 97,116, 32,105, 32, 61, 32,112,111,119, 40,110,104, 44, 32,104,
+ 97,114,100, 41, 59, 10, 10, 9, 9,105, 32, 61, 32,105, 47, 40, 48, 46, 49, 43,110,118, 41, 59, 10, 9, 9,115,112,101, 99,102,
+ 97, 99, 32, 61, 32,105, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95, 98,108,105,110,110, 95,115,
+112,101, 99, 40,118,101, 99, 51, 32,110, 44, 32,118,101, 99, 51, 32,108, 44, 32,118,101, 99, 51, 32,118, 44, 32,102,108,111, 97,
+116, 32,114,101,102,114, 97, 99, 44, 32,102,108,111, 97,116, 32,115,112,101, 99, 95,112,111,119,101,114, 44, 32,111,117,116, 32,
+102,108,111, 97,116, 32,115,112,101, 99,102, 97, 99, 41, 10,123, 10, 9,105,102, 40,114,101,102,114, 97, 99, 32, 60, 32, 49, 46,
+ 48, 41, 32,123, 10, 9, 9,115,112,101, 99,102, 97, 99, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,105,
+102, 40,115,112,101, 99, 95,112,111,119,101,114, 32, 61, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,115,112,101, 99,102, 97, 99,
+ 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10, 9, 9,105,102, 40,115,112,101, 99, 95,112,111,119,
+101,114, 60, 49, 48, 48, 46, 48, 41, 10, 9, 9, 9,115,112,101, 99, 95,112,111,119,101,114, 61, 32,115,113,114,116, 40, 49, 46,
+ 48, 47,115,112,101, 99, 95,112,111,119,101,114, 41, 59, 10, 9, 9,101,108,115,101, 10, 9, 9, 9,115,112,101, 99, 95,112,111,
+119,101,114, 61, 32, 49, 48, 46, 48, 47,115,112,101, 99, 95,112,111,119,101,114, 59, 10, 10, 9, 9,118,101, 99, 51, 32,104, 32,
+ 61, 32,110,111,114,109, 97,108,105,122,101, 40,118, 32, 43, 32,108, 41, 59, 10, 9, 9,102,108,111, 97,116, 32,110,104, 32, 61,
+ 32,100,111,116, 40,110, 44, 32,104, 41, 59, 10, 9, 9,105,102, 40,110,104, 32, 60, 32, 48, 46, 48, 41, 32,123, 10, 9, 9, 9,
+115,112,101, 99,102, 97, 99, 32, 61, 32, 48, 46, 48, 59, 10, 9, 9,125, 10, 9, 9,101,108,115,101, 32,123, 10, 9, 9, 9,102,
+108,111, 97,116, 32,110,118, 32, 61, 32,109, 97,120, 40,100,111,116, 40,110, 44, 32,118, 41, 44, 32, 48, 46, 48, 49, 41, 59, 10,
+ 9, 9, 9,102,108,111, 97,116, 32,110,108, 32, 61, 32,100,111,116, 40,110, 44, 32,108, 41, 59, 10, 9, 9, 9,105,102, 40,110,
+108, 32, 60, 61, 32, 48, 46, 48, 49, 41, 32,123, 10, 9, 9, 9, 9,115,112,101, 99,102, 97, 99, 32, 61, 32, 48, 46, 48, 59, 10,
+ 9, 9, 9,125, 10, 9, 9, 9,101,108,115,101, 32,123, 10, 9, 9, 9, 9,102,108,111, 97,116, 32,118,104, 32, 61, 32,109, 97,
+120, 40,100,111,116, 40,118, 44, 32,104, 41, 44, 32, 48, 46, 48, 49, 41, 59, 10, 10, 9, 9, 9, 9,102,108,111, 97,116, 32, 97,
+ 32, 61, 32, 49, 46, 48, 59, 10, 9, 9, 9, 9,102,108,111, 97,116, 32, 98, 32, 61, 32, 40, 50, 46, 48, 42,110,104, 42,110,118,
+ 41, 47,118,104, 59, 10, 9, 9, 9, 9,102,108,111, 97,116, 32, 99, 32, 61, 32, 40, 50, 46, 48, 42,110,104, 42,110,108, 41, 47,
+118,104, 59, 10, 10, 9, 9, 9, 9,102,108,111, 97,116, 32,103, 32, 61, 32, 48, 46, 48, 59, 10, 10, 9, 9, 9, 9,105,102, 40,
+ 97, 32, 60, 32, 98, 32, 38, 38, 32, 97, 32, 60, 32, 99, 41, 32,103, 32, 61, 32, 97, 59, 10, 9, 9, 9, 9,101,108,115,101, 32,
+105,102, 40, 98, 32, 60, 32, 97, 32, 38, 38, 32, 98, 32, 60, 32, 99, 41, 32,103, 32, 61, 32, 98, 59, 10, 9, 9, 9, 9,101,108,
+115,101, 32,105,102, 40, 99, 32, 60, 32, 97, 32, 38, 38, 32, 99, 32, 60, 32, 98, 41, 32,103, 32, 61, 32, 99, 59, 10, 10, 9, 9,
+ 9, 9,102,108,111, 97,116, 32,112, 32, 61, 32,115,113,114,116, 40, 40, 40,114,101,102,114, 97, 99, 32, 42, 32,114,101,102,114,
+ 97, 99, 41, 43, 40,118,104, 42,118,104, 41, 45, 49, 46, 48, 41, 41, 59, 10, 9, 9, 9, 9,102,108,111, 97,116, 32,102, 32, 61,
+ 32, 40, 40, 40,112, 45,118,104, 41, 42, 40,112, 45,118,104, 41, 41, 47, 40, 40,112, 43,118,104, 41, 42, 40,112, 43,118,104, 41,
+ 41, 41, 42, 40, 49, 46, 48, 43, 40, 40, 40, 40,118,104, 42, 40,112, 43,118,104, 41, 41, 45, 49, 46, 48, 41, 42, 40, 40,118,104,
+ 42, 40,112, 43,118,104, 41, 41, 45, 49, 46, 48, 41, 41, 47, 40, 40, 40,118,104, 42, 40,112, 45,118,104, 41, 41, 43, 49, 46, 48,
+ 41, 42, 40, 40,118,104, 42, 40,112, 45,118,104, 41, 41, 43, 49, 46, 48, 41, 41, 41, 41, 59, 10, 9, 9, 9, 9,102,108,111, 97,
+116, 32, 97,110,103, 32, 61, 32, 97, 99,111,115, 40,110,104, 41, 59, 10, 10, 9, 9, 9, 9,115,112,101, 99,102, 97, 99, 32, 61,
+ 32,109, 97,120, 40,102, 42,103, 42,101,120,112, 95, 98,108,101,110,100,101,114, 40, 40, 45, 40, 97,110,103, 42, 97,110,103, 41,
+ 47, 40, 50, 46, 48, 42,115,112,101, 99, 95,112,111,119,101,114, 42,115,112,101, 99, 95,112,111,119,101,114, 41, 41, 41, 44, 32,
+ 48, 46, 48, 41, 59, 10, 9, 9, 9,125, 10, 9, 9,125, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,
+119, 97,114,100,105,115,111, 95,115,112,101, 99, 40,118,101, 99, 51, 32,110, 44, 32,118,101, 99, 51, 32,108, 44, 32,118,101, 99,
+ 51, 32,118, 44, 32,102,108,111, 97,116, 32,114,109,115, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,115,112,101, 99,102, 97,
+ 99, 41, 10,123, 10, 9,118,101, 99, 51, 32,104, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,108, 32, 43, 32,118, 41, 59,
+ 10, 9,102,108,111, 97,116, 32,110,104, 32, 61, 32,109, 97,120, 40,100,111,116, 40,110, 44, 32,104, 41, 44, 32, 48, 46, 48, 48,
+ 49, 41, 59, 10, 9,102,108,111, 97,116, 32,110,118, 32, 61, 32,109, 97,120, 40,100,111,116, 40,110, 44, 32,118, 41, 44, 32, 48,
+ 46, 48, 48, 49, 41, 59, 10, 9,102,108,111, 97,116, 32,110,108, 32, 61, 32,109, 97,120, 40,100,111,116, 40,110, 44, 32,108, 41,
+ 44, 32, 48, 46, 48, 48, 49, 41, 59, 10, 9,102,108,111, 97,116, 32, 97,110,103,108,101, 32, 61, 32,116, 97,110, 40, 97, 99,111,
+115, 40,110,104, 41, 41, 59, 10, 9,102,108,111, 97,116, 32, 97,108,112,104, 97, 32, 61, 32,109, 97,120, 40,114,109,115, 44, 32,
+ 48, 46, 48, 48, 49, 41, 59, 10, 10, 9,115,112,101, 99,102, 97, 99, 61, 32,110,108, 32, 42, 32, 40, 49, 46, 48, 47, 40, 52, 46,
+ 48, 42, 77, 95, 80, 73, 42, 97,108,112,104, 97, 42, 97,108,112,104, 97, 41, 41, 42, 40,101,120,112, 95, 98,108,101,110,100,101,
+114, 40, 45, 40, 97,110,103,108,101, 42, 97,110,103,108,101, 41, 47, 40, 97,108,112,104, 97, 42, 97,108,112,104, 97, 41, 41, 47,
+ 40,115,113,114,116, 40,110,118, 42,110,108, 41, 41, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,116,111,
+111,110, 95,115,112,101, 99, 40,118,101, 99, 51, 32,110, 44, 32,118,101, 99, 51, 32,108, 44, 32,118,101, 99, 51, 32,118, 44, 32,
+102,108,111, 97,116, 32,115,105,122,101, 44, 32,102,108,111, 97,116, 32,116,115,109,111,111,116,104, 44, 32,111,117,116, 32,102,
+108,111, 97,116, 32,115,112,101, 99,102, 97, 99, 41, 10,123, 10, 9,118,101, 99, 51, 32,104, 32, 61, 32,110,111,114,109, 97,108,
+105,122,101, 40,108, 32, 43, 32,118, 41, 59, 10, 9,102,108,111, 97,116, 32,114,115,108,116, 32, 61, 32,100,111,116, 40,104, 44,
+ 32,110, 41, 59, 10, 9,102,108,111, 97,116, 32, 97,110,103, 32, 61, 32, 97, 99,111,115, 40,114,115,108,116, 41, 59, 10, 10, 9,
+105,102, 40, 97,110,103, 32, 60, 32,115,105,122,101, 41, 32,114,115,108,116, 32, 61, 32, 49, 46, 48, 59, 10, 9,101,108,115,101,
+ 32,105,102, 40, 97,110,103, 32, 62, 61, 32, 40,115,105,122,101, 32, 43, 32,116,115,109,111,111,116,104, 41, 32,124,124, 32,116,
+115,109,111,111,116,104, 32, 61, 61, 32, 48, 46, 48, 41, 32,114,115,108,116, 32, 61, 32, 48, 46, 48, 59, 10, 9,101,108,115,101,
+ 32,114,115,108,116, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40, 40, 97,110,103, 32, 45, 32,115,105,122,101, 41, 47,116,115,109,111,
+111,116,104, 41, 59, 10, 10, 9,115,112,101, 99,102, 97, 99, 32, 61, 32,114,115,108,116, 59, 10,125, 10, 10,118,111,105,100, 32,
+115,104, 97,100,101, 95,115,112,101, 99, 95, 97,114,101, 97, 95,105,110,112, 40,102,108,111, 97,116, 32,115,112,101, 99,102, 97,
+ 99, 44, 32,102,108,111, 97,116, 32,105,110,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,115,112,101, 99,102,
+ 97, 99, 41, 10,123, 10, 9,111,117,116,115,112,101, 99,102, 97, 99, 32, 61, 32,115,112,101, 99,102, 97, 99, 42,105,110,112, 59,
+ 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,115,112,101, 99, 95,116, 40,102,108,111, 97,116, 32,115,104, 97,100,
+102, 97, 99, 44, 32,102,108,111, 97,116, 32,115,112,101, 99, 44, 32,102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 44, 32,
+102,108,111, 97,116, 32,115,112,101, 99,102, 97, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,116, 41, 10,123, 10, 9,116,
+ 32, 61, 32,115,104, 97,100,102, 97, 99, 42,115,112,101, 99, 42,118,105,115,105,102, 97, 99, 42,115,112,101, 99,102, 97, 99, 59,
+ 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95, 97,100,100, 95,115,112,101, 99, 40,102,108,111, 97,116, 32,116, 44,
+ 32,118,101, 99, 51, 32,108, 97,109,112, 99,111,108, 44, 32,118,101, 99, 51, 32,115,112,101, 99, 99,111,108, 44, 32,111,117,116,
+ 32,118,101, 99, 51, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32,116, 42,108, 97,109,112,
+ 99,111,108, 42,115,112,101, 99, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95, 97,100,100, 40,118,
+101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,
+116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 49, 32, 43, 32, 99,111,108, 50, 59, 10,125,
+ 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,109, 97,100,100, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,118,101, 99, 52,
+ 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,
+108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 32, 43, 32, 99,111,108, 49, 42, 99,111,108, 50, 59, 10,
+125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,109, 97,100,100,102, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,102,108,
+111, 97,116, 32,102, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,
+108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 32, 43, 32,102, 42, 99,111,108, 49, 59, 10,125, 10, 10,
+118,111,105,100, 32,115,104, 97,100,101, 95,109,117,108, 40,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,
+111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32,
+ 61, 32, 99,111,108, 49, 42, 99,111,108, 50, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,109,117,108, 95,118,
+ 97,108,117,101, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 44, 32,111,117,116, 32,118,101,
+ 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 42,102, 97, 99, 59, 10,
+125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,111, 98, 99,111,108,111,114, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,
+118,101, 99, 52, 32,111, 98, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,
+111,117,116, 99,111,108, 32, 61, 32,118,101, 99, 52, 40, 99,111,108, 46,114,103, 98, 42,111, 98, 99,111,108, 46,114,103, 98, 44,
+ 32, 99,111,108, 46, 97, 41, 59, 10,125, 10, 10,118,111,105,100, 32,114, 97,109,112, 95,114,103, 98,116,111, 98,119, 40,118,101,
+ 99, 51, 32, 99,111,108,111,114, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,
+117,116,118, 97,108, 32, 61, 32, 99,111,108,111,114, 46,114, 42, 48, 46, 51, 32, 43, 32, 99,111,108,111,114, 46,103, 42, 48, 46,
+ 53, 56, 32, 43, 32, 99,111,108,111,114, 46, 98, 42, 48, 46, 49, 50, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101,
+ 95,111,110,108,121, 95,115,104, 97,100,111,119, 40,102,108,111, 97,116, 32,105, 44, 32,102,108,111, 97,116, 32,115,104, 97,100,
+102, 97, 99, 44, 32,102,108,111, 97,116, 32,101,110,101,114,103,121, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,
+115,104, 97,100,102, 97, 99, 41, 10,123, 10, 9,111,117,116,115,104, 97,100,102, 97, 99, 32, 61, 32,105, 42,101,110,101,114,103,
+121, 42, 40, 49, 46, 48, 32, 45, 32,115,104, 97,100,102, 97, 99, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101,
+ 95,111,110,108,121, 95,115,104, 97,100,111,119, 95,100,105,102,102,117,115,101, 40,102,108,111, 97,116, 32,115,104, 97,100,102,
+ 97, 99, 44, 32,118,101, 99, 51, 32,114,103, 98, 44, 32,118,101, 99, 52, 32,100,105,102,102, 44, 32,111,117,116, 32,118,101, 99,
+ 52, 32,111,117,116,100,105,102,102, 41, 10,123, 10, 9,111,117,116,100,105,102,102, 32, 61, 32,100,105,102,102, 32, 45, 32,118,
+101, 99, 52, 40,114,103, 98, 42,115,104, 97,100,102, 97, 99, 44, 32, 48, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,
+104, 97,100,101, 95,111,110,108,121, 95,115,104, 97,100,111,119, 95,115,112,101, 99,117,108, 97,114, 40,102,108,111, 97,116, 32,
+115,104, 97,100,102, 97, 99, 44, 32,118,101, 99, 51, 32,115,112,101, 99,114,103, 98, 44, 32,118,101, 99, 52, 32,115,112,101, 99,
+ 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116,115,112,101, 99, 41, 10,123, 10, 9,111,117,116,115,112,101, 99, 32, 61,
+ 32,115,112,101, 99, 32, 45, 32,118,101, 99, 52, 40,115,112,101, 99,114,103, 98, 42,115,104, 97,100,102, 97, 99, 44, 32, 48, 46,
+ 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,115,116, 95,115,104, 97,100,111,119, 98,117,102, 40,118,101, 99, 51, 32,
+114, 99,111, 44, 32,115, 97,109,112,108,101,114, 50, 68, 83,104, 97,100,111,119, 32,115,104, 97,100,111,119,109, 97,112, 44, 32,
+109, 97,116, 52, 32,115,104, 97,100,111,119,112,101,114,115,109, 97,116, 44, 32,102,108,111, 97,116, 32,115,104, 97,100,111,119,
+ 98,105, 97,115, 44, 32,102,108,111, 97,116, 32,105,110,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,114,101,115,117,108,
+116, 41, 10,123, 10, 9,105,102, 40,105,110,112, 32, 60, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,114,101,115,117,108,116, 32,
+ 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10, 9, 9,118,101, 99, 52, 32, 99,111, 32, 61, 32,115,104,
+ 97,100,111,119,112,101,114,115,109, 97,116, 42,118,101, 99, 52, 40,114, 99,111, 44, 32, 49, 46, 48, 41, 59, 10, 10, 9, 9, 47,
+ 47,102,108,111, 97,116, 32, 98,105, 97,115, 32, 61, 32, 40, 49, 46, 53, 32, 45, 32,105,110,112, 42,105,110,112, 41, 42,115,104,
+ 97,100,111,119, 98,105, 97,115, 59, 10, 9, 9, 99,111, 46,122, 32, 45, 61, 32,115,104, 97,100,111,119, 98,105, 97,115, 42, 99,
+111, 46,119, 59, 10, 10, 9, 9,114,101,115,117,108,116, 32, 61, 32,115,104, 97,100,111,119, 50, 68, 80,114,111,106, 40,115,104,
+ 97,100,111,119,109, 97,112, 44, 32, 99,111, 41, 46,120, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101,
+ 95,101,120,112,111,115,117,114,101, 95, 99,111,114,114,101, 99,116, 40,118,101, 99, 51, 32, 99,111,108, 44, 32,102,108,111, 97,
+116, 32,108,105,110,102, 97, 99, 44, 32,102,108,111, 97,116, 32,108,111,103,102, 97, 99, 44, 32,111,117,116, 32,118,101, 99, 51,
+ 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32,108,105,110,102, 97, 99, 42, 40, 49, 46, 48,
+ 32, 45, 32,101,120,112, 40, 99,111,108, 42,108,111,103,102, 97, 99, 41, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,
+100,101, 95,109,105,115,116, 95,102, 97, 99,116,111,114, 40,118,101, 99, 51, 32, 99,111, 44, 32,102,108,111, 97,116, 32,109,105,
+115,116,115,116, 97, 44, 32,102,108,111, 97,116, 32,109,105,115,116,100,105,115,116, 44, 32,102,108,111, 97,116, 32,109,105,115,
+116,116,121,112,101, 44, 32,102,108,111, 97,116, 32,109,105,115,105, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,
+102, 97, 99, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99, 44, 32,122, 99,111,114, 59, 10, 10, 9,122, 99,111,114, 32,
+ 61, 32, 40,103,108, 95, 80,114,111,106,101, 99,116,105,111,110, 77, 97,116,114,105,120, 91, 51, 93, 91, 51, 93, 32, 61, 61, 32,
+ 48, 46, 48, 41, 63, 32,108,101,110,103,116,104, 40, 99,111, 41, 58, 32, 45, 99,111, 91, 50, 93, 59, 10, 9, 10, 9,102, 97, 99,
+ 32, 61, 32, 99,108, 97,109,112, 40, 40,122, 99,111,114, 45,109,105,115,116,115,116, 97, 41, 47,109,105,115,116,100,105,115,116,
+ 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,105,102, 40,109,105,115,116,116,121,112,101, 32, 61, 61, 32, 48, 46, 48,
+ 41, 32,102, 97, 99, 32, 42, 61, 32,102, 97, 99, 59, 10, 9,101,108,115,101, 32,105,102, 40,109,105,115,116,116,121,112,101, 32,
+ 61, 61, 32, 49, 46, 48, 41, 59, 10, 9,101,108,115,101, 32,102, 97, 99, 32, 61, 32,115,113,114,116, 40,102, 97, 99, 41, 59, 10,
+ 10, 9,111,117,116,102, 97, 99, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40, 49, 46, 48, 45,102, 97, 99, 41, 42, 40, 49, 46, 48, 45,
+109,105,115,105, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,119,111,114,108,100, 95,109,105,120, 40,118,
+101, 99, 51, 32,104,111,114, 44, 32,118,101, 99, 52, 32, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,
+111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40, 99,111,108, 46, 97, 44, 32,
+ 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 32, 61, 32,118,101, 99, 52, 40,109,105,120, 40,104,111,
+114, 44, 32, 99,111,108, 46,114,103, 98, 44, 32,102, 97, 99, 41, 44, 32, 99,111,108, 46, 97, 41, 59, 10,125, 10, 10,118,111,105,
+100, 32,115,104, 97,100,101, 95, 97,108,112,104, 97, 95,111,112, 97,113,117,101, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,111,
+117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32,118,101, 99, 52,
+ 40, 99,111,108, 46,114,103, 98, 44, 32, 49, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95, 97,108,
+112,104, 97, 95,111, 98, 99,111,108,111,114, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,118,101, 99, 52, 32,111, 98, 99,111,108,
+ 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32,118,
+101, 99, 52, 40, 99,111,108, 46,114,103, 98, 44, 32, 99,111,108, 46, 97, 42,111, 98, 99,111,108, 46, 97, 41, 59, 10,125, 10, 10,
+ 0};
+
diff --git a/source/blender/gpu/intern/gpu_shader_vertex.glsl b/source/blender/gpu/intern/gpu_shader_vertex.glsl
new file mode 100644
index 00000000000..ba9ef7dead6
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_shader_vertex.glsl
@@ -0,0 +1,12 @@
+
+varying vec3 varposition;
+varying vec3 varnormal;
+
+void main()
+{
+ vec4 co = gl_ModelViewMatrix * gl_Vertex;
+
+ varposition = co.xyz;
+ varnormal = gl_NormalMatrix * gl_Normal;
+ gl_Position = gl_ProjectionMatrix * co;
+
diff --git a/source/blender/gpu/intern/gpu_shader_vertex.glsl.c b/source/blender/gpu/intern/gpu_shader_vertex.glsl.c
new file mode 100644
index 00000000000..edf93d838d5
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_shader_vertex.glsl.c
@@ -0,0 +1,13 @@
+/* DataToC output of file <gpu_shader_vertex_glsl> */
+
+int datatoc_gpu_shader_vertex_glsl_size= 217;
+char datatoc_gpu_shader_vertex_glsl[]= {
+ 10,118, 97,114,121,105,110,103, 32,118,101, 99, 51, 32,118, 97,114,112,111,115,105,116,105,111,110,
+ 59, 10,118, 97,114,121,105,110,103, 32,118,101, 99, 51, 32,118, 97,114,110,111,114,109, 97,108, 59, 10, 10,118,111,105,100, 32,
+109, 97,105,110, 40, 41, 10,123, 10, 9,118,101, 99, 52, 32, 99,111, 32, 61, 32,103,108, 95, 77,111,100,101,108, 86,105,101,119,
+ 77, 97,116,114,105,120, 32, 42, 32,103,108, 95, 86,101,114,116,101,120, 59, 10, 10, 9,118, 97,114,112,111,115,105,116,105,111,
+110, 32, 61, 32, 99,111, 46,120,121,122, 59, 10, 9,118, 97,114,110,111,114,109, 97,108, 32, 61, 32,103,108, 95, 78,111,114,109,
+ 97,108, 77, 97,116,114,105,120, 32, 42, 32,103,108, 95, 78,111,114,109, 97,108, 59, 10, 9,103,108, 95, 80,111,115,105,116,105,
+111,110, 32, 61, 32,103,108, 95, 80,114,111,106,101, 99,116,105,111,110, 77, 97,116,114,105,120, 32, 42, 32, 99,111, 59, 10, 10,
+ 0};
+
diff --git a/source/blender/imbuf/CMakeLists.txt b/source/blender/imbuf/CMakeLists.txt
index 0aac462573a..2d41a6d73e6 100644
--- a/source/blender/imbuf/CMakeLists.txt
+++ b/source/blender/imbuf/CMakeLists.txt
@@ -54,5 +54,9 @@ IF(WITH_FFMPEG)
ADD_DEFINITIONS(-DWITH_FFMPEG)
ENDIF(WITH_FFMPEG)
+if(WITH_DDS)
+ ADD_DEFINITIONS(-DWITH_DDS)
+ENDIF(WITH_DDS)
+
BLENDERLIB(bf_imbuf "${SRC}" "${INC}")
#env.BlenderLib ( libname = 'bf_imbuf', sources = sources, includes = Split(incs), defines = defs, libtype=['core','player'], priority = [80, 40] )
diff --git a/source/blender/imbuf/IMB_imbuf.h b/source/blender/imbuf/IMB_imbuf.h
index 338f96cb4f4..d4d8030bf10 100644
--- a/source/blender/imbuf/IMB_imbuf.h
+++ b/source/blender/imbuf/IMB_imbuf.h
@@ -318,7 +318,7 @@ void IMB_antialias(struct ImBuf * ibuf);
*/
void IMB_filter(struct ImBuf *ibuf);
void IMB_filterN(struct ImBuf *out, struct ImBuf *in);
-void IMB_filter_extend(struct ImBuf *ibuf);
+void IMB_filter_extend(struct ImBuf *ibuf, char *mask);
void IMB_makemipmap(struct ImBuf *ibuf, int use_filter);
/**
diff --git a/source/blender/imbuf/IMB_imbuf_types.h b/source/blender/imbuf/IMB_imbuf_types.h
index ce210e7834d..73ef83393b0 100644
--- a/source/blender/imbuf/IMB_imbuf_types.h
+++ b/source/blender/imbuf/IMB_imbuf_types.h
@@ -92,7 +92,7 @@ typedef struct ImBuf {
int userflags; /**< Used to set imbuf to Dirty and other stuff */
int *zbuf; /**< z buffer data, original zbuffer */
float *zbuf_float; /**< z buffer data, camera coordinates */
- void *userdata;
+ void *userdata; /**< temporary storage, only used by baking at the moment */
unsigned char *encodedbuffer; /**< Compressed image only used with png currently */
unsigned int encodedsize; /**< Size of data written to encodedbuffer */
unsigned int encodedbuffersize; /**< Size of encodedbuffer */
@@ -149,6 +149,7 @@ typedef enum {
#define IB_zbuffloat (1 << 16)
#define IB_multilayer (1 << 17)
#define IB_imginfo (1 << 18)
+#define IB_animdeinterlace (1 << 19)
/*
* The bit flag is stored in the ImBuf.ftype variable.
@@ -167,6 +168,7 @@ typedef enum {
#define RADHDR (1 << 24)
#define TIF (1 << 23)
+#define TIF_16BIT (1 << 8 )
#define OPENEXR (1 << 22)
#define OPENEXR_HALF (1 << 8 )
diff --git a/source/blender/imbuf/SConscript b/source/blender/imbuf/SConscript
index 9d8bcf56ec7..cb4759ed240 100644
--- a/source/blender/imbuf/SConscript
+++ b/source/blender/imbuf/SConscript
@@ -4,7 +4,7 @@ Import ('env')
sources = env.Glob('intern/*.c')
incs = '. ../makesdna #/intern/guardedalloc #/intern/memutil ../blenlib'
-incs += ' ../avi ../quicktime ../blenkernel'
+incs += ' ../avi ../blenkernel'
incs += ' ' + env['BF_JPEG_INC']
incs += ' ' + env['BF_PNG_INC']
@@ -17,18 +17,26 @@ if env['WITH_BF_VERSE']:
defs.append('WITH_VERSE')
incs += ' ' + env['BF_VERSE_INCLUDE']
-if env['WITH_BF_OPENEXR'] == 1:
- defs.append('WITH_OPENEXR')
+if env['WITH_BF_OPENEXR']:
+ defs.append('WITH_OPENEXR')
-if env['WITH_BF_DDS'] == 1:
- defs.append('WITH_DDS')
+if env['WITH_BF_DDS']:
+ defs.append('WITH_DDS')
-if env['WITH_BF_FFMPEG'] == 1:
- defs.append('WITH_FFMPEG')
- incs += ' ' + env['BF_FFMPEG_INC']
+if env['WITH_BF_FFMPEG']:
+ defs.append('WITH_FFMPEG')
+ incs += ' ' + env['BF_FFMPEG_INC']
-if env['WITH_BF_QUICKTIME']==1:
- incs += ' ' + env['BF_QUICKTIME_INC']
+if env['WITH_BF_OPENJPEG']:
+ defs.append('WITH_OPENJPEG')
+ incs += ' ' + env['BF_OPENJPEG_INC']
+
+if env['WITH_BF_REDCODE']:
+ defs.append('WITH_REDCODE')
+ incs += ' ' + env['BF_REDCODE_INC']
+
+if env['WITH_BF_QUICKTIME']:
+ incs += ' ../quicktime ' + env['BF_QUICKTIME_INC']
defs.append('WITH_QUICKTIME')
env.BlenderLib ( libname = 'bf_imbuf', sources = sources, includes = Split(incs), defines = defs, libtype=['core','player'], priority = [95, 35] )
diff --git a/source/blender/imbuf/intern/IMB_anim.h b/source/blender/imbuf/intern/IMB_anim.h
index 2c7f8bddbe6..745248d3218 100644
--- a/source/blender/imbuf/intern/IMB_anim.h
+++ b/source/blender/imbuf/intern/IMB_anim.h
@@ -81,6 +81,14 @@
#include <ffmpeg/swscale.h>
#endif
+#ifdef WITH_REDCODE
+#ifdef _WIN32 /* on windows we use the one in extern instead */
+#include "libredcode/format.h"
+#else
+#include "libredcode/format.h"
+#endif
+#endif
+
#include "IMB_imbuf_types.h"
#include "IMB_imbuf.h"
@@ -96,7 +104,7 @@
#define SWAP_S(x) (((x << 8) & 0xff00) | ((x >> 8) & 0xff))
/* more endianness... should move to a separate file... */
-#if defined(__sgi) || defined (__sparc) || (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
+#if defined(__sgi) || defined (__sparc) || (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__hppa__) || defined (__BIG_ENDIAN__)
#define GET_ID GET_BIG_LONG
#define LITTLE_LONG SWAP_LONG
#else
@@ -116,6 +124,7 @@
#define ANIM_AVI (1 << 6)
#define ANIM_QTIME (1 << 7)
#define ANIM_FFMPEG (1 << 8)
+#define ANIM_REDCODE (1 << 9)
#define ANIM5_MMAP 0
#define ANIM5_MALLOC 1
@@ -178,12 +187,16 @@ struct anim {
AVFormatContext *pFormatCtx;
AVCodecContext *pCodecCtx;
AVCodec *pCodec;
- AVFrame *pFrameRGB;
AVFrame *pFrame;
+ AVFrame *pFrameRGB;
+ AVFrame *pFrameDeinterlaced;
struct SwsContext *img_convert_ctx;
int videoStream;
#endif
+#ifdef WITH_REDCODE
+ struct redcode_handle * redcodeCtx;
+#endif
};
#endif
diff --git a/source/blender/imbuf/intern/allocimbuf.c b/source/blender/imbuf/intern/allocimbuf.c
index be462d67238..ad7b1dce2e0 100644
--- a/source/blender/imbuf/intern/allocimbuf.c
+++ b/source/blender/imbuf/intern/allocimbuf.c
@@ -277,6 +277,7 @@ short imb_addrectfloatImBuf(struct ImBuf * ibuf)
size = ibuf->x * ibuf->y;
size = size * 4 * sizeof(float);
+ ibuf->channels= 4;
if ( (ibuf->rect_float = MEM_mapallocN(size, "imb_addrectfloatImBuf")) ){
ibuf->mall |= IB_rectfloat;
@@ -442,7 +443,7 @@ struct ImBuf *IMB_dupImBuf(struct ImBuf *ibuf1)
memcpy(ibuf2->rect, ibuf1->rect, x * y * sizeof(int));
if (flags & IB_rectfloat)
- memcpy(ibuf2->rect_float, ibuf1->rect_float, 4 * x * y * sizeof(float));
+ memcpy(ibuf2->rect_float, ibuf1->rect_float, ibuf1->channels * x * y * sizeof(float));
if (flags & IB_planes)
memcpy(*(ibuf2->planes),*(ibuf1->planes),ibuf1->depth * ibuf1->skipx * y * sizeof(int));
@@ -474,6 +475,7 @@ struct ImBuf *IMB_dupImBuf(struct ImBuf *ibuf1)
// set malloc flag
tbuf.mall = ibuf2->mall;
tbuf.c_handle = 0;
+ tbuf.refcounter = 0;
// for now don't duplicate image info
tbuf.img_info = 0;
diff --git a/source/blender/imbuf/intern/amiga.c b/source/blender/imbuf/intern/amiga.c
index fa13b55874a..534e4945aa3 100644
--- a/source/blender/imbuf/intern/amiga.c
+++ b/source/blender/imbuf/intern/amiga.c
@@ -29,8 +29,12 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#ifdef WIN32
+#ifdef _WIN32
#include <io.h>
+#define open _open
+#define read _read
+#define close _close
+#define write _write
#endif
#include "imbuf.h"
#include "imbuf_patch.h"
@@ -52,7 +56,7 @@
#define SWAP_S(x) (((x << 8) & 0xff00) | ((x >> 8) & 0xff))
/* more endianness... should move to a separate file... */
-#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
+#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__hppa__) || defined (__BIG_ENDIAN__)
#define GET_ID GET_BIG_LONG
#define LITTLE_LONG SWAP_LONG
#else
diff --git a/source/blender/imbuf/intern/anim.c b/source/blender/imbuf/intern/anim.c
index ef3dd79db73..80bf401bec0 100644
--- a/source/blender/imbuf/intern/anim.c
+++ b/source/blender/imbuf/intern/anim.c
@@ -96,6 +96,16 @@
#endif
+#ifdef WITH_REDCODE
+#ifdef _WIN32 /* on windows we use the ones in extern instead */
+#include "libredcode/format.h"
+#include "libredcode/codec.h"
+#else
+#include "libredcode/format.h"
+#include "libredcode/codec.h"
+#endif
+#endif
+
/****/
#ifdef __sgi
@@ -307,6 +317,9 @@ void IMB_free_anim_ibuf(struct anim * anim) {
#ifdef WITH_FFMPEG
static void free_anim_ffmpeg(struct anim * anim);
#endif
+#ifdef WITH_REDCODE
+static void free_anim_redcode(struct anim * anim);
+#endif
void IMB_free_anim(struct anim * anim) {
if (anim == NULL) {
@@ -325,6 +338,9 @@ void IMB_free_anim(struct anim * anim) {
#ifdef WITH_FFMPEG
free_anim_ffmpeg(anim);
#endif
+#ifdef WITH_REDCODE
+ free_anim_redcode(anim);
+#endif
free(anim);
}
@@ -589,19 +605,31 @@ static int startffmpeg(struct anim * anim) {
anim->videoStream = videoStream;
anim->pFrame = avcodec_alloc_frame();
+ anim->pFrameDeinterlaced = avcodec_alloc_frame();
anim->pFrameRGB = avcodec_alloc_frame();
- if (avpicture_get_size(PIX_FMT_RGBA32, anim->x, anim->y)
+ if (avpicture_get_size(PIX_FMT_BGR32, anim->x, anim->y)
!= anim->x * anim->y * 4) {
fprintf (stderr,
"ffmpeg has changed alloc scheme ... ARGHHH!\n");
avcodec_close(anim->pCodecCtx);
av_close_input_file(anim->pFormatCtx);
av_free(anim->pFrameRGB);
+ av_free(anim->pFrameDeinterlaced);
av_free(anim->pFrame);
+ anim->pCodecCtx = NULL;
return -1;
}
+ if (anim->ib_flags & IB_animdeinterlace) {
+ avpicture_fill((AVPicture*) anim->pFrameDeinterlaced,
+ MEM_callocN(avpicture_get_size(
+ anim->pCodecCtx->pix_fmt,
+ anim->x, anim->y),
+ "ffmpeg deinterlace"),
+ anim->pCodecCtx->pix_fmt, anim->x, anim->y);
+ }
+
if (pCodecCtx->has_b_frames) {
anim->preseek = 25; /* FIXME: detect gopsize ... */
} else {
@@ -614,10 +642,22 @@ static int startffmpeg(struct anim * anim) {
anim->pCodecCtx->pix_fmt,
anim->pCodecCtx->width,
anim->pCodecCtx->height,
- PIX_FMT_RGBA,
+ PIX_FMT_BGR32,
SWS_FAST_BILINEAR | SWS_PRINT_INFO,
NULL, NULL, NULL);
-
+
+ if (!anim->img_convert_ctx) {
+ fprintf (stderr,
+ "Can't transform color space??? Bailing out...\n");
+ avcodec_close(anim->pCodecCtx);
+ av_close_input_file(anim->pFormatCtx);
+ av_free(anim->pFrameRGB);
+ av_free(anim->pFrameDeinterlaced);
+ av_free(anim->pFrame);
+ anim->pCodecCtx = NULL;
+ return -1;
+ }
+
return (0);
}
@@ -627,14 +667,15 @@ static ImBuf * ffmpeg_fetchibuf(struct anim * anim, int position) {
AVPacket packet;
int64_t pts_to_search = 0;
int pos_found = 1;
+ int filter_y = 0;
if (anim == 0) return (0);
ibuf = IMB_allocImBuf(anim->x, anim->y, 24, IB_rect, 0);
- avpicture_fill((AVPicture *)anim->pFrameRGB,
+ avpicture_fill((AVPicture*) anim->pFrameRGB,
(unsigned char*) ibuf->rect,
- PIX_FMT_RGBA32, anim->x, anim->y);
+ PIX_FMT_BGR32, anim->x, anim->y);
if (position != anim->curposition + 1) {
if (position > anim->curposition + 1
@@ -711,35 +752,135 @@ static ImBuf * ffmpeg_fetchibuf(struct anim * anim, int position) {
}
if(frameFinished && pos_found == 1) {
- int * dstStride = anim->pFrameRGB->linesize;
- uint8_t** dst = anim->pFrameRGB->data;
- int dstStride2[4]= { -dstStride[0], 0, 0, 0 };
- uint8_t* dst2[4]= {
- dst[0] + (anim->y - 1)*dstStride[0],
- 0, 0, 0 };
- int i;
-
- sws_scale(anim->img_convert_ctx,
- anim->pFrame->data,
- anim->pFrame->linesize,
- 0,
- anim->pCodecCtx->height,
- dst2,
- dstStride2);
-
- /* workaround: sws_scale sets alpha = 0... */
- for (i = 0; i < ibuf->x * ibuf->y; i++) {
- ibuf->rect[i] |= 0xff000000;
+ AVFrame * input = anim->pFrame;
+
+ /* This means the data wasnt read properly,
+ this check stops crashing */
+ if (input->data[0]==0 && input->data[1]==0
+ && input->data[2]==0 && input->data[3]==0){
+ av_free_packet(&packet);
+ break;
}
- av_free_packet(&packet);
- break;
+ if (anim->ib_flags & IB_animdeinterlace) {
+ if (avpicture_deinterlace(
+ (AVPicture*)
+ anim->pFrameDeinterlaced,
+ (const AVPicture*)
+ anim->pFrame,
+ anim->pCodecCtx->pix_fmt,
+ anim->pCodecCtx->width,
+ anim->pCodecCtx->height)
+ < 0) {
+ filter_y = 1;
+ } else {
+ input = anim->pFrameDeinterlaced;
+ }
+ }
+
+ if (G.order == B_ENDIAN) {
+ int * dstStride
+ = anim->pFrameRGB->linesize;
+ uint8_t** dst = anim->pFrameRGB->data;
+ int dstStride2[4]
+ = { dstStride[0], 0, 0, 0 };
+ uint8_t* dst2[4]= {
+ dst[0], 0, 0, 0 };
+ int x,y,h,w;
+ unsigned char* bottom;
+ unsigned char* top;
+
+ sws_scale(anim->img_convert_ctx,
+ input->data,
+ input->linesize,
+ 0,
+ anim->pCodecCtx->height,
+ dst2,
+ dstStride2);
+
+ /* workaround: sws_scale
+ sets alpha = 0 and compensate
+ for altivec-bugs and flipy... */
+
+ bottom = (unsigned char*) ibuf->rect;
+ top = bottom
+ + ibuf->x * (ibuf->y-1) * 4;
+
+ h = (ibuf->y + 1) / 2;
+ w = ibuf->x;
+
+ for (y = 0; y < h; y++) {
+ unsigned char tmp[4];
+ unsigned long * tmp_l =
+ (unsigned long*) tmp;
+ tmp[3] = 0xff;
+
+ for (x = 0; x < w; x++) {
+ tmp[0] = bottom[3];
+ tmp[1] = bottom[2];
+ tmp[2] = bottom[1];
+
+ bottom[0] = top[3];
+ bottom[1] = top[2];
+ bottom[2] = top[1];
+ bottom[3] = 0xff;
+
+ *(unsigned long*) top
+ = *tmp_l;
+
+ bottom +=4;
+ top += 4;
+ }
+ top -= 8 * w;
+ }
+
+ av_free_packet(&packet);
+ break;
+ } else {
+ int * dstStride
+ = anim->pFrameRGB->linesize;
+ uint8_t** dst = anim->pFrameRGB->data;
+ int dstStride2[4]
+ = { -dstStride[0], 0, 0, 0 };
+ uint8_t* dst2[4]= {
+ dst[0]
+ + (anim->y - 1)*dstStride[0],
+ 0, 0, 0 };
+ int i;
+ unsigned char* r;
+
+
+ sws_scale(anim->img_convert_ctx,
+ input->data,
+ input->linesize,
+ 0,
+ anim->pCodecCtx->height,
+ dst2,
+ dstStride2);
+
+ /* workaround: sws_scale
+ sets alpha = 0... */
+
+ r = (unsigned char*) ibuf->rect;
+
+ for (i = 0; i < ibuf->x * ibuf->y;i++){
+ r[3] = 0xff;
+ r+=4;
+ }
+
+ av_free_packet(&packet);
+ break;
+ }
}
}
av_free_packet(&packet);
}
+ if (filter_y && ibuf) {
+ IMB_filtery(ibuf);
+ }
+
return(ibuf);
}
@@ -751,6 +892,11 @@ static void free_anim_ffmpeg(struct anim * anim) {
av_close_input_file(anim->pFormatCtx);
av_free(anim->pFrameRGB);
av_free(anim->pFrame);
+
+ if (anim->ib_flags & IB_animdeinterlace) {
+ MEM_freeN(anim->pFrameDeinterlaced->data[0]);
+ }
+ av_free(anim->pFrameDeinterlaced);
sws_freeContext(anim->img_convert_ctx);
}
anim->duration = 0;
@@ -758,6 +904,58 @@ static void free_anim_ffmpeg(struct anim * anim) {
#endif
+#ifdef WITH_REDCODE
+
+static int startredcode(struct anim * anim) {
+ anim->redcodeCtx = redcode_open(anim->name);
+ if (!anim->redcodeCtx) {
+ return -1;
+ }
+ anim->duration = redcode_get_length(anim->redcodeCtx);
+
+ return 0;
+}
+
+static ImBuf * redcode_fetchibuf(struct anim * anim, int position) {
+ struct ImBuf * ibuf;
+ struct redcode_frame * frame;
+ struct redcode_frame_raw * raw_frame;
+
+ if (!anim->redcodeCtx) {
+ return NULL;
+ }
+
+ frame = redcode_read_video_frame(anim->redcodeCtx, position);
+
+ if (!frame) {
+ return NULL;
+ }
+
+ raw_frame = redcode_decode_video_raw(frame, 1);
+
+ redcode_free_frame(frame);
+
+ if (!raw_frame) {
+ return NULL;
+ }
+
+ ibuf = IMB_allocImBuf(raw_frame->width * 2,
+ raw_frame->height * 2, 32, IB_rectfloat, 0);
+
+ redcode_decode_video_float(raw_frame, ibuf->rect_float, 1);
+
+ return ibuf;
+}
+
+static void free_anim_redcode(struct anim * anim) {
+ if (anim->redcodeCtx) {
+ redcode_close(anim->redcodeCtx);
+ anim->redcodeCtx = 0;
+ }
+ anim->duration = 0;
+}
+
+#endif
/* probeer volgende plaatje te lezen */
/* Geen plaatje, probeer dan volgende animatie te openen */
@@ -777,6 +975,10 @@ static struct ImBuf * anim_getnew(struct anim * anim) {
#ifdef WITH_FFMPEG
free_anim_ffmpeg(anim);
#endif
+#ifdef WITH_REDCODE
+ free_anim_redcode(anim);
+#endif
+
if (anim->curtype != 0) return (0);
anim->curtype = imb_get_anim_type(anim->name);
@@ -816,8 +1018,13 @@ static struct ImBuf * anim_getnew(struct anim * anim) {
ibuf = IMB_allocImBuf (anim->x, anim->y, 24, 0, 0);
break;
#endif
+#ifdef WITH_REDCODE
+ case ANIM_REDCODE:
+ if (startredcode(anim)) return (0);
+ ibuf = IMB_allocImBuf (8, 8, 32, 0, 0);
+ break;
+#endif
}
-
return(ibuf);
}
@@ -839,6 +1046,7 @@ struct ImBuf * IMB_anim_absolute(struct anim * anim, int position) {
char head[256], tail[256];
unsigned short digits;
int pic;
+ int filter_y = (anim->ib_flags & IB_animdeinterlace);
if (anim == NULL) return(0);
@@ -896,12 +1104,20 @@ struct ImBuf * IMB_anim_absolute(struct anim * anim, int position) {
case ANIM_FFMPEG:
ibuf = ffmpeg_fetchibuf(anim, position);
if (ibuf) anim->curposition = position;
+ filter_y = 0; /* done internally */
+ break;
+#endif
+#ifdef WITH_REDCODE
+ case ANIM_REDCODE:
+ ibuf = redcode_fetchibuf(anim, position);
+ if (ibuf) anim->curposition = position;
break;
#endif
}
if (ibuf) {
if (anim->ib_flags & IB_ttob) IMB_flipy(ibuf);
+ if (filter_y) IMB_filtery(ibuf);
sprintf(ibuf->name, "%s.%04d", anim->name, anim->curposition + 1);
}
diff --git a/source/blender/imbuf/intern/bmp.c b/source/blender/imbuf/intern/bmp.c
index 2aa276a5f53..141b8a985cf 100644
--- a/source/blender/imbuf/intern/bmp.c
+++ b/source/blender/imbuf/intern/bmp.c
@@ -164,9 +164,9 @@ struct ImBuf *imb_bmp_decode(unsigned char *mem, int size, int flags)
}
} else if (depth == 32) {
for (i = x * y; i > 0; i--) {
- rect[0] = bmp[0];
+ rect[0] = bmp[2];
rect[1] = bmp[1];
- rect[2] = bmp[2];
+ rect[2] = bmp[0];
rect[3] = bmp[3];
rect += 4; bmp += 4;
}
diff --git a/source/blender/imbuf/intern/cineon/SConscript b/source/blender/imbuf/intern/cineon/SConscript
index 9d3bbcbc058..f887516443c 100644
--- a/source/blender/imbuf/intern/cineon/SConscript
+++ b/source/blender/imbuf/intern/cineon/SConscript
@@ -4,13 +4,13 @@ Import ('env')
source_files = env.Glob('*.c')
incs = ['.',
- '../../../blenkernel',
- '../../',
- '..',
- '../../../blenlib',
- 'intern/include',
- '#/intern/guardedalloc',
- '../../../makesdna']
+ '../../../blenkernel',
+ '../../',
+ '..',
+ '../../../blenlib',
+ 'intern/include',
+ '#/intern/guardedalloc',
+ '../../../makesdna']
defs = []
diff --git a/source/blender/imbuf/intern/cineon/cineon_dpx.c b/source/blender/imbuf/intern/cineon/cineon_dpx.c
index 691b81745e0..514d6b5522b 100644
--- a/source/blender/imbuf/intern/cineon/cineon_dpx.c
+++ b/source/blender/imbuf/intern/cineon/cineon_dpx.c
@@ -42,14 +42,29 @@
#include "MEM_guardedalloc.h"
+/* ugly bad level, should be fixed */
+#include "DNA_scene_types.h"
+#include "BKE_global.h"
+
+static void cineon_conversion_parameters(LogImageByteConversionParameters *params)
+{
+ params->blackPoint = G.scene?G.scene->r.cineonblack:95;
+ params->whitePoint = G.scene?G.scene->r.cineonwhite:685;
+ params->gamma = G.scene?G.scene->r.cineongamma:1.7f;
+ params->doLogarithm = G.scene?G.scene->r.subimtype & R_CINEON_LOG:0;
+}
+
static struct ImBuf *imb_load_dpx_cineon(unsigned char *mem, int use_cineon, int size, int flags)
{
+ LogImageByteConversionParameters conversion;
ImBuf *ibuf;
LogImageFile *image;
int x, y;
unsigned short *row, *upix;
int width, height, depth;
float *frow;
+
+ cineon_conversion_parameters(&conversion);
image = logImageOpenFromMem(mem, size, use_cineon);
@@ -70,6 +85,8 @@ static struct ImBuf *imb_load_dpx_cineon(unsigned char *mem, int use_cineon, int
return NULL;
}
+ logImageSetByteConversion(image, &conversion);
+
ibuf = IMB_allocImBuf(width, height, 32, IB_rectfloat | flags, 0);
row = MEM_mallocN(sizeof(unsigned short)*width*depth, "row in cineon_dpx.c");
@@ -107,10 +124,9 @@ static int imb_save_dpx_cineon(ImBuf *buf, char *filename, int use_cineon, int f
int i, j;
int index;
float *fline;
-
- conversion.blackPoint = 95;
- conversion.whitePoint = 685;
- conversion.gamma = 1;
+
+ cineon_conversion_parameters(&conversion);
+
/*
* Get the drawable for the current image...
*/
@@ -119,7 +135,13 @@ static int imb_save_dpx_cineon(ImBuf *buf, char *filename, int use_cineon, int f
height = buf->y;
depth = 3;
- if (!buf->rect_float) return 0;
+
+ if (!buf->rect_float) {
+ IMB_float_from_rect(buf);
+ if (!buf->rect_float) { /* in the unlikely event that converting to a float buffer fails */
+ return 0;
+ }
+ }
logImageSetVerbose(0);
logImage = logImageCreate(filename, use_cineon, width, height, depth);
diff --git a/source/blender/imbuf/intern/cineon/cineonlib.c b/source/blender/imbuf/intern/cineon/cineonlib.c
index 20f4e0d4de4..75516bbf3ae 100644
--- a/source/blender/imbuf/intern/cineon/cineonlib.c
+++ b/source/blender/imbuf/intern/cineon/cineonlib.c
@@ -67,12 +67,12 @@ fillCineonFileInfo(CineonFile* cineon, CineonFileInformation* fileInfo, const ch
static void
dumpCineonFileInfo(CineonFileInformation* fileInfo) {
d_printf("\n--File Information--\n");
- d_printf("Magic: %8.8lX\n", (unsigned long)ntohl(fileInfo->magic_num));
- d_printf("Image Offset %ld\n", (long)ntohl(fileInfo->image_offset));
- d_printf("Generic Header size %ld\n", (long)ntohl(fileInfo->gen_hdr_size));
- d_printf("Industry Header size %ld\n", (long)ntohl(fileInfo->ind_hdr_size));
- d_printf("User Data size %ld\n", (long)ntohl(fileInfo->user_data_size));
- d_printf("File size %ld\n", (long)ntohl(fileInfo->file_size));
+ d_printf("Magic: %8.8lX\n", (uintptr_t)ntohl(fileInfo->magic_num));
+ d_printf("Image Offset %ld\n", (intptr_t)ntohl(fileInfo->image_offset));
+ d_printf("Generic Header size %ld\n", (intptr_t)ntohl(fileInfo->gen_hdr_size));
+ d_printf("Industry Header size %ld\n", (intptr_t)ntohl(fileInfo->ind_hdr_size));
+ d_printf("User Data size %ld\n", (intptr_t)ntohl(fileInfo->user_data_size));
+ d_printf("File size %ld\n", (intptr_t)ntohl(fileInfo->file_size));
d_printf("Version \"%s\"\n", fileInfo->vers);
d_printf("File name \"%s\"\n", fileInfo->file_name);
d_printf("Creation date \"%s\"\n", fileInfo->create_date);
@@ -112,11 +112,11 @@ dumpCineonChannelInfo(CineonChannelInformation* chan) {
default: d_printf(" (unknown)\n"); break;
}
d_printf(" Bits per pixel %d\n", chan->bits_per_pixel);
- d_printf(" Pixels per line %ld\n", (long)ntohl(chan->pixels_per_line));
- d_printf(" Lines per image %ld\n", (long)ntohl(chan->lines_per_image));
- d_printf(" Ref low data %ld\n", (long)ntohl(chan->ref_low_data));
+ d_printf(" Pixels per line %ld\n", (intptr_t)ntohl(chan->pixels_per_line));
+ d_printf(" Lines per image %ld\n", (intptr_t)ntohl(chan->lines_per_image));
+ d_printf(" Ref low data %ld\n", (intptr_t)ntohl(chan->ref_low_data));
d_printf(" Ref low quantity %f\n", ntohf(chan->ref_low_quantity));
- d_printf(" Ref high data %ld\n", (long)ntohl(chan->ref_high_data));
+ d_printf(" Ref high data %ld\n", (intptr_t)ntohl(chan->ref_high_data));
d_printf(" Ref high quantity %f\n", ntohf(chan->ref_high_quantity));
}
@@ -231,8 +231,8 @@ dumpCineonFormatInfo(CineonFormatInformation* formatInfo) {
} else {
d_printf(" positive\n");
}
- d_printf("End of line padding %ld\n", (long)ntohl(formatInfo->line_padding));
- d_printf("End of channel padding %ld\n", (long)ntohl(formatInfo->channel_padding));
+ d_printf("End of line padding %ld\n", (intptr_t)ntohl(formatInfo->line_padding));
+ d_printf("End of channel padding %ld\n", (intptr_t)ntohl(formatInfo->channel_padding));
}
static void
@@ -256,8 +256,8 @@ fillCineonOriginationInfo(CineonFile* cineon,
static void
dumpCineonOriginationInfo(CineonOriginationInformation* originInfo) {
d_printf("\n--Origination Information--\n");
- d_printf("X offset %ld\n", (long)ntohl(originInfo->x_offset));
- d_printf("Y offset %ld\n", (long)ntohl(originInfo->y_offset));
+ d_printf("X offset %ld\n", (intptr_t)ntohl(originInfo->x_offset));
+ d_printf("Y offset %ld\n", (intptr_t)ntohl(originInfo->y_offset));
d_printf("File name \"%s\"\n", originInfo->file_name);
d_printf("Creation date \"%s\"\n", originInfo->create_date);
d_printf("Creation time \"%s\"\n", originInfo->create_time);
@@ -350,8 +350,10 @@ cineonGetRowBytes(CineonFile* cineon, unsigned short* row, int y) {
/* extract required pixels */
for (pixelIndex = 0; pixelIndex < numPixels; ++pixelIndex) {
- /* row[pixelIndex] = cineon->lut10[cineon->pixelBuffer[pixelIndex]]; */
- row[pixelIndex] = cineon->pixelBuffer[pixelIndex] << 6;
+ if(cineon->params.doLogarithm)
+ row[pixelIndex] = cineon->lut10_16[cineon->pixelBuffer[pixelIndex]];
+ else
+ row[pixelIndex] = cineon->pixelBuffer[pixelIndex] << 6;
}
return 0;
@@ -367,8 +369,10 @@ cineonSetRowBytes(CineonFile* cineon, const unsigned short* row, int y) {
/* put new pixels into pixelBuffer */
for (pixelIndex = 0; pixelIndex < numPixels; ++pixelIndex) {
- /* cineon->pixelBuffer[pixelIndex] = cineon->lut8[row[pixelIndex]]; */
- cineon->pixelBuffer[pixelIndex] = row[pixelIndex] >> 6;
+ if(cineon->params.doLogarithm)
+ cineon->pixelBuffer[pixelIndex] = cineon->lut16_16[row[pixelIndex]];
+ else
+ cineon->pixelBuffer[pixelIndex] = row[pixelIndex] >> 6;
}
/* pack into longwords */
@@ -525,7 +529,7 @@ cineonOpen(const char* filename) {
/* let's assume cineon files are always network order */
if (header.fileInfo.magic_num != ntohl(CINEON_FILE_MAGIC)) {
if (verbose) d_printf("Bad magic number %8.8lX in \"%s\".\n",
- (unsigned long)ntohl(header.fileInfo.magic_num), filename);
+ (uintptr_t)ntohl(header.fileInfo.magic_num), filename);
cineonClose(cineon);
return 0;
}
@@ -613,7 +617,7 @@ cineonOpenFromMem(unsigned char *mem, unsigned int size) {
cineon->file = 0;
cineon->reading = 1;
- verbose = 1;
+ verbose = 0;
if (size < sizeof(CineonGenericHeader)) {
if (verbose) d_printf("Not enough data for header!\n");
cineonClose(cineon);
@@ -624,7 +628,7 @@ cineonOpenFromMem(unsigned char *mem, unsigned int size) {
/* let's assume cineon files are always network order */
if (header.fileInfo.magic_num != ntohl(CINEON_FILE_MAGIC)) {
- if (verbose) d_printf("Bad magic number %8.8lX in\n", (unsigned long)ntohl(header.fileInfo.magic_num));
+ if (verbose) d_printf("Bad magic number %8.8lX in\n", (uintptr_t)ntohl(header.fileInfo.magic_num));
cineonClose(cineon);
return 0;
diff --git a/source/blender/imbuf/intern/cineon/dpxlib.c b/source/blender/imbuf/intern/cineon/dpxlib.c
index b769d1e6132..8a9adc73cdc 100644
--- a/source/blender/imbuf/intern/cineon/dpxlib.c
+++ b/source/blender/imbuf/intern/cineon/dpxlib.c
@@ -58,15 +58,15 @@ fillDpxChannelInfo(DpxFile* dpx, DpxChannelInformation* chan, int des) {
static void
dumpDpxChannelInfo(DpxChannelInformation* chan) {
- d_printf(" Signage %ld", (long)ntohl(chan->signage));
- d_printf(" Ref low data %ld\n", (long)ntohl(chan->ref_low_data));
+ d_printf(" Signage %ld", (intptr_t)ntohl(chan->signage));
+ d_printf(" Ref low data %ld\n", (intptr_t)ntohl(chan->ref_low_data));
d_printf(" Ref low quantity %f\n", ntohf(chan->ref_low_quantity));
- d_printf(" Ref high data %ld\n", (long)ntohl(chan->ref_high_data));
+ d_printf(" Ref high data %ld\n", (intptr_t)ntohl(chan->ref_high_data));
d_printf(" Ref high quantity %f\n", ntohf(chan->ref_high_quantity));
d_printf(" Designator1: %d,", chan->designator1);
d_printf(" Bits per pixel %d\n", chan->bits_per_pixel);
d_printf(" Packing: %d,", ntohs(chan->packing));
- d_printf(" Data Offset: %ld,", (long)ntohl(chan->data_offset));
+ d_printf(" Data Offset: %ld,", (intptr_t)ntohl(chan->data_offset));
}
static void
@@ -110,19 +110,19 @@ static void
dumpDpxFileInfo(DpxFileInformation* fileInfo) {
d_printf("\n--File Information--\n");
d_printf("Magic: %8.8lX\n", (unsigned long)ntohl(fileInfo->magic_num));
- d_printf("Image Offset %ld\n", (long)ntohl(fileInfo->offset));
+ d_printf("Image Offset %ld\n", (intptr_t)ntohl(fileInfo->offset));
d_printf("Version \"%s\"\n", fileInfo->vers);
- d_printf("File size %ld\n", (long)ntohl(fileInfo->file_size));
- d_printf("Ditto key %ld\n", (long)ntohl(fileInfo->ditto_key));
- d_printf("Generic Header size %ld\n", (long)ntohl(fileInfo->gen_hdr_size));
- d_printf("Industry Header size %ld\n", (long)ntohl(fileInfo->ind_hdr_size));
- d_printf("User Data size %ld\n", (long)ntohl(fileInfo->user_data_size));
+ d_printf("File size %ld\n", (intptr_t)ntohl(fileInfo->file_size));
+ d_printf("Ditto key %ld\n", (intptr_t)ntohl(fileInfo->ditto_key));
+ d_printf("Generic Header size %ld\n", (intptr_t)ntohl(fileInfo->gen_hdr_size));
+ d_printf("Industry Header size %ld\n", (intptr_t)ntohl(fileInfo->ind_hdr_size));
+ d_printf("User Data size %ld\n", (intptr_t)ntohl(fileInfo->user_data_size));
d_printf("File name \"%s\"\n", fileInfo->file_name);
d_printf("Creation date \"%s\"\n", fileInfo->create_date);
d_printf("Creator \"%s\"\n", fileInfo->creator);
d_printf("Project \"%s\"\n", fileInfo->project);
d_printf("Copyright \"%s\"\n", fileInfo->copyright);
- d_printf("Key %ld\n", (long)ntohl(fileInfo->key));
+ d_printf("Key %ld\n", (intptr_t)ntohl(fileInfo->key));
}
static void
@@ -150,8 +150,8 @@ dumpDpxImageInfo(DpxImageInformation* imageInfo) {
d_printf("Image orientation %d,", ntohs(imageInfo->orientation));
n = ntohs(imageInfo->channels_per_image);
d_printf("Channels %d\n", n);
- d_printf("Pixels per line %ld\n", (long)ntohl(imageInfo->pixels_per_line));
- d_printf("Lines per image %ld\n", (long)ntohl(imageInfo->lines_per_image));
+ d_printf("Pixels per line %ld\n", (intptr_t)ntohl(imageInfo->pixels_per_line));
+ d_printf("Lines per image %ld\n", (intptr_t)ntohl(imageInfo->lines_per_image));
for (i = 0; i < n; ++i) {
d_printf(" --Channel %d--\n", i);
dumpDpxChannelInfo(&imageInfo->channel[i]);
@@ -166,12 +166,12 @@ fillDpxOriginationInfo(
static void
dumpDpxOriginationInfo(DpxOriginationInformation* originInfo) {
d_printf("\n--Origination Information--\n");
- d_printf("X offset %ld\n", (long)ntohl(originInfo->x_offset));
- d_printf("Y offset %ld\n", (long)ntohl(originInfo->y_offset));
+ d_printf("X offset %ld\n", (intptr_t)ntohl(originInfo->x_offset));
+ d_printf("Y offset %ld\n", (intptr_t)ntohl(originInfo->y_offset));
d_printf("X centre %f\n", ntohf(originInfo->x_centre));
d_printf("Y centre %f\n", ntohf(originInfo->y_centre));
- d_printf("Original X %ld\n", (long)ntohl(originInfo->x_original_size));
- d_printf("Original Y %ld\n", (long)ntohl(originInfo->y_original_size));
+ d_printf("Original X %ld\n", (intptr_t)ntohl(originInfo->x_original_size));
+ d_printf("Original Y %ld\n", (intptr_t)ntohl(originInfo->y_original_size));
d_printf("File name \"%s\"\n", originInfo->file_name);
d_printf("Creation time \"%s\"\n", originInfo->creation_time);
d_printf("Input device \"%s\"\n", originInfo->input_device);
@@ -275,8 +275,10 @@ dpxGetRowBytes(DpxFile* dpx, unsigned short* row, int y) {
/* extract required pixels */
for (pixelIndex = 0; pixelIndex < numPixels; ++pixelIndex) {
- /* row[pixelIndex] = dpx->lut10[dpx->pixelBuffer[pixelIndex]]; */
- row[pixelIndex] = dpx->pixelBuffer[pixelIndex] << 6;
+ if(dpx->params.doLogarithm)
+ row[pixelIndex] = dpx->lut10_16[dpx->pixelBuffer[pixelIndex]];
+ else
+ row[pixelIndex] = dpx->pixelBuffer[pixelIndex] << 6;
}
/* save remaining pixels */
@@ -316,8 +318,10 @@ dpxSetRowBytes(DpxFile* dpx, const unsigned short* row, int y) {
/* put new pixels into pixelBuffer */
for (pixelIndex = 0; pixelIndex < numPixels; ++pixelIndex) {
- /* dpx->pixelBuffer[dpx->pixelBufferUsed + pixelIndex] = dpx->lut8[row[pixelIndex]]; */
- dpx->pixelBuffer[dpx->pixelBufferUsed + pixelIndex] = row[pixelIndex] >> 6;
+ if(dpx->params.doLogarithm)
+ dpx->pixelBuffer[dpx->pixelBufferUsed + pixelIndex] = dpx->lut16_16[row[pixelIndex]];
+ else
+ dpx->pixelBuffer[dpx->pixelBufferUsed + pixelIndex] = row[pixelIndex] >> 6;
}
dpx->pixelBufferUsed += numPixels;
@@ -413,7 +417,7 @@ intern_dpxOpen(int mode, const char* bytestuff, int bufsize) {
/* let's assume dpx files are always network order */
if (header.fileInfo.magic_num != ntohl(DPX_FILE_MAGIC)) {
if (verbose) d_printf("Bad magic number %8.8lX in \"%s\".\n",
- (unsigned long)ntohl(header.fileInfo.magic_num), filename);
+ (uintptr_t)ntohl(header.fileInfo.magic_num), filename);
dpxClose(dpx);
return 0;
}
@@ -437,10 +441,15 @@ intern_dpxOpen(int mode, const char* bytestuff, int bufsize) {
default: break;
}
}
- dpx->bitsPerPixel = 10;
- /* dpx->bitsPerPixel = header.imageInfo.channel[0].bits_per_pixel; */
- dpx->imageOffset = ntohl(header.fileInfo.offset);
+ /* dpx->bitsPerPixel = 10; */
+ dpx->bitsPerPixel = header.imageInfo.channel[0].bits_per_pixel;
+ if (dpx->bitsPerPixel != 10) {
+ if (verbose) d_printf("Don't support depth: %d\n", dpx->bitsPerPixel);
+ dpxClose(dpx);
+ return 0;
+ }
+ dpx->imageOffset = ntohl(header.fileInfo.offset);
dpx->lineBufferLength = pixelsToLongs(dpx->width * dpx->depth);
dpx->lineBuffer = malloc(dpx->lineBufferLength * 4);
if (dpx->lineBuffer == 0) {
@@ -467,6 +476,26 @@ intern_dpxOpen(int mode, const char* bytestuff, int bufsize) {
dpx->fileYPos = 0;
logImageGetByteConversionDefaults(&dpx->params);
+ /* The SMPTE define this code:
+ * 2 - Linear
+ * 3 - Logarithmic
+ *
+ * Note that transfer_characteristics is U8, don't need
+ * check the byte order.
+ */
+ switch (header.imageInfo.channel[0].transfer_characteristics) {
+ case 2:
+ dpx->params.doLogarithm= 0;
+ break;
+ case 3:
+ dpx->params.doLogarithm= 1;
+ break;
+ default:
+ if (verbose) d_printf("Un-supported Transfer Characteristics: %d\n", header.imageInfo.channel[0].transfer_characteristics);
+ dpxClose(dpx);
+ return 0;
+ break;
+ }
setupLut(dpx);
dpx->getRow = &dpxGetRowBytes;
@@ -559,6 +588,18 @@ dpxCreate(const char* filename, int width, int height, int depth) {
++shortFilename;
}
initDpxMainHeader(dpx, &header, shortFilename);
+ logImageGetByteConversionDefaults(&dpx->params);
+ /* Need set the file type before write the header!
+ * 2 - Linear
+ * 3 - Logarithmic
+ *
+ * Note that transfer characteristics is U8, don't need
+ * check the byte order.
+ */
+ if (dpx->params.doLogarithm == 0)
+ header.imageInfo.channel[0].transfer_characteristics= 2;
+ else
+ header.imageInfo.channel[0].transfer_characteristics= 3;
if (fwrite(&header, sizeof(header), 1, dpx->file) == 0) {
if (verbose) d_printf("Couldn't write image header\n");
@@ -566,8 +607,6 @@ dpxCreate(const char* filename, int width, int height, int depth) {
return 0;
}
dpx->fileYPos = 0;
-
- logImageGetByteConversionDefaults(&dpx->params);
setupLut(dpx);
dpx->getRow = 0;
diff --git a/source/blender/imbuf/intern/cineon/logImageCore.c b/source/blender/imbuf/intern/cineon/logImageCore.c
index e88e9241443..6032f342ed8 100644
--- a/source/blender/imbuf/intern/cineon/logImageCore.c
+++ b/source/blender/imbuf/intern/cineon/logImageCore.c
@@ -93,6 +93,35 @@ setupLut(LogImageFile *logImage) {
}
}
+/* set up the 10 bit to 16 bit and 16 bit to 10 bit tables */
+void
+setupLut16(LogImageFile *logImage) {
+
+ int i;
+ double f_black;
+ double scale;
+
+ f_black = convertTo(logImage->params.blackPoint, logImage->params.whitePoint, logImage->params.gamma);
+ scale = 65535.0 / (1.0 - f_black);
+
+ for (i = 0; i <= logImage->params.blackPoint; ++i) {
+ logImage->lut10_16[i] = 0;
+ }
+ for (; i < logImage->params.whitePoint; ++i) {
+ double f_i;
+ f_i = convertTo(i, logImage->params.whitePoint, logImage->params.gamma);
+ logImage->lut10_16[i] = (int)rint(scale * (f_i - f_black));
+ }
+ for (; i < 1024; ++i) {
+ logImage->lut10_16[i] = 65535;
+ }
+
+ for (i = 0; i < 65536; ++i) {
+ double f_i = f_black + (i / 65535.0) * (1.0 - f_black);
+ logImage->lut16_16[i] = convertFrom(f_i, logImage->params.whitePoint, logImage->params.gamma);
+ }
+}
+
/* how many longwords to hold this many pixels? */
int
pixelsToLongs(int numPixels) {
diff --git a/source/blender/imbuf/intern/cineon/logImageCore.h b/source/blender/imbuf/intern/cineon/logImageCore.h
index 1af18d5e3b8..2646e8b3c12 100644
--- a/source/blender/imbuf/intern/cineon/logImageCore.h
+++ b/source/blender/imbuf/intern/cineon/logImageCore.h
@@ -34,7 +34,9 @@
extern "C" {
#endif
-
+#include "BLO_sys_types.h" // for intptr_t support
+#undef ntohl
+#undef htonl
typedef int (GetRowFn)(LogImageFile* logImage, unsigned short* row, int lineNum);
typedef int (SetRowFn)(LogImageFile* logImage, const unsigned short* row, int lineNum);
typedef void (CloseFn)(LogImageFile* logImage);
@@ -71,17 +73,21 @@ struct _Log_Image_File_t_
unsigned char lut10[1024];
unsigned short lut8[256];
+ unsigned short lut10_16[1024];
+ unsigned short lut16_16[65536];
+
/* pixel access functions */
GetRowFn* getRow;
SetRowFn* setRow;
CloseFn* close;
unsigned char *membuffer;
- unsigned long membuffersize;
+ uintptr_t membuffersize;
unsigned char *memcursor;
};
void setupLut(LogImageFile*);
+void setupLut16(LogImageFile*);
int pixelsToLongs(int numPixels);
diff --git a/source/blender/imbuf/intern/cineon/logImageLib.c b/source/blender/imbuf/intern/cineon/logImageLib.c
index ff209d5ebd0..2fc52959ff6 100644
--- a/source/blender/imbuf/intern/cineon/logImageLib.c
+++ b/source/blender/imbuf/intern/cineon/logImageLib.c
@@ -89,6 +89,7 @@ logImageGetByteConversionDefaults(LogImageByteConversionParameters* params) {
params->gamma = DEFAULT_GAMMA;
params->blackPoint = DEFAULT_BLACK_POINT;
params->whitePoint = DEFAULT_WHITE_POINT;
+ params->doLogarithm = 0;
return 0;
}
@@ -97,6 +98,7 @@ logImageGetByteConversion(const LogImageFile* logImage, LogImageByteConversionPa
params->gamma = logImage->params.gamma;
params->blackPoint = logImage->params.blackPoint;
params->whitePoint = logImage->params.whitePoint;
+ params->doLogarithm = 0;
return 0;
}
@@ -110,7 +112,8 @@ logImageSetByteConversion(LogImageFile* logImage, const LogImageByteConversionPa
logImage->params.gamma = params->gamma;
logImage->params.blackPoint = params->blackPoint;
logImage->params.whitePoint = params->whitePoint;
- setupLut(logImage);
+ logImage->params.doLogarithm = params->doLogarithm;
+ setupLut16(logImage);
return 0;
}
return 1;
diff --git a/source/blender/imbuf/intern/cineon/logImageLib.h b/source/blender/imbuf/intern/cineon/logImageLib.h
index ea45c675fe2..617da1d0d92 100644
--- a/source/blender/imbuf/intern/cineon/logImageLib.h
+++ b/source/blender/imbuf/intern/cineon/logImageLib.h
@@ -47,6 +47,7 @@ typedef struct {
float gamma;
int blackPoint;
int whitePoint;
+ int doLogarithm;
} LogImageByteConversionParameters;
/* int functions return 0 for OK */
diff --git a/source/blender/imbuf/intern/cineon/logmemfile.c b/source/blender/imbuf/intern/cineon/logmemfile.c
index 20359335933..160e8453713 100644
--- a/source/blender/imbuf/intern/cineon/logmemfile.c
+++ b/source/blender/imbuf/intern/cineon/logmemfile.c
@@ -24,10 +24,10 @@
#include "logImageCore.h"
-int logimage_fseek(void* logfile, long offsett, int origin)
+int logimage_fseek(void* logfile, intptr_t offsett, int origin)
{
struct _Log_Image_File_t_ *file = (struct _Log_Image_File_t_*) logfile;
- long offset = offsett;
+ intptr_t offset = offsett;
if (file->file) fseek(file->file, offset, origin);
else { /*we're seeking in memory*/
@@ -38,7 +38,7 @@ int logimage_fseek(void* logfile, long offsett, int origin)
if (offset > file->membuffersize) return 1;
file->memcursor = (file->membuffer + file->membuffersize) - offset;
} else if (origin==SEEK_CUR) {
- unsigned long pos = (unsigned long)file->membuffer - (unsigned long)file->memcursor;
+ uintptr_t pos = (uintptr_t)file->membuffer - (uintptr_t)file->memcursor;
if (pos + offset > file->membuffersize) return 1;
if (pos < 0) return 1;
file->memcursor += offset;
diff --git a/source/blender/imbuf/intern/cineon/logmemfile.h b/source/blender/imbuf/intern/cineon/logmemfile.h
index 6e82cf2b145..39e2f36dad9 100644
--- a/source/blender/imbuf/intern/cineon/logmemfile.h
+++ b/source/blender/imbuf/intern/cineon/logmemfile.h
@@ -22,7 +22,7 @@
#ifndef _LOGMEMFILE_H
#define _LOGMEMFILE_H
-int logimage_fseek(void* logfile, long offsett, int origin);
+int logimage_fseek(void* logfile, intptr_t offsett, int origin);
int logimage_fwrite(void *buffer, unsigned int size, unsigned int count, void *logfile);
int logimage_fread(void *buffer, unsigned int size, unsigned int count, void *logfile);
diff --git a/source/blender/imbuf/intern/dds/BlockDXT.cpp b/source/blender/imbuf/intern/dds/BlockDXT.cpp
index 44435317f69..2a8a2c470c4 100644
--- a/source/blender/imbuf/intern/dds/BlockDXT.cpp
+++ b/source/blender/imbuf/intern/dds/BlockDXT.cpp
@@ -61,7 +61,7 @@
BlockDXT1
----------------------------------------------------------------------------*/
-unsigned int BlockDXT1::evaluatePalette(Color32 color_array[4]) const
+uint BlockDXT1::evaluatePalette(Color32 color_array[4]) const
{
// Does bit expansion before interpolation.
color_array[0].b = (col0.b << 3) | (col0.b >> 2);
@@ -176,9 +176,9 @@ void BlockDXT1::decodeBlock(ColorBlock * block) const
evaluatePalette(color_array);
// Write color block.
- for( unsigned int j = 0; j < 4; j++ ) {
- for( unsigned int i = 0; i < 4; i++ ) {
- unsigned int idx = (row[j] >> (2 * i)) & 3;
+ for( uint j = 0; j < 4; j++ ) {
+ for( uint i = 0; i < 4; i++ ) {
+ uint idx = (row[j] >> (2 * i)) & 3;
block->color(i, j) = color_array[idx];
}
}
@@ -187,7 +187,7 @@ void BlockDXT1::decodeBlock(ColorBlock * block) const
void BlockDXT1::setIndices(int * idx)
{
indices = 0;
- for(unsigned int i = 0; i < 16; i++) {
+ for(uint i = 0; i < 16; i++) {
indices |= (idx[i] & 3) << (2 * i);
}
}
@@ -196,16 +196,14 @@ void BlockDXT1::setIndices(int * idx)
/// Flip DXT1 block vertically.
inline void BlockDXT1::flip4()
{
- unsigned char tmp;
- swap(row[0], row[3], tmp);
- swap(row[1], row[2], tmp);
+ swap(row[0], row[3]);
+ swap(row[1], row[2]);
}
/// Flip half DXT1 block vertically.
inline void BlockDXT1::flip2()
{
- unsigned char tmp;
- swap(row[0], row[1], tmp);
+ swap(row[0], row[1]);
}
@@ -245,16 +243,14 @@ void AlphaBlockDXT3::decodeBlock(ColorBlock * block) const
/// Flip DXT3 alpha block vertically.
void AlphaBlockDXT3::flip4()
{
- unsigned short tmp;
- swap(row[0], row[3], tmp);
- swap(row[1], row[2], tmp);
+ swap(row[0], row[3]);
+ swap(row[1], row[2]);
}
/// Flip half DXT3 alpha block vertically.
void AlphaBlockDXT3::flip2()
{
- unsigned short tmp;
- swap(row[0], row[1], tmp);
+ swap(row[0], row[1]);
}
/// Flip DXT3 block vertically.
@@ -276,9 +272,9 @@ void BlockDXT3::flip2()
BlockDXT5
----------------------------------------------------------------------------*/
-void AlphaBlockDXT5::evaluatePalette(unsigned char alpha[8]) const
+void AlphaBlockDXT5::evaluatePalette(uint8 alpha[8]) const
{
- if (alpha0 > alpha1) {
+ if (alpha0() > alpha1()) {
evaluatePalette8(alpha);
}
else {
@@ -286,100 +282,100 @@ void AlphaBlockDXT5::evaluatePalette(unsigned char alpha[8]) const
}
}
-void AlphaBlockDXT5::evaluatePalette8(unsigned char alpha[8]) const
+void AlphaBlockDXT5::evaluatePalette8(uint8 alpha[8]) const
{
// 8-alpha block: derive the other six alphas.
// Bit code 000 = alpha0, 001 = alpha1, others are interpolated.
- alpha[0] = alpha0;
- alpha[1] = alpha1;
- alpha[2] = (6 * alpha0 + 1 * alpha1) / 7; // bit code 010
- alpha[3] = (5 * alpha0 + 2 * alpha1) / 7; // bit code 011
- alpha[4] = (4 * alpha0 + 3 * alpha1) / 7; // bit code 100
- alpha[5] = (3 * alpha0 + 4 * alpha1) / 7; // bit code 101
- alpha[6] = (2 * alpha0 + 5 * alpha1) / 7; // bit code 110
- alpha[7] = (1 * alpha0 + 6 * alpha1) / 7; // bit code 111
+ alpha[0] = alpha0();
+ alpha[1] = alpha1();
+ alpha[2] = (6 * alpha[0] + 1 * alpha[1]) / 7; // bit code 010
+ alpha[3] = (5 * alpha[0] + 2 * alpha[1]) / 7; // bit code 011
+ alpha[4] = (4 * alpha[0] + 3 * alpha[1]) / 7; // bit code 100
+ alpha[5] = (3 * alpha[0] + 4 * alpha[1]) / 7; // bit code 101
+ alpha[6] = (2 * alpha[0] + 5 * alpha[1]) / 7; // bit code 110
+ alpha[7] = (1 * alpha[0] + 6 * alpha[1]) / 7; // bit code 111
}
-void AlphaBlockDXT5::evaluatePalette6(unsigned char alpha[8]) const
+void AlphaBlockDXT5::evaluatePalette6(uint8 alpha[8]) const
{
// 6-alpha block.
// Bit code 000 = alpha0, 001 = alpha1, others are interpolated.
- alpha[0] = alpha0;
- alpha[1] = alpha1;
- alpha[2] = (4 * alpha0 + 1 * alpha1) / 5; // Bit code 010
- alpha[3] = (3 * alpha0 + 2 * alpha1) / 5; // Bit code 011
- alpha[4] = (2 * alpha0 + 3 * alpha1) / 5; // Bit code 100
- alpha[5] = (1 * alpha0 + 4 * alpha1) / 5; // Bit code 101
+ alpha[0] = alpha0();
+ alpha[1] = alpha1();
+ alpha[2] = (4 * alpha[0] + 1 * alpha[1]) / 5; // Bit code 010
+ alpha[3] = (3 * alpha[0] + 2 * alpha[1]) / 5; // Bit code 011
+ alpha[4] = (2 * alpha[0] + 3 * alpha[1]) / 5; // Bit code 100
+ alpha[5] = (1 * alpha[0] + 4 * alpha[1]) / 5; // Bit code 101
alpha[6] = 0x00; // Bit code 110
alpha[7] = 0xFF; // Bit code 111
}
-void AlphaBlockDXT5::indices(unsigned char index_array[16]) const
+void AlphaBlockDXT5::indices(uint8 index_array[16]) const
{
- index_array[0x0] = bits0;
- index_array[0x1] = bits1;
- index_array[0x2] = bits2;
- index_array[0x3] = bits3;
- index_array[0x4] = bits4;
- index_array[0x5] = bits5;
- index_array[0x6] = bits6;
- index_array[0x7] = bits7;
- index_array[0x8] = bits8;
- index_array[0x9] = bits9;
- index_array[0xA] = bitsA;
- index_array[0xB] = bitsB;
- index_array[0xC] = bitsC;
- index_array[0xD] = bitsD;
- index_array[0xE] = bitsE;
- index_array[0xF] = bitsF;
+ index_array[0x0] = bits0();
+ index_array[0x1] = bits1();
+ index_array[0x2] = bits2();
+ index_array[0x3] = bits3();
+ index_array[0x4] = bits4();
+ index_array[0x5] = bits5();
+ index_array[0x6] = bits6();
+ index_array[0x7] = bits7();
+ index_array[0x8] = bits8();
+ index_array[0x9] = bits9();
+ index_array[0xA] = bitsA();
+ index_array[0xB] = bitsB();
+ index_array[0xC] = bitsC();
+ index_array[0xD] = bitsD();
+ index_array[0xE] = bitsE();
+ index_array[0xF] = bitsF();
}
-unsigned int AlphaBlockDXT5::index(unsigned int index) const
+uint AlphaBlockDXT5::index(uint index) const
{
int offset = (3 * index + 16);
- return (this->u >> offset) & 0x7;
+ return uint((this->u >> offset) & 0x7);
}
-void AlphaBlockDXT5::setIndex(unsigned int index, unsigned int value)
+void AlphaBlockDXT5::setIndex(uint index, uint value)
{
int offset = (3 * index + 16);
- unsigned long long mask = ((unsigned long long)(0x7)) << offset;
- this->u = (this->u & ~mask) | (((unsigned long long)(value)) << offset);
+ uint64 mask = uint64(0x7) << offset;
+ this->u = (this->u & ~mask) | (uint64(value) << offset);
}
void AlphaBlockDXT5::decodeBlock(ColorBlock * block) const
{
- unsigned char alpha_array[8];
+ uint8 alpha_array[8];
evaluatePalette(alpha_array);
- unsigned char index_array[16];
+ uint8 index_array[16];
indices(index_array);
- for(unsigned int i = 0; i < 16; i++) {
+ for(uint i = 0; i < 16; i++) {
block->color(i).a = alpha_array[index_array[i]];
}
}
void AlphaBlockDXT5::flip4()
{
- unsigned long long * b = (unsigned long long *)this;
+ uint64 * b = (uint64 *)this;
// @@ The masks might have to be byte swapped.
- unsigned long long tmp = (*b & (unsigned long long)(0x000000000000FFFFLL));
- tmp |= (*b & (unsigned long long)(0x000000000FFF0000LL)) << 36;
- tmp |= (*b & (unsigned long long)(0x000000FFF0000000LL)) << 12;
- tmp |= (*b & (unsigned long long)(0x000FFF0000000000LL)) >> 12;
- tmp |= (*b & (unsigned long long)(0xFFF0000000000000LL)) >> 36;
+ uint64 tmp = (*b & (uint64)(0x000000000000FFFFLL));
+ tmp |= (*b & (uint64)(0x000000000FFF0000LL)) << 36;
+ tmp |= (*b & (uint64)(0x000000FFF0000000LL)) << 12;
+ tmp |= (*b & (uint64)(0x000FFF0000000000LL)) >> 12;
+ tmp |= (*b & (uint64)(0xFFF0000000000000LL)) >> 36;
*b = tmp;
}
void AlphaBlockDXT5::flip2()
{
- unsigned int * b = (unsigned int *)this;
+ uint * b = (uint *)this;
// @@ The masks might have to be byte swapped.
- unsigned int tmp = (*b & 0xFF000000);
+ uint tmp = (*b & 0xFF000000);
tmp |= (*b & 0x00000FFF) << 12;
tmp |= (*b & 0x00FFF000) >> 12;
@@ -393,6 +389,7 @@ void BlockDXT5::decodeBlock(ColorBlock * block) const
// Decode alpha.
alpha.decodeBlock(block);
+
}
/// Flip DXT5 block vertically.
@@ -413,13 +410,13 @@ void BlockDXT5::flip2()
/// Decode ATI1 block.
void BlockATI1::decodeBlock(ColorBlock * block) const
{
- unsigned char alpha_array[8];
+ uint8 alpha_array[8];
alpha.evaluatePalette(alpha_array);
- unsigned char index_array[16];
+ uint8 index_array[16];
alpha.indices(index_array);
- for(unsigned int i = 0; i < 16; i++) {
+ for(uint i = 0; i < 16; i++) {
Color32 & c = block->color(i);
c.b = c.g = c.r = alpha_array[index_array[i]];
c.a = 255;
@@ -442,13 +439,13 @@ void BlockATI1::flip2()
/// Decode ATI2 block.
void BlockATI2::decodeBlock(ColorBlock * block) const
{
- unsigned char alpha_array[8];
- unsigned char index_array[16];
+ uint8 alpha_array[8];
+ uint8 index_array[16];
x.evaluatePalette(alpha_array);
x.indices(index_array);
- for(unsigned int i = 0; i < 16; i++) {
+ for(uint i = 0; i < 16; i++) {
Color32 & c = block->color(i);
c.r = alpha_array[index_array[i]];
}
@@ -456,7 +453,7 @@ void BlockATI2::decodeBlock(ColorBlock * block) const
y.evaluatePalette(alpha_array);
y.indices(index_array);
- for(unsigned int i = 0; i < 16; i++) {
+ for(uint i = 0; i < 16; i++) {
Color32 & c = block->color(i);
c.g = alpha_array[index_array[i]];
c.b = 0;
@@ -478,6 +475,68 @@ void BlockATI2::flip2()
y.flip2();
}
+
+void BlockCTX1::evaluatePalette(Color32 color_array[4]) const
+{
+ // Does bit expansion before interpolation.
+ color_array[0].b = 0x00;
+ color_array[0].g = col0[1];
+ color_array[0].r = col0[0];
+ color_array[0].a = 0xFF;
+
+ color_array[1].r = 0x00;
+ color_array[1].g = col0[1];
+ color_array[1].b = col1[0];
+ color_array[1].a = 0xFF;
+
+ color_array[2].r = 0x00;
+ color_array[2].g = (2 * color_array[0].g + color_array[1].g) / 3;
+ color_array[2].b = (2 * color_array[0].b + color_array[1].b) / 3;
+ color_array[2].a = 0xFF;
+
+ color_array[3].r = 0x00;
+ color_array[3].g = (2 * color_array[1].g + color_array[0].g) / 3;
+ color_array[3].b = (2 * color_array[1].b + color_array[0].b) / 3;
+ color_array[3].a = 0xFF;
+}
+
+void BlockCTX1::decodeBlock(ColorBlock * block) const
+{
+ // Decode color block.
+ Color32 color_array[4];
+ evaluatePalette(color_array);
+
+ // Write color block.
+ for( uint j = 0; j < 4; j++ ) {
+ for( uint i = 0; i < 4; i++ ) {
+ uint idx = (row[j] >> (2 * i)) & 3;
+ block->color(i, j) = color_array[idx];
+ }
+ }
+}
+
+void BlockCTX1::setIndices(int * idx)
+{
+ indices = 0;
+ for(uint i = 0; i < 16; i++) {
+ indices |= (idx[i] & 3) << (2 * i);
+ }
+}
+
+
+/// Flip CTX1 block vertically.
+inline void BlockCTX1::flip4()
+{
+ swap(row[0], row[3]);
+ swap(row[1], row[2]);
+}
+
+/// Flip half CTX1 block vertically.
+inline void BlockCTX1::flip2()
+{
+ swap(row[0], row[1]);
+}
+
void mem_read(Stream & mem, BlockDXT1 & block)
{
mem_read(mem, block.col0.u);
@@ -518,3 +577,12 @@ void mem_read(Stream & mem, BlockATI2 & block)
mem_read(mem, block.y);
}
+void mem_read(Stream & mem, BlockCTX1 & block)
+{
+ mem_read(mem, block.col0[0]);
+ mem_read(mem, block.col0[1]);
+ mem_read(mem, block.col1[0]);
+ mem_read(mem, block.col1[1]);
+ mem_read(mem, block.indices);
+}
+
diff --git a/source/blender/imbuf/intern/dds/BlockDXT.h b/source/blender/imbuf/intern/dds/BlockDXT.h
index 8381c4705ae..3f9a81e40c8 100644
--- a/source/blender/imbuf/intern/dds/BlockDXT.h
+++ b/source/blender/imbuf/intern/dds/BlockDXT.h
@@ -55,6 +55,7 @@
#ifndef _DDS_BLOCKDXT_H
#define _DDS_BLOCKDXT_H
+#include <Common.h>
#include <Color.h>
#include <ColorBlock.h>
#include <Stream.h>
@@ -65,14 +66,14 @@ struct BlockDXT1
Color16 col0;
Color16 col1;
union {
- unsigned char row[4];
- unsigned int indices;
+ uint8 row[4];
+ uint indices;
};
bool isFourColorMode() const;
- unsigned int evaluatePalette(Color32 color_array[4]) const;
- unsigned int evaluatePaletteFast(Color32 color_array[4]) const;
+ uint evaluatePalette(Color32 color_array[4]) const;
+ uint evaluatePaletteFast(Color32 color_array[4]) const;
void evaluatePalette3(Color32 color_array[4]) const;
void evaluatePalette4(Color32 color_array[4]) const;
@@ -87,7 +88,7 @@ struct BlockDXT1
/// Return true if the block uses four color mode, false otherwise.
inline bool BlockDXT1::isFourColorMode() const
{
- return col0.u >= col1.u; // @@ > or >= ?
+ return col0.u > col1.u;
}
@@ -96,24 +97,24 @@ struct AlphaBlockDXT3
{
union {
struct {
- unsigned int alpha0 : 4;
- unsigned int alpha1 : 4;
- unsigned int alpha2 : 4;
- unsigned int alpha3 : 4;
- unsigned int alpha4 : 4;
- unsigned int alpha5 : 4;
- unsigned int alpha6 : 4;
- unsigned int alpha7 : 4;
- unsigned int alpha8 : 4;
- unsigned int alpha9 : 4;
- unsigned int alphaA : 4;
- unsigned int alphaB : 4;
- unsigned int alphaC : 4;
- unsigned int alphaD : 4;
- unsigned int alphaE : 4;
- unsigned int alphaF : 4;
+ uint alpha0 : 4;
+ uint alpha1 : 4;
+ uint alpha2 : 4;
+ uint alpha3 : 4;
+ uint alpha4 : 4;
+ uint alpha5 : 4;
+ uint alpha6 : 4;
+ uint alpha7 : 4;
+ uint alpha8 : 4;
+ uint alpha9 : 4;
+ uint alphaA : 4;
+ uint alphaB : 4;
+ uint alphaC : 4;
+ uint alphaD : 4;
+ uint alphaE : 4;
+ uint alphaF : 4;
};
- unsigned short row[4];
+ uint16 row[4];
};
void decodeBlock(ColorBlock * block) const;
@@ -139,37 +140,59 @@ struct BlockDXT3
/// DXT5 alpha block.
struct AlphaBlockDXT5
{
+ // uint64 unions do not compile on all platforms
+ /*
union {
struct {
- unsigned int alpha0 : 8; // 8
- unsigned int alpha1 : 8; // 16
- unsigned int bits0 : 3; // 3 - 19
- unsigned int bits1 : 3; // 6 - 22
- unsigned int bits2 : 3; // 9 - 25
- unsigned int bits3 : 3; // 12 - 28
- unsigned int bits4 : 3; // 15 - 31
- unsigned int bits5 : 3; // 18 - 34
- unsigned int bits6 : 3; // 21 - 37
- unsigned int bits7 : 3; // 24 - 40
- unsigned int bits8 : 3; // 27 - 43
- unsigned int bits9 : 3; // 30 - 46
- unsigned int bitsA : 3; // 33 - 49
- unsigned int bitsB : 3; // 36 - 52
- unsigned int bitsC : 3; // 39 - 55
- unsigned int bitsD : 3; // 42 - 58
- unsigned int bitsE : 3; // 45 - 61
- unsigned int bitsF : 3; // 48 - 64
+ uint64 alpha0 : 8; // 8
+ uint64 alpha1 : 8; // 16
+ uint64 bits0 : 3; // 3 - 19
+ uint64 bits1 : 3; // 6 - 22
+ uint64 bits2 : 3; // 9 - 25
+ uint64 bits3 : 3; // 12 - 28
+ uint64 bits4 : 3; // 15 - 31
+ uint64 bits5 : 3; // 18 - 34
+ uint64 bits6 : 3; // 21 - 37
+ uint64 bits7 : 3; // 24 - 40
+ uint64 bits8 : 3; // 27 - 43
+ uint64 bits9 : 3; // 30 - 46
+ uint64 bitsA : 3; // 33 - 49
+ uint64 bitsB : 3; // 36 - 52
+ uint64 bitsC : 3; // 39 - 55
+ uint64 bitsD : 3; // 42 - 58
+ uint64 bitsE : 3; // 45 - 61
+ uint64 bitsF : 3; // 48 - 64
};
- unsigned long long u;
+ uint64 u;
};
+ */
+ uint64 u;
+ uint8 alpha0() const { return u & 0xffLL; };
+ uint8 alpha1() const { return (u >> 8) & 0xffLL; };
+ uint8 bits0() const { return (u >> 16) & 0x7LL; };
+ uint8 bits1() const { return (u >> 19) & 0x7LL; };
+ uint8 bits2() const { return (u >> 22) & 0x7LL; };
+ uint8 bits3() const { return (u >> 25) & 0x7LL; };
+ uint8 bits4() const { return (u >> 28) & 0x7LL; };
+ uint8 bits5() const { return (u >> 31) & 0x7LL; };
+ uint8 bits6() const { return (u >> 34) & 0x7LL; };
+ uint8 bits7() const { return (u >> 37) & 0x7LL; };
+ uint8 bits8() const { return (u >> 40) & 0x7LL; };
+ uint8 bits9() const { return (u >> 43) & 0x7LL; };
+ uint8 bitsA() const { return (u >> 46) & 0x7LL; };
+ uint8 bitsB() const { return (u >> 49) & 0x7LL; };
+ uint8 bitsC() const { return (u >> 52) & 0x7LL; };
+ uint8 bitsD() const { return (u >> 55) & 0x7LL; };
+ uint8 bitsE() const { return (u >> 58) & 0x7LL; };
+ uint8 bitsF() const { return (u >> 61) & 0x7LL; };
- void evaluatePalette(unsigned char alpha[8]) const;
- void evaluatePalette8(unsigned char alpha[8]) const;
- void evaluatePalette6(unsigned char alpha[8]) const;
- void indices(unsigned char index_array[16]) const;
+ void evaluatePalette(uint8 alpha[8]) const;
+ void evaluatePalette8(uint8 alpha[8]) const;
+ void evaluatePalette6(uint8 alpha[8]) const;
+ void indices(uint8 index_array[16]) const;
- unsigned int index(unsigned int index) const;
- void setIndex(unsigned int index, unsigned int value);
+ uint index(uint index) const;
+ void setIndex(uint index, uint value);
void decodeBlock(ColorBlock * block) const;
@@ -213,6 +236,25 @@ struct BlockATI2
void flip2();
};
+/// CTX1 block.
+struct BlockCTX1
+{
+ uint8 col0[2];
+ uint8 col1[2];
+ union {
+ uint8 row[4];
+ uint indices;
+ };
+
+ void evaluatePalette(Color32 color_array[4]) const;
+ void setIndices(int * idx);
+
+ void decodeBlock(ColorBlock * block) const;
+
+ void flip4();
+ void flip2();
+};
+
void mem_read(Stream & mem, BlockDXT1 & block);
void mem_read(Stream & mem, AlphaBlockDXT3 & block);
void mem_read(Stream & mem, BlockDXT3 & block);
@@ -220,5 +262,6 @@ void mem_read(Stream & mem, AlphaBlockDXT5 & block);
void mem_read(Stream & mem, BlockDXT5 & block);
void mem_read(Stream & mem, BlockATI1 & block);
void mem_read(Stream & mem, BlockATI2 & block);
+void mem_read(Stream & mem, BlockCTX1 & block);
#endif // _DDS_BLOCKDXT_H
diff --git a/source/blender/imbuf/intern/dds/CMakeLists.txt b/source/blender/imbuf/intern/dds/CMakeLists.txt
new file mode 100644
index 00000000000..842f53bd88b
--- /dev/null
+++ b/source/blender/imbuf/intern/dds/CMakeLists.txt
@@ -0,0 +1,45 @@
+# $Id: CMakeLists.txt 14444 2008-04-16 22:40:48Z hos $
+# ***** BEGIN GPL LICENSE BLOCK *****
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software Foundation,
+# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# The Original Code is Copyright (C) 2006, Blender Foundation
+# All rights reserved.
+#
+# The Original Code is: all of this file.
+#
+# Contributor(s):
+#
+# ***** END GPL LICENSE BLOCK *****
+
+FILE (GLOB SRC *.cpp)
+
+SET(INC
+ .
+ ../../../blenkernel
+ ../../../makesdna
+ ../../
+ ..
+ ../../../blenlib
+ intern/include
+ ../../../../../intern/guardedalloc
+)
+
+if(WITH_DDS)
+ ADD_DEFINITIONS(-DWITH_DDS)
+ENDIF(WITH_DDS)
+
+BLENDERLIB(bf_dds "${SRC}" "${INC}")
+#env.BlenderLib ('bf_dds', source_files, incs, defs, libtype=['core','player'], priority = [90, 200])
diff --git a/source/blender/imbuf/intern/dds/ColorBlock.cpp b/source/blender/imbuf/intern/dds/ColorBlock.cpp
index 2511f6b8b30..043fba9d675 100644
--- a/source/blender/imbuf/intern/dds/ColorBlock.cpp
+++ b/source/blender/imbuf/intern/dds/ColorBlock.cpp
@@ -36,13 +36,13 @@
#include <Common.h>
// Get approximate luminance.
- inline static unsigned int colorLuminance(Color32 c)
+ inline static uint colorLuminance(Color32 c)
{
return c.r + c.g + c.b;
}
// Get the euclidean distance between the given colors.
- inline static unsigned int colorDistance(Color32 c0, Color32 c1)
+ inline static uint colorDistance(Color32 c0, Color32 c1)
{
return (c0.r - c1.r) * (c0.r - c1.r) + (c0.g - c1.g) * (c0.g - c1.g) + (c0.b - c1.b) * (c0.b - c1.b);
}
@@ -53,25 +53,33 @@ ColorBlock::ColorBlock()
{
}
+/// Init the color block from an array of colors.
+ColorBlock::ColorBlock(const uint * linearImage)
+{
+ for(uint i = 0; i < 16; i++) {
+ color(i) = Color32(linearImage[i]);
+ }
+}
+
/// Init the color block with the contents of the given block.
ColorBlock::ColorBlock(const ColorBlock & block)
{
- for(unsigned int i = 0; i < 16; i++) {
+ for(uint i = 0; i < 16; i++) {
color(i) = block.color(i);
}
}
/// Initialize this color block.
-ColorBlock::ColorBlock(const Image * img, unsigned int x, unsigned int y)
+ColorBlock::ColorBlock(const Image * img, uint x, uint y)
{
init(img, x, y);
}
-void ColorBlock::init(const Image * img, unsigned int x, unsigned int y)
+void ColorBlock::init(const Image * img, uint x, uint y)
{
- const unsigned int bw = min(img->width() - x, 4U);
- const unsigned int bh = min(img->height() - y, 4U);
+ const uint bw = min(img->width() - x, 4U);
+ const uint bh = min(img->height() - y, 4U);
static int remainder[] = {
0, 0, 0, 0,
@@ -83,10 +91,10 @@ void ColorBlock::init(const Image * img, unsigned int x, unsigned int y)
// Blocks that are smaller than 4x4 are handled by repeating the pixels.
// @@ Thats only correct when block size is 1, 2 or 4, but not with 3. :(
- for(unsigned int i = 0; i < 4; i++) {
+ for(uint i = 0; i < 4; i++) {
//const int by = i % bh;
const int by = remainder[(bh - 1) * 4 + i];
- for(unsigned int e = 0; e < 4; e++) {
+ for(uint e = 0; e < 4; e++) {
//const int bx = e % bw;
const int bx = remainder[(bw - 1) * 4 + e];
color(e, i) = img->pixel(x + bx, y + by);
@@ -100,7 +108,7 @@ void ColorBlock::swizzleDXT5n()
for(int i = 0; i < 16; i++)
{
Color32 c = m_color[i];
- m_color[i] = Color32(0, c.g, 0, c.r);
+ m_color[i] = Color32(0xFF, c.g, 0, c.r);
}
}
@@ -108,7 +116,7 @@ void ColorBlock::splatX()
{
for(int i = 0; i < 16; i++)
{
- unsigned char x = m_color[i].r;
+ uint8 x = m_color[i].r;
m_color[i] = Color32(x, x, x, x);
}
}
@@ -117,16 +125,56 @@ void ColorBlock::splatY()
{
for(int i = 0; i < 16; i++)
{
- unsigned char y = m_color[i].g;
+ uint8 y = m_color[i].g;
m_color[i] = Color32(y, y, y, y);
}
}
+/// Returns true if the block has a single color.
+bool ColorBlock::isSingleColor() const
+{
+ Color32 mask(0xFF, 0xFF, 0xFF, 0x00);
+ uint u = m_color[0].u & mask.u;
+
+ for(int i = 1; i < 16; i++)
+ {
+ if (u != (m_color[i].u & mask.u))
+ {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+/// Returns true if the block has a single color, ignoring transparent pixels.
+bool ColorBlock::isSingleColorNoAlpha() const
+{
+ Color32 c;
+ int i;
+ for(i = 0; i < 16; i++)
+ {
+ if (m_color[i].a != 0) c = m_color[i];
+ }
+
+ Color32 mask(0xFF, 0xFF, 0xFF, 0x00);
+ uint u = c.u & mask.u;
+
+ for(; i < 16; i++)
+ {
+ if (u != (m_color[i].u & mask.u))
+ {
+ return false;
+ }
+ }
+
+ return true;
+}
/// Count number of unique colors in this color block.
-unsigned int ColorBlock::countUniqueColors() const
+uint ColorBlock::countUniqueColors() const
{
- unsigned int count = 0;
+ uint count = 0;
// @@ This does not have to be o(n^2)
for(int i = 0; i < 16; i++)
@@ -149,17 +197,27 @@ unsigned int ColorBlock::countUniqueColors() const
/// Get average color of the block.
Color32 ColorBlock::averageColor() const
{
- unsigned int r, g, b, a;
+ uint r, g, b, a;
r = g = b = a = 0;
- for(unsigned int i = 0; i < 16; i++) {
+ for(uint i = 0; i < 16; i++) {
r += m_color[i].r;
g += m_color[i].g;
b += m_color[i].b;
a += m_color[i].a;
}
- return Color32((unsigned char)(r / 16), (unsigned char)(g / 16), (unsigned char)(b / 16), (unsigned char)(a / 16));
+ return Color32(uint8(r / 16), uint8(g / 16), uint8(b / 16), uint8(a / 16));
+}
+
+/// Return true if the block is not fully opaque.
+bool ColorBlock::hasAlpha() const
+{
+ for (uint i = 0; i < 16; i++)
+ {
+ if (m_color[i].a != 255) return true;
+ }
+ return false;
}
@@ -167,11 +225,11 @@ Color32 ColorBlock::averageColor() const
void ColorBlock::diameterRange(Color32 * start, Color32 * end) const
{
Color32 c0, c1;
- unsigned int best_dist = 0;
+ uint best_dist = 0;
for(int i = 0; i < 16; i++) {
for (int j = i+1; j < 16; j++) {
- unsigned int dist = colorDistance(m_color[i], m_color[j]);
+ uint dist = colorDistance(m_color[i], m_color[j]);
if( dist > best_dist ) {
best_dist = dist;
c0 = m_color[i];
@@ -188,13 +246,13 @@ void ColorBlock::diameterRange(Color32 * start, Color32 * end) const
void ColorBlock::luminanceRange(Color32 * start, Color32 * end) const
{
Color32 minColor, maxColor;
- unsigned int minLuminance, maxLuminance;
+ uint minLuminance, maxLuminance;
maxLuminance = minLuminance = colorLuminance(m_color[0]);
- for(unsigned int i = 1; i < 16; i++)
+ for(uint i = 1; i < 16; i++)
{
- unsigned int luminance = colorLuminance(m_color[i]);
+ uint luminance = colorLuminance(m_color[i]);
if (luminance > maxLuminance) {
maxLuminance = luminance;
@@ -216,7 +274,7 @@ void ColorBlock::boundsRange(Color32 * start, Color32 * end) const
Color32 minColor(255, 255, 255);
Color32 maxColor(0, 0, 0);
- for(unsigned int i = 0; i < 16; i++)
+ for(uint i = 0; i < 16; i++)
{
if (m_color[i].r < minColor.r) { minColor.r = m_color[i].r; }
if (m_color[i].g < minColor.g) { minColor.g = m_color[i].g; }
@@ -250,7 +308,7 @@ void ColorBlock::boundsRangeAlpha(Color32 * start, Color32 * end) const
Color32 minColor(255, 255, 255, 255);
Color32 maxColor(0, 0, 0, 0);
- for(unsigned int i = 0; i < 16; i++)
+ for(uint i = 0; i < 16; i++)
{
if (m_color[i].r < minColor.r) { minColor.r = m_color[i].r; }
if (m_color[i].g < minColor.g) { minColor.g = m_color[i].g; }
@@ -287,11 +345,11 @@ void ColorBlock::boundsRangeAlpha(Color32 * start, Color32 * end) const
void ColorBlock::sortColorsByAbsoluteValue()
{
// Dummy selection sort.
- for( unsigned int a = 0; a < 16; a++ ) {
- unsigned int max = a;
+ for( uint a = 0; a < 16; a++ ) {
+ uint max = a;
Color16 cmax(m_color[a]);
- for( unsigned int b = a+1; b < 16; b++ ) {
+ for( uint b = a+1; b < 16; b++ ) {
Color16 cb(m_color[b]);
if( cb.u > cmax.u ) {
@@ -299,9 +357,6 @@ void ColorBlock::sortColorsByAbsoluteValue()
cmax = cb;
}
}
- Color32 tmp;
- swap( m_color[a], m_color[max], tmp );
+ swap( m_color[a], m_color[max] );
}
}
-
-
diff --git a/source/blender/imbuf/intern/dds/ColorBlock.h b/source/blender/imbuf/intern/dds/ColorBlock.h
index 0d195f73811..537c17346a1 100644
--- a/source/blender/imbuf/intern/dds/ColorBlock.h
+++ b/source/blender/imbuf/intern/dds/ColorBlock.h
@@ -41,23 +41,26 @@
struct ColorBlock
{
ColorBlock();
+ ColorBlock(const uint * linearImage);
ColorBlock(const ColorBlock & block);
- ColorBlock(const Image * img, unsigned int x, unsigned int y);
+ ColorBlock(const Image * img, uint x, uint y);
- void init(const Image * img, unsigned int x, unsigned int y);
+ void init(const Image * img, uint x, uint y);
void swizzleDXT5n();
void splatX();
void splatY();
- unsigned int countUniqueColors() const;
+ bool isSingleColor() const;
+ bool isSingleColorNoAlpha() const;
+ uint countUniqueColors() const;
Color32 averageColor() const;
+ bool hasAlpha() const;
void diameterRange(Color32 * start, Color32 * end) const;
void luminanceRange(Color32 * start, Color32 * end) const;
void boundsRange(Color32 * start, Color32 * end) const;
void boundsRangeAlpha(Color32 * start, Color32 * end) const;
- void bestFitRange(Color32 * start, Color32 * end) const;
void sortColorsByAbsoluteValue();
@@ -66,11 +69,11 @@ struct ColorBlock
// Accessors
const Color32 * colors() const;
- Color32 color(unsigned int i) const;
- Color32 & color(unsigned int i);
+ Color32 color(uint i) const;
+ Color32 & color(uint i);
- Color32 color(unsigned int x, unsigned int y) const;
- Color32 & color(unsigned int x, unsigned int y);
+ Color32 color(uint x, uint y) const;
+ Color32 & color(uint x, uint y);
private:
@@ -86,25 +89,25 @@ inline const Color32 * ColorBlock::colors() const
}
/// Get block color.
-inline Color32 ColorBlock::color(unsigned int i) const
+inline Color32 ColorBlock::color(uint i) const
{
return m_color[i];
}
/// Get block color.
-inline Color32 & ColorBlock::color(unsigned int i)
+inline Color32 & ColorBlock::color(uint i)
{
return m_color[i];
}
/// Get block color.
-inline Color32 ColorBlock::color(unsigned int x, unsigned int y) const
+inline Color32 ColorBlock::color(uint x, uint y) const
{
return m_color[y * 4 + x];
}
/// Get block color.
-inline Color32 & ColorBlock::color(unsigned int x, unsigned int y)
+inline Color32 & ColorBlock::color(uint x, uint y)
{
return m_color[y * 4 + x];
}
diff --git a/source/blender/imbuf/intern/dds/Common.h b/source/blender/imbuf/intern/dds/Common.h
index e504e7b1241..6f09346f770 100644
--- a/source/blender/imbuf/intern/dds/Common.h
+++ b/source/blender/imbuf/intern/dds/Common.h
@@ -34,8 +34,20 @@
#ifndef clamp
#define clamp(x,a,b) min(max((x), (a)), (b))
#endif
-#ifndef swap
-#define swap(a,b,tmp) tmp=a; a=b; b=tmp;
-#endif
+
+template<typename T>
+inline void
+swap(T & a, T & b)
+{
+ T tmp = a;
+ a = b;
+ b = tmp;
+}
+
+typedef unsigned char uint8;
+typedef unsigned short uint16;
+typedef unsigned int uint;
+typedef unsigned int uint32;
+typedef unsigned long long uint64;
#endif
diff --git a/source/blender/imbuf/intern/dds/DirectDrawSurface.cpp b/source/blender/imbuf/intern/dds/DirectDrawSurface.cpp
index f8eb7afa66b..0981ae88db6 100644
--- a/source/blender/imbuf/intern/dds/DirectDrawSurface.cpp
+++ b/source/blender/imbuf/intern/dds/DirectDrawSurface.cpp
@@ -52,103 +52,374 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
-#include <Common.h>
#include <DirectDrawSurface.h>
#include <BlockDXT.h>
+#include <PixelFormat.h>
#include <stdio.h> // printf
#include <math.h> // sqrt
+#include <sys/types.h>
/*** declarations ***/
#if !defined(MAKEFOURCC)
# define MAKEFOURCC(ch0, ch1, ch2, ch3) \
- ((unsigned int)((unsigned char)(ch0)) | \
- ((unsigned int)((unsigned char)(ch1)) << 8) | \
- ((unsigned int)((unsigned char)(ch2)) << 16) | \
- ((unsigned int)((unsigned char)(ch3)) << 24 ))
+ ((uint)((unsigned char)(ch0)) | \
+ ((uint)((unsigned char)(ch1)) << 8) | \
+ ((uint)((unsigned char)(ch2)) << 16) | \
+ ((uint)((unsigned char)(ch3)) << 24 ))
#endif
-static const unsigned int FOURCC_DDS = MAKEFOURCC('D', 'D', 'S', ' ');
-static const unsigned int FOURCC_DXT1 = MAKEFOURCC('D', 'X', 'T', '1');
-static const unsigned int FOURCC_DXT2 = MAKEFOURCC('D', 'X', 'T', '2');
-static const unsigned int FOURCC_DXT3 = MAKEFOURCC('D', 'X', 'T', '3');
-static const unsigned int FOURCC_DXT4 = MAKEFOURCC('D', 'X', 'T', '4');
-static const unsigned int FOURCC_DXT5 = MAKEFOURCC('D', 'X', 'T', '5');
-static const unsigned int FOURCC_RXGB = MAKEFOURCC('R', 'X', 'G', 'B');
-static const unsigned int FOURCC_ATI1 = MAKEFOURCC('A', 'T', 'I', '1');
-static const unsigned int FOURCC_ATI2 = MAKEFOURCC('A', 'T', 'I', '2');
-
-// RGB formats.
-static const unsigned int D3DFMT_R8G8B8 = 20;
-static const unsigned int D3DFMT_A8R8G8B8 = 21;
-static const unsigned int D3DFMT_X8R8G8B8 = 22;
-static const unsigned int D3DFMT_R5G6B5 = 23;
-static const unsigned int D3DFMT_X1R5G5B5 = 24;
-static const unsigned int D3DFMT_A1R5G5B5 = 25;
-static const unsigned int D3DFMT_A4R4G4B4 = 26;
-static const unsigned int D3DFMT_R3G3B2 = 27;
-static const unsigned int D3DFMT_A8 = 28;
-static const unsigned int D3DFMT_A8R3G3B2 = 29;
-static const unsigned int D3DFMT_X4R4G4B4 = 30;
-static const unsigned int D3DFMT_A2B10G10R10 = 31;
-static const unsigned int D3DFMT_A8B8G8R8 = 32;
-static const unsigned int D3DFMT_X8B8G8R8 = 33;
-static const unsigned int D3DFMT_G16R16 = 34;
-static const unsigned int D3DFMT_A2R10G10B10 = 35;
-static const unsigned int D3DFMT_A16B16G16R16 = 36;
+static const uint FOURCC_DDS = MAKEFOURCC('D', 'D', 'S', ' ');
+static const uint FOURCC_DXT1 = MAKEFOURCC('D', 'X', 'T', '1');
+static const uint FOURCC_DXT2 = MAKEFOURCC('D', 'X', 'T', '2');
+static const uint FOURCC_DXT3 = MAKEFOURCC('D', 'X', 'T', '3');
+static const uint FOURCC_DXT4 = MAKEFOURCC('D', 'X', 'T', '4');
+static const uint FOURCC_DXT5 = MAKEFOURCC('D', 'X', 'T', '5');
+static const uint FOURCC_RXGB = MAKEFOURCC('R', 'X', 'G', 'B');
+static const uint FOURCC_ATI1 = MAKEFOURCC('A', 'T', 'I', '1');
+static const uint FOURCC_ATI2 = MAKEFOURCC('A', 'T', 'I', '2');
+
+static const uint FOURCC_A2XY = MAKEFOURCC('A', '2', 'X', 'Y');
+
+static const uint FOURCC_DX10 = MAKEFOURCC('D', 'X', '1', '0');
+
+// 32 bit RGB formats.
+static const uint D3DFMT_R8G8B8 = 20;
+static const uint D3DFMT_A8R8G8B8 = 21;
+static const uint D3DFMT_X8R8G8B8 = 22;
+static const uint D3DFMT_R5G6B5 = 23;
+static const uint D3DFMT_X1R5G5B5 = 24;
+static const uint D3DFMT_A1R5G5B5 = 25;
+static const uint D3DFMT_A4R4G4B4 = 26;
+static const uint D3DFMT_R3G3B2 = 27;
+static const uint D3DFMT_A8 = 28;
+static const uint D3DFMT_A8R3G3B2 = 29;
+static const uint D3DFMT_X4R4G4B4 = 30;
+static const uint D3DFMT_A2B10G10R10 = 31;
+static const uint D3DFMT_A8B8G8R8 = 32;
+static const uint D3DFMT_X8B8G8R8 = 33;
+static const uint D3DFMT_G16R16 = 34;
+static const uint D3DFMT_A2R10G10B10 = 35;
+
+static const uint D3DFMT_A16B16G16R16 = 36;
// Palette formats.
-static const unsigned int D3DFMT_A8P8 = 40;
-static const unsigned int D3DFMT_P8 = 41;
+static const uint D3DFMT_A8P8 = 40;
+static const uint D3DFMT_P8 = 41;
// Luminance formats.
-static const unsigned int D3DFMT_L8 = 50;
-static const unsigned int D3DFMT_A8L8 = 51;
-static const unsigned int D3DFMT_A4L4 = 52;
+static const uint D3DFMT_L8 = 50;
+static const uint D3DFMT_A8L8 = 51;
+static const uint D3DFMT_A4L4 = 52;
+static const uint D3DFMT_L16 = 81;
// Floating point formats
-static const unsigned int D3DFMT_R16F = 111;
-static const unsigned int D3DFMT_G16R16F = 112;
-static const unsigned int D3DFMT_A16B16G16R16F = 113;
-static const unsigned int D3DFMT_R32F = 114;
-static const unsigned int D3DFMT_G32R32F = 115;
-static const unsigned int D3DFMT_A32B32G32R32F = 116;
-
-static const unsigned int DDSD_CAPS = 0x00000001U;
-static const unsigned int DDSD_PIXELFORMAT = 0x00001000U;
-static const unsigned int DDSD_WIDTH = 0x00000004U;
-static const unsigned int DDSD_HEIGHT = 0x00000002U;
-static const unsigned int DDSD_PITCH = 0x00000008U;
-static const unsigned int DDSD_MIPMAPCOUNT = 0x00020000U;
-static const unsigned int DDSD_LINEARSIZE = 0x00080000U;
-static const unsigned int DDSD_DEPTH = 0x00800000U;
-
-static const unsigned int DDSCAPS_COMPLEX = 0x00000008U;
-static const unsigned int DDSCAPS_TEXTURE = 0x00001000U;
-static const unsigned int DDSCAPS_MIPMAP = 0x00400000U;
-static const unsigned int DDSCAPS2_VOLUME = 0x00200000U;
-static const unsigned int DDSCAPS2_CUBEMAP = 0x00000200U;
-
-static const unsigned int DDSCAPS2_CUBEMAP_POSITIVEX = 0x00000400U;
-static const unsigned int DDSCAPS2_CUBEMAP_NEGATIVEX = 0x00000800U;
-static const unsigned int DDSCAPS2_CUBEMAP_POSITIVEY = 0x00001000U;
-static const unsigned int DDSCAPS2_CUBEMAP_NEGATIVEY = 0x00002000U;
-static const unsigned int DDSCAPS2_CUBEMAP_POSITIVEZ = 0x00004000U;
-static const unsigned int DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x00008000U;
-static const unsigned int DDSCAPS2_CUBEMAP_ALL_FACES = 0x0000FC00U;
-
-static const unsigned int DDPF_ALPHAPIXELS = 0x00000001U;
-static const unsigned int DDPF_ALPHA = 0x00000002U;
-static const unsigned int DDPF_FOURCC = 0x00000004U;
-static const unsigned int DDPF_RGB = 0x00000040U;
-static const unsigned int DDPF_PALETTEINDEXED1 = 0x00000800U;
-static const unsigned int DDPF_PALETTEINDEXED2 = 0x00001000U;
-static const unsigned int DDPF_PALETTEINDEXED4 = 0x00000008U;
-static const unsigned int DDPF_PALETTEINDEXED8 = 0x00000020U;
-static const unsigned int DDPF_LUMINANCE = 0x00020000U;
-static const unsigned int DDPF_ALPHAPREMULT = 0x00008000U;
-static const unsigned int DDPF_NORMAL = 0x80000000U; // @@ Custom nv flag.
+static const uint D3DFMT_R16F = 111;
+static const uint D3DFMT_G16R16F = 112;
+static const uint D3DFMT_A16B16G16R16F = 113;
+static const uint D3DFMT_R32F = 114;
+static const uint D3DFMT_G32R32F = 115;
+static const uint D3DFMT_A32B32G32R32F = 116;
+
+static const uint DDSD_CAPS = 0x00000001U;
+static const uint DDSD_PIXELFORMAT = 0x00001000U;
+static const uint DDSD_WIDTH = 0x00000004U;
+static const uint DDSD_HEIGHT = 0x00000002U;
+static const uint DDSD_PITCH = 0x00000008U;
+static const uint DDSD_MIPMAPCOUNT = 0x00020000U;
+static const uint DDSD_LINEARSIZE = 0x00080000U;
+static const uint DDSD_DEPTH = 0x00800000U;
+
+static const uint DDSCAPS_COMPLEX = 0x00000008U;
+static const uint DDSCAPS_TEXTURE = 0x00001000U;
+static const uint DDSCAPS_MIPMAP = 0x00400000U;
+static const uint DDSCAPS2_VOLUME = 0x00200000U;
+static const uint DDSCAPS2_CUBEMAP = 0x00000200U;
+
+static const uint DDSCAPS2_CUBEMAP_POSITIVEX = 0x00000400U;
+static const uint DDSCAPS2_CUBEMAP_NEGATIVEX = 0x00000800U;
+static const uint DDSCAPS2_CUBEMAP_POSITIVEY = 0x00001000U;
+static const uint DDSCAPS2_CUBEMAP_NEGATIVEY = 0x00002000U;
+static const uint DDSCAPS2_CUBEMAP_POSITIVEZ = 0x00004000U;
+static const uint DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x00008000U;
+static const uint DDSCAPS2_CUBEMAP_ALL_FACES = 0x0000FC00U;
+
+static const uint DDPF_ALPHAPIXELS = 0x00000001U;
+static const uint DDPF_ALPHA = 0x00000002U;
+static const uint DDPF_FOURCC = 0x00000004U;
+static const uint DDPF_RGB = 0x00000040U;
+static const uint DDPF_PALETTEINDEXED1 = 0x00000800U;
+static const uint DDPF_PALETTEINDEXED2 = 0x00001000U;
+static const uint DDPF_PALETTEINDEXED4 = 0x00000008U;
+static const uint DDPF_PALETTEINDEXED8 = 0x00000020U;
+static const uint DDPF_LUMINANCE = 0x00020000U;
+static const uint DDPF_ALPHAPREMULT = 0x00008000U;
+static const uint DDPF_NORMAL = 0x80000000U; // @@ Custom nv flag.
+
+ // DX10 formats.
+ enum DXGI_FORMAT
+ {
+ DXGI_FORMAT_UNKNOWN = 0,
+
+ DXGI_FORMAT_R32G32B32A32_TYPELESS = 1,
+ DXGI_FORMAT_R32G32B32A32_FLOAT = 2,
+ DXGI_FORMAT_R32G32B32A32_UINT = 3,
+ DXGI_FORMAT_R32G32B32A32_SINT = 4,
+
+ DXGI_FORMAT_R32G32B32_TYPELESS = 5,
+ DXGI_FORMAT_R32G32B32_FLOAT = 6,
+ DXGI_FORMAT_R32G32B32_UINT = 7,
+ DXGI_FORMAT_R32G32B32_SINT = 8,
+
+ DXGI_FORMAT_R16G16B16A16_TYPELESS = 9,
+ DXGI_FORMAT_R16G16B16A16_FLOAT = 10,
+ DXGI_FORMAT_R16G16B16A16_UNORM = 11,
+ DXGI_FORMAT_R16G16B16A16_UINT = 12,
+ DXGI_FORMAT_R16G16B16A16_SNORM = 13,
+ DXGI_FORMAT_R16G16B16A16_SINT = 14,
+
+ DXGI_FORMAT_R32G32_TYPELESS = 15,
+ DXGI_FORMAT_R32G32_FLOAT = 16,
+ DXGI_FORMAT_R32G32_UINT = 17,
+ DXGI_FORMAT_R32G32_SINT = 18,
+
+ DXGI_FORMAT_R32G8X24_TYPELESS = 19,
+ DXGI_FORMAT_D32_FLOAT_S8X24_UINT = 20,
+ DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS = 21,
+ DXGI_FORMAT_X32_TYPELESS_G8X24_UINT = 22,
+
+ DXGI_FORMAT_R10G10B10A2_TYPELESS = 23,
+ DXGI_FORMAT_R10G10B10A2_UNORM = 24,
+ DXGI_FORMAT_R10G10B10A2_UINT = 25,
+
+ DXGI_FORMAT_R11G11B10_FLOAT = 26,
+
+ DXGI_FORMAT_R8G8B8A8_TYPELESS = 27,
+ DXGI_FORMAT_R8G8B8A8_UNORM = 28,
+ DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 29,
+ DXGI_FORMAT_R8G8B8A8_UINT = 30,
+ DXGI_FORMAT_R8G8B8A8_SNORM = 31,
+ DXGI_FORMAT_R8G8B8A8_SINT = 32,
+
+ DXGI_FORMAT_R16G16_TYPELESS = 33,
+ DXGI_FORMAT_R16G16_FLOAT = 34,
+ DXGI_FORMAT_R16G16_UNORM = 35,
+ DXGI_FORMAT_R16G16_UINT = 36,
+ DXGI_FORMAT_R16G16_SNORM = 37,
+ DXGI_FORMAT_R16G16_SINT = 38,
+
+ DXGI_FORMAT_R32_TYPELESS = 39,
+ DXGI_FORMAT_D32_FLOAT = 40,
+ DXGI_FORMAT_R32_FLOAT = 41,
+ DXGI_FORMAT_R32_UINT = 42,
+ DXGI_FORMAT_R32_SINT = 43,
+
+ DXGI_FORMAT_R24G8_TYPELESS = 44,
+ DXGI_FORMAT_D24_UNORM_S8_UINT = 45,
+ DXGI_FORMAT_R24_UNORM_X8_TYPELESS = 46,
+ DXGI_FORMAT_X24_TYPELESS_G8_UINT = 47,
+
+ DXGI_FORMAT_R8G8_TYPELESS = 48,
+ DXGI_FORMAT_R8G8_UNORM = 49,
+ DXGI_FORMAT_R8G8_UINT = 50,
+ DXGI_FORMAT_R8G8_SNORM = 51,
+ DXGI_FORMAT_R8G8_SINT = 52,
+
+ DXGI_FORMAT_R16_TYPELESS = 53,
+ DXGI_FORMAT_R16_FLOAT = 54,
+ DXGI_FORMAT_D16_UNORM = 55,
+ DXGI_FORMAT_R16_UNORM = 56,
+ DXGI_FORMAT_R16_UINT = 57,
+ DXGI_FORMAT_R16_SNORM = 58,
+ DXGI_FORMAT_R16_SINT = 59,
+
+ DXGI_FORMAT_R8_TYPELESS = 60,
+ DXGI_FORMAT_R8_UNORM = 61,
+ DXGI_FORMAT_R8_UINT = 62,
+ DXGI_FORMAT_R8_SNORM = 63,
+ DXGI_FORMAT_R8_SINT = 64,
+ DXGI_FORMAT_A8_UNORM = 65,
+
+ DXGI_FORMAT_R1_UNORM = 66,
+
+ DXGI_FORMAT_R9G9B9E5_SHAREDEXP = 67,
+
+ DXGI_FORMAT_R8G8_B8G8_UNORM = 68,
+ DXGI_FORMAT_G8R8_G8B8_UNORM = 69,
+
+ DXGI_FORMAT_BC1_TYPELESS = 70,
+ DXGI_FORMAT_BC1_UNORM = 71,
+ DXGI_FORMAT_BC1_UNORM_SRGB = 72,
+
+ DXGI_FORMAT_BC2_TYPELESS = 73,
+ DXGI_FORMAT_BC2_UNORM = 74,
+ DXGI_FORMAT_BC2_UNORM_SRGB = 75,
+
+ DXGI_FORMAT_BC3_TYPELESS = 76,
+ DXGI_FORMAT_BC3_UNORM = 77,
+ DXGI_FORMAT_BC3_UNORM_SRGB = 78,
+
+ DXGI_FORMAT_BC4_TYPELESS = 79,
+ DXGI_FORMAT_BC4_UNORM = 80,
+ DXGI_FORMAT_BC4_SNORM = 81,
+
+ DXGI_FORMAT_BC5_TYPELESS = 82,
+ DXGI_FORMAT_BC5_UNORM = 83,
+ DXGI_FORMAT_BC5_SNORM = 84,
+
+ DXGI_FORMAT_B5G6R5_UNORM = 85,
+ DXGI_FORMAT_B5G5R5A1_UNORM = 86,
+ DXGI_FORMAT_B8G8R8A8_UNORM = 87,
+ DXGI_FORMAT_B8G8R8X8_UNORM = 88,
+ };
+
+ enum D3D10_RESOURCE_DIMENSION
+ {
+ D3D10_RESOURCE_DIMENSION_UNKNOWN = 0,
+ D3D10_RESOURCE_DIMENSION_BUFFER = 1,
+ D3D10_RESOURCE_DIMENSION_TEXTURE1D = 2,
+ D3D10_RESOURCE_DIMENSION_TEXTURE2D = 3,
+ D3D10_RESOURCE_DIMENSION_TEXTURE3D = 4,
+ };
+
+
+ const char * getDxgiFormatString(DXGI_FORMAT dxgiFormat)
+ {
+#define CASE(format) case DXGI_FORMAT_##format: return #format
+ switch(dxgiFormat)
+ {
+ CASE(UNKNOWN);
+
+ CASE(R32G32B32A32_TYPELESS);
+ CASE(R32G32B32A32_FLOAT);
+ CASE(R32G32B32A32_UINT);
+ CASE(R32G32B32A32_SINT);
+
+ CASE(R32G32B32_TYPELESS);
+ CASE(R32G32B32_FLOAT);
+ CASE(R32G32B32_UINT);
+ CASE(R32G32B32_SINT);
+
+ CASE(R16G16B16A16_TYPELESS);
+ CASE(R16G16B16A16_FLOAT);
+ CASE(R16G16B16A16_UNORM);
+ CASE(R16G16B16A16_UINT);
+ CASE(R16G16B16A16_SNORM);
+ CASE(R16G16B16A16_SINT);
+
+ CASE(R32G32_TYPELESS);
+ CASE(R32G32_FLOAT);
+ CASE(R32G32_UINT);
+ CASE(R32G32_SINT);
+
+ CASE(R32G8X24_TYPELESS);
+ CASE(D32_FLOAT_S8X24_UINT);
+ CASE(R32_FLOAT_X8X24_TYPELESS);
+ CASE(X32_TYPELESS_G8X24_UINT);
+
+ CASE(R10G10B10A2_TYPELESS);
+ CASE(R10G10B10A2_UNORM);
+ CASE(R10G10B10A2_UINT);
+
+ CASE(R11G11B10_FLOAT);
+
+ CASE(R8G8B8A8_TYPELESS);
+ CASE(R8G8B8A8_UNORM);
+ CASE(R8G8B8A8_UNORM_SRGB);
+ CASE(R8G8B8A8_UINT);
+ CASE(R8G8B8A8_SNORM);
+ CASE(R8G8B8A8_SINT);
+
+ CASE(R16G16_TYPELESS);
+ CASE(R16G16_FLOAT);
+ CASE(R16G16_UNORM);
+ CASE(R16G16_UINT);
+ CASE(R16G16_SNORM);
+ CASE(R16G16_SINT);
+
+ CASE(R32_TYPELESS);
+ CASE(D32_FLOAT);
+ CASE(R32_FLOAT);
+ CASE(R32_UINT);
+ CASE(R32_SINT);
+
+ CASE(R24G8_TYPELESS);
+ CASE(D24_UNORM_S8_UINT);
+ CASE(R24_UNORM_X8_TYPELESS);
+ CASE(X24_TYPELESS_G8_UINT);
+
+ CASE(R8G8_TYPELESS);
+ CASE(R8G8_UNORM);
+ CASE(R8G8_UINT);
+ CASE(R8G8_SNORM);
+ CASE(R8G8_SINT);
+
+ CASE(R16_TYPELESS);
+ CASE(R16_FLOAT);
+ CASE(D16_UNORM);
+ CASE(R16_UNORM);
+ CASE(R16_UINT);
+ CASE(R16_SNORM);
+ CASE(R16_SINT);
+
+ CASE(R8_TYPELESS);
+ CASE(R8_UNORM);
+ CASE(R8_UINT);
+ CASE(R8_SNORM);
+ CASE(R8_SINT);
+ CASE(A8_UNORM);
+
+ CASE(R1_UNORM);
+
+ CASE(R9G9B9E5_SHAREDEXP);
+
+ CASE(R8G8_B8G8_UNORM);
+ CASE(G8R8_G8B8_UNORM);
+
+ CASE(BC1_TYPELESS);
+ CASE(BC1_UNORM);
+ CASE(BC1_UNORM_SRGB);
+
+ CASE(BC2_TYPELESS);
+ CASE(BC2_UNORM);
+ CASE(BC2_UNORM_SRGB);
+
+ CASE(BC3_TYPELESS);
+ CASE(BC3_UNORM);
+ CASE(BC3_UNORM_SRGB);
+
+ CASE(BC4_TYPELESS);
+ CASE(BC4_UNORM);
+ CASE(BC4_SNORM);
+
+ CASE(BC5_TYPELESS);
+ CASE(BC5_UNORM);
+ CASE(BC5_SNORM);
+
+ CASE(B5G6R5_UNORM);
+ CASE(B5G5R5A1_UNORM);
+ CASE(B8G8R8A8_UNORM);
+ CASE(B8G8R8X8_UNORM);
+
+ default:
+ return "UNKNOWN";
+ }
+#undef CASE
+ }
+
+ const char * getD3d10ResourceDimensionString(D3D10_RESOURCE_DIMENSION resourceDimension)
+ {
+ switch(resourceDimension)
+ {
+ default:
+ case D3D10_RESOURCE_DIMENSION_UNKNOWN: return "UNKNOWN";
+ case D3D10_RESOURCE_DIMENSION_BUFFER: return "BUFFER";
+ case D3D10_RESOURCE_DIMENSION_TEXTURE1D: return "TEXTURE1D";
+ case D3D10_RESOURCE_DIMENSION_TEXTURE2D: return "TEXTURE2D";
+ case D3D10_RESOURCE_DIMENSION_TEXTURE3D: return "TEXTURE3D";
+ }
+ }
/*** implementation ***/
@@ -172,6 +443,15 @@ void mem_read(Stream & mem, DDSCaps & caps)
mem_read(mem, caps.caps4);
}
+void mem_read(Stream & mem, DDSHeader10 & header)
+{
+ mem_read(mem, header.dxgiFormat);
+ mem_read(mem, header.resourceDimension);
+ mem_read(mem, header.miscFlag);
+ mem_read(mem, header.arraySize);
+ mem_read(mem, header.reserved);
+}
+
void mem_read(Stream & mem, DDSHeader & header)
{
mem_read(mem, header.fourcc);
@@ -182,12 +462,19 @@ void mem_read(Stream & mem, DDSHeader & header)
mem_read(mem, header.pitch);
mem_read(mem, header.depth);
mem_read(mem, header.mipmapcount);
- for (unsigned int i = 0; i < 11; i++) mem_read(mem, header.reserved[i]);
+ for (uint i = 0; i < 11; i++) mem_read(mem, header.reserved[i]);
mem_read(mem, header.pf);
mem_read(mem, header.caps);
mem_read(mem, header.notused);
+
+ if (header.hasDX10Header())
+ {
+ mem_read(mem, header.header10);
+ }
}
+
+
DDSHeader::DDSHeader()
{
this->fourcc = FOURCC_DDS;
@@ -198,11 +485,11 @@ DDSHeader::DDSHeader()
this->pitch = 0;
this->depth = 0;
this->mipmapcount = 0;
- for (unsigned int i = 0; i < 11; i++) this->reserved[i] = 0;
+ for (uint i = 0; i < 11; i++) this->reserved[i] = 0;
// Store version information on the reserved header attributes.
this->reserved[9] = MAKEFOURCC('N', 'V', 'T', 'T');
- this->reserved[10] = (0 << 16) | (9 << 8) | (3); // major.minor.revision
+ this->reserved[10] = (0 << 16) | (9 << 8) | (5); // major.minor.revision
this->pf.size = 32;
this->pf.flags = 0;
@@ -217,29 +504,35 @@ DDSHeader::DDSHeader()
this->caps.caps3 = 0;
this->caps.caps4 = 0;
this->notused = 0;
+
+ this->header10.dxgiFormat = DXGI_FORMAT_UNKNOWN;
+ this->header10.resourceDimension = D3D10_RESOURCE_DIMENSION_UNKNOWN;
+ this->header10.miscFlag = 0;
+ this->header10.arraySize = 0;
+ this->header10.reserved = 0;
}
-void DDSHeader::setWidth(unsigned int w)
+void DDSHeader::setWidth(uint w)
{
this->flags |= DDSD_WIDTH;
this->width = w;
}
-void DDSHeader::setHeight(unsigned int h)
+void DDSHeader::setHeight(uint h)
{
this->flags |= DDSD_HEIGHT;
this->height = h;
}
-void DDSHeader::setDepth(unsigned int d)
+void DDSHeader::setDepth(uint d)
{
this->flags |= DDSD_DEPTH;
this->height = d;
}
-void DDSHeader::setMipmapCount(unsigned int count)
+void DDSHeader::setMipmapCount(uint count)
{
- if (count == 0)
+ if (count == 0 || count == 1)
{
this->flags &= ~DDSD_MIPMAPCOUNT;
this->mipmapcount = 0;
@@ -262,47 +555,61 @@ void DDSHeader::setMipmapCount(unsigned int count)
void DDSHeader::setTexture2D()
{
- // nothing to do here.
+ this->header10.resourceDimension = D3D10_RESOURCE_DIMENSION_TEXTURE2D;
}
void DDSHeader::setTexture3D()
{
this->caps.caps2 = DDSCAPS2_VOLUME;
+
+ this->header10.resourceDimension = D3D10_RESOURCE_DIMENSION_TEXTURE3D;
}
void DDSHeader::setTextureCube()
{
this->caps.caps1 |= DDSCAPS_COMPLEX;
this->caps.caps2 = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_ALL_FACES;
+
+ this->header10.resourceDimension = D3D10_RESOURCE_DIMENSION_TEXTURE2D;
+ this->header10.arraySize = 6;
}
-void DDSHeader::setLinearSize(unsigned int size)
+void DDSHeader::setLinearSize(uint size)
{
this->flags &= ~DDSD_PITCH;
this->flags |= DDSD_LINEARSIZE;
this->pitch = size;
}
-void DDSHeader::setPitch(unsigned int pitch)
+void DDSHeader::setPitch(uint pitch)
{
this->flags &= ~DDSD_LINEARSIZE;
this->flags |= DDSD_PITCH;
this->pitch = pitch;
}
-void DDSHeader::setFourCC(unsigned char c0, unsigned char c1, unsigned char c2, unsigned char c3)
+void DDSHeader::setFourCC(uint8 c0, uint8 c1, uint8 c2, uint8 c3)
{
// set fourcc pixel format.
this->pf.flags = DDPF_FOURCC;
this->pf.fourcc = MAKEFOURCC(c0, c1, c2, c3);
- this->pf.bitcount = 0;
+
+ if (this->pf.fourcc == FOURCC_ATI2)
+ {
+ this->pf.bitcount = FOURCC_A2XY;
+ }
+ else
+ {
+ this->pf.bitcount = 0;
+ }
+
this->pf.rmask = 0;
this->pf.gmask = 0;
this->pf.bmask = 0;
this->pf.amask = 0;
}
-void DDSHeader::setPixelFormat(unsigned int bitcount, unsigned int rmask, unsigned int gmask, unsigned int bmask, unsigned int amask)
+void DDSHeader::setPixelFormat(uint bitcount, uint rmask, uint gmask, uint bmask, uint amask)
{
// Make sure the masks are correct.
if ((rmask & gmask) || \
@@ -324,15 +631,25 @@ void DDSHeader::setPixelFormat(unsigned int bitcount, unsigned int rmask, unsign
if (bitcount == 0)
{
// Compute bit count from the masks.
- unsigned int total = rmask | gmask | bmask | amask;
+ uint total = rmask | gmask | bmask | amask;
while(total != 0) {
bitcount++;
total >>= 1;
}
- // @@ Align to 8?
}
- this->pf.fourcc = 0;
+ if (!(bitcount > 0 && bitcount <= 32)) {
+ printf("DDS: bad bit count, pixel format not set\n");
+ return;
+ }
+
+ // Align to 8.
+ if (bitcount <= 8) bitcount = 8;
+ else if (bitcount <= 16) bitcount = 16;
+ else if (bitcount <= 24) bitcount = 24;
+ else bitcount = 32;
+
+ this->pf.fourcc = 0; //findD3D9Format(bitcount, rmask, gmask, bmask, amask);
this->pf.bitcount = bitcount;
this->pf.rmask = rmask;
this->pf.gmask = gmask;
@@ -340,48 +657,33 @@ void DDSHeader::setPixelFormat(unsigned int bitcount, unsigned int rmask, unsign
this->pf.amask = amask;
}
+void DDSHeader::setDX10Format(uint format)
+{
+ //this->pf.flags = 0;
+ this->pf.fourcc = FOURCC_DX10;
+ this->header10.dxgiFormat = format;
+}
+
void DDSHeader::setNormalFlag(bool b)
{
if (b) this->pf.flags |= DDPF_NORMAL;
else this->pf.flags &= ~DDPF_NORMAL;
}
-/*
-void DDSHeader::swapBytes()
+bool DDSHeader::hasDX10Header() const
{
- this->fourcc = POSH_LittleU32(this->fourcc);
- this->size = POSH_LittleU32(this->size);
- this->flags = POSH_LittleU32(this->flags);
- this->height = POSH_LittleU32(this->height);
- this->width = POSH_LittleU32(this->width);
- this->pitch = POSH_LittleU32(this->pitch);
- this->depth = POSH_LittleU32(this->depth);
- this->mipmapcount = POSH_LittleU32(this->mipmapcount);
-
- for(int i = 0; i < 11; i++) {
- this->reserved[i] = POSH_LittleU32(this->reserved[i]);
- }
-
- this->pf.size = POSH_LittleU32(this->pf.size);
- this->pf.flags = POSH_LittleU32(this->pf.flags);
- this->pf.fourcc = POSH_LittleU32(this->pf.fourcc);
- this->pf.bitcount = POSH_LittleU32(this->pf.bitcount);
- this->pf.rmask = POSH_LittleU32(this->pf.rmask);
- this->pf.gmask = POSH_LittleU32(this->pf.gmask);
- this->pf.bmask = POSH_LittleU32(this->pf.bmask);
- this->pf.amask = POSH_LittleU32(this->pf.amask);
- this->caps.caps1 = POSH_LittleU32(this->caps.caps1);
- this->caps.caps2 = POSH_LittleU32(this->caps.caps2);
- this->caps.caps3 = POSH_LittleU32(this->caps.caps3);
- this->caps.caps4 = POSH_LittleU32(this->caps.caps4);
- this->notused = POSH_LittleU32(this->notused);
+ return this->pf.fourcc == FOURCC_DX10; // @@ This is according to AMD
+ //return this->pf.flags == 0; // @@ This is according to MS
}
-*/
-
-DirectDrawSurface::DirectDrawSurface(unsigned char *mem, unsigned int size) : stream(mem, size), header()
+DirectDrawSurface::DirectDrawSurface(unsigned char *mem, uint size) : stream(mem, size), header()
{
mem_read(stream, header);
+
+ // some ATI2 compressed normal maps do not have their
+ // normal flag set, so force it here (the original nvtt don't do
+ // this, but the decompressor has a -forcenormal flag)
+ if (header.pf.fourcc == FOURCC_ATI2) header.setNormalFlag(true);
}
DirectDrawSurface::~DirectDrawSurface()
@@ -395,7 +697,7 @@ bool DirectDrawSurface::isValid() const
return false;
}
- const unsigned int required = (DDSD_WIDTH|DDSD_HEIGHT|DDSD_CAPS|DDSD_PIXELFORMAT);
+ const uint required = (DDSD_WIDTH|DDSD_HEIGHT/*|DDSD_CAPS|DDSD_PIXELFORMAT*/);
if( (header.flags & required) != required ) {
return false;
}
@@ -416,78 +718,72 @@ bool DirectDrawSurface::isValid() const
bool DirectDrawSurface::isSupported() const
{
- if (header.pf.flags & DDPF_FOURCC)
+ if (header.hasDX10Header())
{
- if (header.pf.fourcc != FOURCC_DXT1 &&
- header.pf.fourcc != FOURCC_DXT2 &&
- header.pf.fourcc != FOURCC_DXT3 &&
- header.pf.fourcc != FOURCC_DXT4 &&
- header.pf.fourcc != FOURCC_DXT5 &&
- header.pf.fourcc != FOURCC_RXGB &&
- header.pf.fourcc != FOURCC_ATI1 &&
- header.pf.fourcc != FOURCC_ATI2)
- {
- // Unknown fourcc code.
- return false;
- }
}
- else if (header.pf.flags & DDPF_RGB)
+ else
{
- if (header.pf.bitcount == 24)
+ if (header.pf.flags & DDPF_FOURCC)
{
- return true;
+ if (header.pf.fourcc != FOURCC_DXT1 &&
+ header.pf.fourcc != FOURCC_DXT2 &&
+ header.pf.fourcc != FOURCC_DXT3 &&
+ header.pf.fourcc != FOURCC_DXT4 &&
+ header.pf.fourcc != FOURCC_DXT5 &&
+ header.pf.fourcc != FOURCC_RXGB &&
+ header.pf.fourcc != FOURCC_ATI1 &&
+ header.pf.fourcc != FOURCC_ATI2)
+ {
+ // Unknown fourcc code.
+ return false;
+ }
}
- else if (header.pf.bitcount == 32)
+ else if (header.pf.flags & DDPF_RGB)
{
- return true;
+ // All RGB formats are supported now.
}
else
{
- // Unsupported pixel format.
return false;
}
- }
- else
- {
- return false;
- }
-
- if (isTextureCube() && (header.caps.caps2 & DDSCAPS2_CUBEMAP_ALL_FACES) != DDSCAPS2_CUBEMAP_ALL_FACES)
- {
- // Cubemaps must contain all faces.
- return false;
- }
+
+ if (isTextureCube() && (header.caps.caps2 & DDSCAPS2_CUBEMAP_ALL_FACES) != DDSCAPS2_CUBEMAP_ALL_FACES)
+ {
+ // Cubemaps must contain all faces.
+ return false;
+ }
- if (isTexture3D())
- {
- // @@ 3D textures not supported yet.
- return false;
+ if (isTexture3D())
+ {
+ // @@ 3D textures not supported yet.
+ return false;
+ }
}
return true;
}
-unsigned int DirectDrawSurface::mipmapCount() const
+uint DirectDrawSurface::mipmapCount() const
{
if (header.flags & DDSD_MIPMAPCOUNT) return header.mipmapcount;
- else return 0;
+ else return 1;
}
-unsigned int DirectDrawSurface::width() const
+uint DirectDrawSurface::width() const
{
if (header.flags & DDSD_WIDTH) return header.width;
else return 1;
}
-unsigned int DirectDrawSurface::height() const
+uint DirectDrawSurface::height() const
{
if (header.flags & DDSD_HEIGHT) return header.height;
else return 1;
}
-unsigned int DirectDrawSurface::depth() const
+uint DirectDrawSurface::depth() const
{
if (header.flags & DDSD_DEPTH) return header.depth;
else return 1;
@@ -509,14 +805,37 @@ bool DirectDrawSurface::hasAlpha() const
}
}
+bool DirectDrawSurface::isTexture1D() const
+{
+ if (header.hasDX10Header())
+ {
+ return header.header10.resourceDimension == D3D10_RESOURCE_DIMENSION_TEXTURE1D;
+ }
+ return false;
+}
+
bool DirectDrawSurface::isTexture2D() const
{
- return !isTexture3D() && !isTextureCube();
+ if (header.hasDX10Header())
+ {
+ return header.header10.resourceDimension == D3D10_RESOURCE_DIMENSION_TEXTURE2D;
+ }
+ else
+ {
+ return !isTexture3D() && !isTextureCube();
+ }
}
bool DirectDrawSurface::isTexture3D() const
{
+ if (header.hasDX10Header())
+ {
+ return header.header10.resourceDimension == D3D10_RESOURCE_DIMENSION_TEXTURE3D;
+ }
+ else
+ {
return (header.caps.caps2 & DDSCAPS2_VOLUME) != 0;
+ }
}
bool DirectDrawSurface::isTextureCube() const
@@ -524,18 +843,23 @@ bool DirectDrawSurface::isTextureCube() const
return (header.caps.caps2 & DDSCAPS2_CUBEMAP) != 0;
}
-void DirectDrawSurface::mipmap(Image * img, unsigned int face, unsigned int mipmap)
+void DirectDrawSurface::setNormalFlag(bool b)
+{
+ header.setNormalFlag(b);
+}
+
+void DirectDrawSurface::mipmap(Image * img, uint face, uint mipmap)
{
stream.seek(offset(face, mipmap));
- unsigned int w = width();
- unsigned int h = height();
+ uint w = width();
+ uint h = height();
// Compute width and height.
- for (unsigned int m = 0; m < mipmap; m++)
+ for (uint m = 0; m < mipmap; m++)
{
- w = max(w/2, 1U);
- h = max(h/2, 1U);
+ w = max(1U, w / 2);
+ h = max(1U, h / 2);
}
img->allocate(w, h);
@@ -550,94 +874,57 @@ void DirectDrawSurface::mipmap(Image * img, unsigned int face, unsigned int mipm
}
}
-/* helper function for readLinearImage */
-void maskShiftAndSize(unsigned int mask, unsigned int * shift, unsigned int * size)
-{
- if (!mask)
- {
- *shift = 0;
- *size = 0;
- return;
- }
-
- *shift = 0;
- while((mask & 1) == 0) {
- ++(*shift);
- mask >>= 1;
- }
-
- *size = 0;
- while((mask & 1) == 1) {
- ++(*size);
- mask >>= 1;
- }
-}
-
-/* helper function for readLinearImage */
-unsigned int convert(unsigned int c, unsigned int inbits, unsigned int outbits)
-{
- if (inbits == 0) {
- return 0;
- }
- else if (inbits == outbits)
- {
- return c;
- }
- else if (inbits > outbits)
- {
- // truncate
- return c >> (inbits - outbits);
- }
- else
- {
- // bitexpand
- return (c << (outbits - inbits)) | convert(c, inbits, outbits - inbits);
- }
-}
-
void DirectDrawSurface::readLinearImage(Image * img)
{
- const unsigned int w = img->width();
- const unsigned int h = img->height();
-
- unsigned int rshift, rsize;
- maskShiftAndSize(header.pf.rmask, &rshift, &rsize);
- unsigned int gshift, gsize;
- maskShiftAndSize(header.pf.gmask, &gshift, &gsize);
+ const uint w = img->width();
+ const uint h = img->height();
+
+ uint rshift, rsize;
+ PixelFormat::maskShiftAndSize(header.pf.rmask, &rshift, &rsize);
- unsigned int bshift, bsize;
- maskShiftAndSize(header.pf.bmask, &bshift, &bsize);
+ uint gshift, gsize;
+ PixelFormat::maskShiftAndSize(header.pf.gmask, &gshift, &gsize);
- unsigned int ashift, asize;
- maskShiftAndSize(header.pf.amask, &ashift, &asize);
+ uint bshift, bsize;
+ PixelFormat::maskShiftAndSize(header.pf.bmask, &bshift, &bsize);
+
+ uint ashift, asize;
+ PixelFormat::maskShiftAndSize(header.pf.amask, &ashift, &asize);
+
+ uint byteCount = (header.pf.bitcount + 7) / 8;
- unsigned int byteCount = (header.pf.bitcount + 7) / 8;
if (byteCount > 4)
{
/* just in case... we could have segfaults later on if byteCount > 4 */
- printf("DDS: bitcount too large (file corrupt?)");
+ printf("DDS: bitcount too large");
return;
}
- if (header.pf.amask != 0)
+ // set image format: RGB or ARGB
+ // alpha channel exists if and only if the alpha mask is non-zero
+ if (header.pf.amask == 0)
+ {
+ img->setFormat(Image::Format_RGB);
+ }
+ else
{
img->setFormat(Image::Format_ARGB);
}
// Read linear RGB images.
- for (unsigned int y = 0; y < h; y++)
+ for (uint y = 0; y < h; y++)
{
- for (unsigned int x = 0; x < w; x++)
+ for (uint x = 0; x < w; x++)
{
- unsigned int c = 0;
+ uint c = 0;
mem_read(stream, (unsigned char *)(&c), byteCount);
Color32 pixel(0, 0, 0, 0xFF);
- pixel.r = convert(c >> rshift, rsize, 8);
- pixel.g = convert(c >> gshift, gsize, 8);
- pixel.b = convert(c >> bshift, bsize, 8);
- pixel.a = convert(c >> ashift, asize, 8);
+ pixel.r = PixelFormat::convert(c >> rshift, rsize, 8);
+ pixel.g = PixelFormat::convert(c >> gshift, gsize, 8);
+ pixel.b = PixelFormat::convert(c >> bshift, bsize, 8);
+ pixel.a = PixelFormat::convert(c >> ashift, asize, 8);
img->pixel(x, y) = pixel;
}
@@ -646,15 +933,29 @@ void DirectDrawSurface::readLinearImage(Image * img)
void DirectDrawSurface::readBlockImage(Image * img)
{
- const unsigned int w = img->width();
- const unsigned int h = img->height();
+
+ // set image format: RGB or ARGB
+ if (header.pf.fourcc == FOURCC_RXGB ||
+ header.pf.fourcc == FOURCC_ATI1 ||
+ header.pf.fourcc == FOURCC_ATI2 ||
+ header.pf.flags & DDPF_NORMAL)
+ {
+ img->setFormat(Image::Format_RGB);
+ }
+ else
+ {
+ img->setFormat(Image::Format_ARGB);
+ }
+
+ const uint w = img->width();
+ const uint h = img->height();
- const unsigned int bw = (w + 3) / 4;
- const unsigned int bh = (h + 3) / 4;
+ const uint bw = (w + 3) / 4;
+ const uint bh = (h + 3) / 4;
- for (unsigned int by = 0; by < bh; by++)
+ for (uint by = 0; by < bh; by++)
{
- for (unsigned int bx = 0; bx < bw; bx++)
+ for (uint bx = 0; bx < bw; bx++)
{
ColorBlock block;
@@ -662,9 +963,9 @@ void DirectDrawSurface::readBlockImage(Image * img)
readBlock(&block);
// Write color block.
- for (unsigned int y = 0; y < min(4U, h-4*by); y++)
+ for (uint y = 0; y < min(4U, h-4*by); y++)
{
- for (unsigned int x = 0; x < min(4U, w-4*bx); x++)
+ for (uint x = 0; x < min(4U, w-4*bx); x++)
{
img->pixel(4*bx+x, 4*by+y) = block.color(x, y);
}
@@ -673,12 +974,13 @@ void DirectDrawSurface::readBlockImage(Image * img)
}
}
-static Color32 buildNormal(unsigned char x, unsigned char y)
+static Color32 buildNormal(uint8 x, uint8 y)
{
- float nx = 2 * (x / 255) - 1;
- float ny = 2 * (x / 255) - 1;
- float nz = sqrt(1 - nx*nx - ny*ny);
- unsigned char z = clamp(int(255 * (nz + 1) / 2), 0, 255);
+ float nx = 2 * (x / 255.0f) - 1;
+ float ny = 2 * (y / 255.0f) - 1;
+ float nz = 0.0f;
+ if (1 - nx*nx - ny*ny > 0) nz = sqrt(1 - nx*nx - ny*ny);
+ uint8 z = clamp(int(255.0f * (nz + 1) / 2.0f), 0, 255);
return Color32(x, y, z);
}
@@ -713,7 +1015,7 @@ void DirectDrawSurface::readBlock(ColorBlock * rgba)
for (int i = 0; i < 16; i++)
{
Color32 & c = rgba->color(i);
- unsigned int tmp = c.r;
+ uint tmp = c.r;
c.r = c.a;
c.a = tmp;
}
@@ -748,14 +1050,14 @@ void DirectDrawSurface::readBlock(ColorBlock * rgba)
for (int i = 0; i < 16; i++)
{
Color32 & c = rgba->color(i);
- c = buildNormal(c.g, c.a);
+ c = buildNormal(c.a, c.g);
}
}
}
}
-unsigned int DirectDrawSurface::blockSize() const
+uint DirectDrawSurface::blockSize() const
{
switch(header.pf.fourcc)
{
@@ -775,13 +1077,13 @@ unsigned int DirectDrawSurface::blockSize() const
return 0;
}
-unsigned int DirectDrawSurface::mipmapSize(unsigned int mipmap) const
+uint DirectDrawSurface::mipmapSize(uint mipmap) const
{
- unsigned int w = width();
- unsigned int h = height();
- unsigned int d = depth();
+ uint w = width();
+ uint h = height();
+ uint d = depth();
- for (unsigned int m = 0; m < mipmap; m++)
+ for (uint m = 0; m < mipmap; m++)
{
w = max(1U, w / 2);
h = max(1U, h / 2);
@@ -798,10 +1100,10 @@ unsigned int DirectDrawSurface::mipmapSize(unsigned int mipmap) const
else if (header.pf.flags & DDPF_RGB)
{
// Align pixels to bytes.
- unsigned int byteCount = (header.pf.bitcount + 7) / 8;
+ uint byteCount = (header.pf.bitcount + 7) / 8;
// Align pitch to 4 bytes.
- unsigned int pitch = 4 * ((w * byteCount + 3) / 4);
+ uint pitch = 4 * ((w * byteCount + 3) / 4);
return pitch * h * d;
}
@@ -811,12 +1113,12 @@ unsigned int DirectDrawSurface::mipmapSize(unsigned int mipmap) const
};
}
-unsigned int DirectDrawSurface::faceSize() const
+uint DirectDrawSurface::faceSize() const
{
- const unsigned int count = mipmapCount();
- unsigned int size = 0;
+ const uint count = mipmapCount();
+ uint size = 0;
- for (unsigned int m = 0; m < count; m++)
+ for (uint m = 0; m < count; m++)
{
size += mipmapSize(m);
}
@@ -824,16 +1126,21 @@ unsigned int DirectDrawSurface::faceSize() const
return size;
}
-unsigned int DirectDrawSurface::offset(const unsigned int face, const unsigned int mipmap)
+uint DirectDrawSurface::offset(const uint face, const uint mipmap)
{
- unsigned int size = sizeof(DDSHeader);
+ uint size = 128; //sizeof(DDSHeader);
+ if (header.hasDX10Header())
+ {
+ size += 20; // sizeof(DDSHeader10);
+ }
+
if (face != 0)
{
size += face * faceSize();
}
- for (unsigned int m = 0; m < mipmap; m++)
+ for (uint m = 0; m < mipmap; m++)
{
size += mipmapSize(m);
}
@@ -876,8 +1183,23 @@ void DirectDrawSurface::printInfo() const
if (header.pf.flags & DDPF_ALPHAPREMULT) printf("\t\tDDPF_ALPHAPREMULT\n");
if (header.pf.flags & DDPF_NORMAL) printf("\t\tDDPF_NORMAL\n");
- printf("\tFourCC: '%c%c%c%c'\n", ((header.pf.fourcc >> 0) & 0xFF), ((header.pf.fourcc >> 8) & 0xFF), ((header.pf.fourcc >> 16) & 0xFF), ((header.pf.fourcc >> 24) & 0xFF));
- printf("\tBit count: %d\n", header.pf.bitcount);
+ printf("\tFourCC: '%c%c%c%c'\n",
+ ((header.pf.fourcc >> 0) & 0xFF),
+ ((header.pf.fourcc >> 8) & 0xFF),
+ ((header.pf.fourcc >> 16) & 0xFF),
+ ((header.pf.fourcc >> 24) & 0xFF));
+ if ((header.pf.fourcc & DDPF_FOURCC) && (header.pf.bitcount != 0))
+ {
+ printf("\tSwizzle: '%c%c%c%c'\n",
+ (header.pf.bitcount >> 0) & 0xFF,
+ (header.pf.bitcount >> 8) & 0xFF,
+ (header.pf.bitcount >> 16) & 0xFF,
+ (header.pf.bitcount >> 24) & 0xFF);
+ }
+ else
+ {
+ printf("\tBit count: %d\n", header.pf.bitcount);
+ }
printf("\tRed mask: 0x%.8X\n", header.pf.rmask);
printf("\tGreen mask: 0x%.8X\n", header.pf.gmask);
printf("\tBlue mask: 0x%.8X\n", header.pf.bmask);
@@ -908,6 +1230,15 @@ void DirectDrawSurface::printInfo() const
printf("\tCaps 3: 0x%.8X\n", header.caps.caps3);
printf("\tCaps 4: 0x%.8X\n", header.caps.caps4);
+ if (header.hasDX10Header())
+ {
+ printf("DX10 Header:\n");
+ printf("\tDXGI Format: %u (%s)\n", header.header10.dxgiFormat, getDxgiFormatString((DXGI_FORMAT)header.header10.dxgiFormat));
+ printf("\tResource dimension: %u (%s)\n", header.header10.resourceDimension, getD3d10ResourceDimensionString((D3D10_RESOURCE_DIMENSION)header.header10.resourceDimension));
+ printf("\tMisc flag: %u\n", header.header10.miscFlag);
+ printf("\tArray size: %u\n", header.header10.arraySize);
+ }
+
if (header.reserved[9] == MAKEFOURCC('N', 'V', 'T', 'T'))
{
int major = (header.reserved[10] >> 16) & 0xFF;
diff --git a/source/blender/imbuf/intern/dds/DirectDrawSurface.h b/source/blender/imbuf/intern/dds/DirectDrawSurface.h
index 76272717332..28fcc95fe83 100644
--- a/source/blender/imbuf/intern/dds/DirectDrawSurface.h
+++ b/source/blender/imbuf/intern/dds/DirectDrawSurface.h
@@ -55,92 +55,114 @@
#ifndef _DDS_DIRECTDRAWSURFACE_H
#define _DDS_DIRECTDRAWSURFACE_H
+#include <Common.h>
#include <Stream.h>
#include <ColorBlock.h>
#include <Image.h>
-struct DDSPixelFormat {
- unsigned int size;
- unsigned int flags;
- unsigned int fourcc;
- unsigned int bitcount;
- unsigned int rmask;
- unsigned int gmask;
- unsigned int bmask;
- unsigned int amask;
+struct DDSPixelFormat
+{
+ uint size;
+ uint flags;
+ uint fourcc;
+ uint bitcount;
+ uint rmask;
+ uint gmask;
+ uint bmask;
+ uint amask;
+};
+
+struct DDSCaps
+{
+ uint caps1;
+ uint caps2;
+ uint caps3;
+ uint caps4;
};
-struct DDSCaps {
- unsigned int caps1;
- unsigned int caps2;
- unsigned int caps3;
- unsigned int caps4;
+/// DDS file header for DX10.
+struct DDSHeader10
+{
+ uint dxgiFormat;
+ uint resourceDimension;
+ uint miscFlag;
+ uint arraySize;
+ uint reserved;
};
/// DDS file header.
-struct DDSHeader {
- unsigned int fourcc;
- unsigned int size;
- unsigned int flags;
- unsigned int height;
- unsigned int width;
- unsigned int pitch;
- unsigned int depth;
- unsigned int mipmapcount;
- unsigned int reserved[11];
+struct DDSHeader
+{
+ uint fourcc;
+ uint size;
+ uint flags;
+ uint height;
+ uint width;
+ uint pitch;
+ uint depth;
+ uint mipmapcount;
+ uint reserved[11];
DDSPixelFormat pf;
DDSCaps caps;
- unsigned int notused;
-
+ uint notused;
+ DDSHeader10 header10;
+
+
// Helper methods.
DDSHeader();
- void setWidth(unsigned int w);
- void setHeight(unsigned int h);
- void setDepth(unsigned int d);
- void setMipmapCount(unsigned int count);
+ void setWidth(uint w);
+ void setHeight(uint h);
+ void setDepth(uint d);
+ void setMipmapCount(uint count);
void setTexture2D();
void setTexture3D();
void setTextureCube();
- void setLinearSize(unsigned int size);
- void setPitch(unsigned int pitch);
- void setFourCC(unsigned char c0, unsigned char c1, unsigned char c2, unsigned char c3);
- void setPixelFormat(unsigned int bitcount, unsigned int rmask, unsigned int gmask, unsigned int bmask, unsigned int amask);
+ void setLinearSize(uint size);
+ void setPitch(uint pitch);
+ void setFourCC(uint8 c0, uint8 c1, uint8 c2, uint8 c3);
+ void setPixelFormat(uint bitcount, uint rmask, uint gmask, uint bmask, uint amask);
+ void setDX10Format(uint format);
void setNormalFlag(bool b);
- /* void swapBytes(); */
+ bool hasDX10Header() const;
};
/// DirectDraw Surface. (DDS)
class DirectDrawSurface
{
public:
- DirectDrawSurface(unsigned char *mem, unsigned int size);
+ DirectDrawSurface(unsigned char *mem, uint size);
~DirectDrawSurface();
bool isValid() const;
bool isSupported() const;
- unsigned int mipmapCount() const;
- unsigned int width() const;
- unsigned int height() const;
- unsigned int depth() const;
+ uint mipmapCount() const;
+ uint width() const;
+ uint height() const;
+ uint depth() const;
+ bool isTexture1D() const;
bool isTexture2D() const;
bool isTexture3D() const;
bool isTextureCube() const;
- bool hasAlpha() const; /* false for DXT1, true for all others */
+
+ void setNormalFlag(bool b);
+
+ bool hasAlpha() const; /* false for DXT1, true for all other DXTs */
- void mipmap(Image * img, unsigned int f, unsigned int m);
+ void mipmap(Image * img, uint f, uint m);
+ // void mipmap(FloatImage * img, uint f, uint m);
void printInfo() const;
private:
- unsigned int blockSize() const;
- unsigned int faceSize() const;
- unsigned int mipmapSize(unsigned int m) const;
+ uint blockSize() const;
+ uint faceSize() const;
+ uint mipmapSize(uint m) const;
- unsigned int offset(unsigned int f, unsigned int m);
+ uint offset(uint f, uint m);
void readLinearImage(Image * img);
void readBlockImage(Image * img);
@@ -155,5 +177,6 @@ private:
void mem_read(Stream & mem, DDSPixelFormat & pf);
void mem_read(Stream & mem, DDSCaps & caps);
void mem_read(Stream & mem, DDSHeader & header);
+void mem_read(Stream & mem, DDSHeader10 & header);
#endif // _DDS_DIRECTDRAWSURFACE_H
diff --git a/source/blender/imbuf/intern/dds/Image.cpp b/source/blender/imbuf/intern/dds/Image.cpp
index 6a751591f3e..8f6ac8658ba 100644
--- a/source/blender/imbuf/intern/dds/Image.cpp
+++ b/source/blender/imbuf/intern/dds/Image.cpp
@@ -45,7 +45,7 @@ Image::~Image()
free();
}
-void Image::allocate(unsigned int w, unsigned int h)
+void Image::allocate(uint w, uint h)
{
free();
m_width = w;
@@ -60,17 +60,17 @@ void Image::free()
}
-unsigned int Image::width() const
+uint Image::width() const
{
return m_width;
}
-unsigned int Image::height() const
+uint Image::height() const
{
return m_height;
}
-const Color32 * Image::scanline(unsigned int h) const
+const Color32 * Image::scanline(uint h) const
{
if (h >= m_height) {
printf("DDS: scanline beyond dimensions of image");
@@ -79,7 +79,7 @@ const Color32 * Image::scanline(unsigned int h) const
return m_data + h * m_width;
}
-Color32 * Image::scanline(unsigned int h)
+Color32 * Image::scanline(uint h)
{
if (h >= m_height) {
printf("DDS: scanline beyond dimensions of image");
@@ -98,7 +98,7 @@ Color32 * Image::pixels()
return m_data;
}
-const Color32 & Image::pixel(unsigned int idx) const
+const Color32 & Image::pixel(uint idx) const
{
if (idx >= m_width * m_height) {
printf("DDS: pixel beyond dimensions of image");
@@ -107,7 +107,7 @@ const Color32 & Image::pixel(unsigned int idx) const
return m_data[idx];
}
-Color32 & Image::pixel(unsigned int idx)
+Color32 & Image::pixel(uint idx)
{
if (idx >= m_width * m_height) {
printf("DDS: pixel beyond dimensions of image");
diff --git a/source/blender/imbuf/intern/dds/Image.h b/source/blender/imbuf/intern/dds/Image.h
index 3a656995857..f2ff9e4fbf3 100644
--- a/source/blender/imbuf/intern/dds/Image.h
+++ b/source/blender/imbuf/intern/dds/Image.h
@@ -34,6 +34,7 @@
#ifndef _DDS_IMAGE_H
#define _DDS_IMAGE_H
+#include <Common.h>
#include <Color.h>
/// 32 bit RGBA image.
@@ -50,28 +51,28 @@ public:
Image();
~Image();
- void allocate(unsigned int w, unsigned int h);
+ void allocate(uint w, uint h);
/*
bool load(const char * name);
- void wrap(void * data, unsigned int w, unsigned int h);
+ void wrap(void * data, uint w, uint h);
void unwrap();
*/
- unsigned int width() const;
- unsigned int height() const;
+ uint width() const;
+ uint height() const;
- const Color32 * scanline(unsigned int h) const;
- Color32 * scanline(unsigned int h);
+ const Color32 * scanline(uint h) const;
+ Color32 * scanline(uint h);
const Color32 * pixels() const;
Color32 * pixels();
- const Color32 & pixel(unsigned int idx) const;
- Color32 & pixel(unsigned int idx);
+ const Color32 & pixel(uint idx) const;
+ Color32 & pixel(uint idx);
- const Color32 & pixel(unsigned int x, unsigned int y) const;
- Color32 & pixel(unsigned int x, unsigned int y);
+ const Color32 & pixel(uint x, uint y) const;
+ Color32 & pixel(uint x, uint y);
Format format() const;
void setFormat(Format f);
@@ -80,19 +81,19 @@ private:
void free();
private:
- unsigned int m_width;
- unsigned int m_height;
+ uint m_width;
+ uint m_height;
Format m_format;
Color32 * m_data;
};
-inline const Color32 & Image::pixel(unsigned int x, unsigned int y) const
+inline const Color32 & Image::pixel(uint x, uint y) const
{
return pixel(y * width() + x);
}
-inline Color32 & Image::pixel(unsigned int x, unsigned int y)
+inline Color32 & Image::pixel(uint x, uint y)
{
return pixel(y * width() + x);
}
diff --git a/source/blender/imbuf/intern/dds/PixelFormat.h b/source/blender/imbuf/intern/dds/PixelFormat.h
new file mode 100644
index 00000000000..2004d689a3e
--- /dev/null
+++ b/source/blender/imbuf/intern/dds/PixelFormat.h
@@ -0,0 +1,107 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * Contributors: Amorilia (amorilia@gamebox.net)
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/*
+ * This file is based on a similar file from the NVIDIA texture tools
+ * (http://nvidia-texture-tools.googlecode.com/)
+ *
+ * Original license from NVIDIA follows.
+ */
+
+// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com>
+//
+// Permission is hereby granted, free of charge, to any person
+// obtaining a copy of this software and associated documentation
+// files (the "Software"), to deal in the Software without
+// restriction, including without limitation the rights to use,
+// copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the
+// Software is furnished to do so, subject to the following
+// conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+// OTHER DEALINGS IN THE SOFTWARE.
+
+#ifndef _DDS_PIXELFORMAT_H
+#define _DDS_PIXELFORMAT_H
+
+#include <Common.h>
+
+ namespace PixelFormat
+ {
+
+ // Convert component @a c having @a inbits to the returned value having @a outbits.
+ inline uint convert(uint c, uint inbits, uint outbits)
+ {
+ if (inbits == 0)
+ {
+ return 0;
+ }
+ else if (inbits >= outbits)
+ {
+ // truncate
+ return c >> (inbits - outbits);
+ }
+ else
+ {
+ // bitexpand
+ return (c << (outbits - inbits)) | convert(c, inbits, outbits - inbits);
+ }
+ }
+
+ // Get pixel component shift and size given its mask.
+ inline void maskShiftAndSize(uint mask, uint * shift, uint * size)
+ {
+ if (!mask)
+ {
+ *shift = 0;
+ *size = 0;
+ return;
+ }
+
+ *shift = 0;
+ while((mask & 1) == 0) {
+ ++(*shift);
+ mask >>= 1;
+ }
+
+ *size = 0;
+ while((mask & 1) == 1) {
+ ++(*size);
+ mask >>= 1;
+ }
+ }
+
+ } // PixelFormat namespace
+
+#endif // _DDS_IMAGE_PIXELFORMAT_H
diff --git a/source/blender/imbuf/intern/dds/dds_api.cpp b/source/blender/imbuf/intern/dds/dds_api.cpp
index b41b940dca7..cf2f6c16d08 100644
--- a/source/blender/imbuf/intern/dds/dds_api.cpp
+++ b/source/blender/imbuf/intern/dds/dds_api.cpp
@@ -94,6 +94,7 @@ struct ImBuf *imb_load_dds(unsigned char *mem, int size, int flags)
}
/* convert DDS into ImBuf */
+ // TODO use the image RGB or RGBA tag to determine the bits per pixel
if (dds.hasAlpha()) bits_per_pixel = 32;
else bits_per_pixel = 24;
ibuf = IMB_allocImBuf(dds.width(), dds.height(), bits_per_pixel, 0, 0);
diff --git a/source/blender/imbuf/intern/divers.c b/source/blender/imbuf/intern/divers.c
index 84588b52573..8043e594454 100644
--- a/source/blender/imbuf/intern/divers.c
+++ b/source/blender/imbuf/intern/divers.c
@@ -38,6 +38,7 @@
#include "IMB_imbuf.h"
#include "IMB_allocimbuf.h"
#include "IMB_divers.h"
+#include "BKE_utildefines.h"
void imb_checkncols(struct ImBuf *ibuf)
{
@@ -171,7 +172,6 @@ void IMB_gamwarp(struct ImBuf *ibuf, double gamma)
}
}
-#define FTOCHAR(val) val<=0.0f?0: (val>=1.0f?255: (char)(255.99f*val))
void IMB_rect_from_float(struct ImBuf *ibuf)
{
diff --git a/source/blender/imbuf/intern/dynlibtiff.c b/source/blender/imbuf/intern/dynlibtiff.c
index d2ca19e8282..b9186e482c5 100644
--- a/source/blender/imbuf/intern/dynlibtiff.c
+++ b/source/blender/imbuf/intern/dynlibtiff.c
@@ -80,13 +80,19 @@ void libtiff_loadlibtiff(void)
/* Try to find libtiff in a couple of standard places */
libtiff = PIL_dynlib_open("libtiff.so");
if (libtiff != NULL) return;
+ libtiff = PIL_dynlib_open("libtiff.so.3");
+ if (libtiff != NULL) return;
libtiff = PIL_dynlib_open("libtiff.dll");
if (libtiff != NULL) return;
libtiff = PIL_dynlib_open("/usr/lib/libtiff.so");
if (libtiff != NULL) return;
- /* OSX has version specific library */
libtiff = PIL_dynlib_open("/usr/lib/libtiff.so.3");
if (libtiff != NULL) return;
+ /* OSX has version specific library */
+#ifdef __x86_64__
+ libtiff = PIL_dynlib_open("/usr/lib64/libtiff.so.3");
+ if (libtiff != NULL) return;
+#endif
libtiff = PIL_dynlib_open("/usr/local/lib/libtiff.so");
if (libtiff != NULL) return;
/* For solaris */
@@ -100,8 +106,11 @@ void *libtiff_findsymbol(char *name)
assert(libtiff != NULL);
symbol = PIL_dynlib_find_symbol(libtiff, name);
if (symbol == NULL) {
- printf("libtiff_findsymbol: error %s\n",
- PIL_dynlib_get_error_as_string(libtiff));
+ char *err = PIL_dynlib_get_error_as_string(libtiff);
+
+ if (err) printf("libtiff_findsymbol: error %s\n",err);
+ else printf("libtiff_findsymbol: error Unknown.\n");
+
libtiff = NULL;
G.have_libtiff = (0);
return NULL;
diff --git a/source/blender/imbuf/intern/filter.c b/source/blender/imbuf/intern/filter.c
index fda79315268..9802405fd8d 100644
--- a/source/blender/imbuf/intern/filter.c
+++ b/source/blender/imbuf/intern/filter.c
@@ -203,29 +203,46 @@ void imb_filterx(struct ImBuf *ibuf)
void IMB_filterN(ImBuf *out, ImBuf *in)
{
register char *row1, *row2, *row3;
- register char *cp;
+ register char *cp, *r11, *r13, *r21, *r23, *r31, *r33;
int rowlen, x, y;
rowlen= in->x;
- for(y=2; y<in->y; y++) {
+ for(y=0; y<in->y; y++) {
/* setup rows */
- row1= (char *)(in->rect + (y-2)*rowlen);
- row2= row1 + 4*rowlen;
- row3= row2 + 4*rowlen;
+ row2= (char*)(in->rect + y*rowlen);
+ row1= (y == 0)? row2: row2 - 4*rowlen;
+ row3= (y == in->y-1)? row2: row2 + 4*rowlen;
- cp= (char *)(out->rect + (y-1)*rowlen);
- cp[0]= row2[0];
- cp[1]= row2[1];
- cp[2]= row2[2];
- cp[3]= row2[3];
- cp+= 4;
+ cp= (char *)(out->rect + y*rowlen);
- for(x=2; x<rowlen; x++) {
- cp[0]= (row1[0] + 2*row1[4] + row1[8] + 2*row2[0] + 4*row2[4] + 2*row2[8] + row3[0] + 2*row3[4] + row3[8])>>4;
- cp[1]= (row1[1] + 2*row1[5] + row1[9] + 2*row2[1] + 4*row2[5] + 2*row2[9] + row3[1] + 2*row3[5] + row3[9])>>4;
- cp[2]= (row1[2] + 2*row1[6] + row1[10] + 2*row2[2] + 4*row2[6] + 2*row2[10] + row3[2] + 2*row3[6] + row3[10])>>4;
- cp[3]= (row1[3] + 2*row1[7] + row1[11] + 2*row2[3] + 4*row2[7] + 2*row2[11] + row3[3] + 2*row3[7] + row3[11])>>4;
+ for(x=0; x<rowlen; x++) {
+ if(x == 0) {
+ r11 = row1;
+ r21 = row1;
+ r31 = row1;
+ }
+ else {
+ r11 = row1-4;
+ r21 = row1-4;
+ r31 = row1-4;
+ }
+
+ if(x == rowlen-1) {
+ r13 = row1;
+ r23 = row1;
+ r33 = row1;
+ }
+ else {
+ r13 = row1+4;
+ r23 = row1+4;
+ r33 = row1+4;
+ }
+
+ cp[0]= (r11[0] + 2*row1[0] + r13[0] + 2*r21[0] + 4*row2[0] + 2*r23[0] + r31[0] + 2*row3[0] + r33[0])>>4;
+ cp[1]= (r11[1] + 2*row1[1] + r13[1] + 2*r21[1] + 4*row2[1] + 2*r23[1] + r31[1] + 2*row3[1] + r33[1])>>4;
+ cp[2]= (r11[2] + 2*row1[2] + r13[2] + 2*r21[2] + 4*row2[2] + 2*r23[2] + r31[2] + 2*row3[2] + r33[2])>>4;
+ cp[3]= (r11[3] + 2*row1[3] + r13[3] + 2*r21[3] + 4*row2[3] + 2*r23[3] + r31[3] + 2*row3[3] + r33[3])>>4;
cp+=4; row1+=4; row2+=4; row3+=4;
}
}
@@ -237,18 +254,72 @@ void IMB_filter(struct ImBuf *ibuf)
imb_filterx(ibuf);
}
-#define EXTEND_PIXEL(a, w) if((a)[3]) {r+= w*(a)[0]; g+= w*(a)[1]; b+= w*(a)[2]; tot+=w;}
+#define EXTEND_PIXEL(color, w) if((color)[3]) {r+= w*(color)[0]; g+= w*(color)[1]; b+= w*(color)[2]; a+= w*(color)[3]; tot+=w;}
-/* if alpha is zero, it checks surrounding pixels and averages color. sets new alphas to 255 */
-void IMB_filter_extend(struct ImBuf *ibuf)
+/* if alpha is zero, it checks surrounding pixels and averages color. sets new alphas to 1.0
+ *
+ * When a mask is given, only effect pixels with a mask value of 1, defined as BAKE_MASK_MARGIN in rendercore.c
+ * */
+void IMB_filter_extend(struct ImBuf *ibuf, char *mask)
{
register char *row1, *row2, *row3;
- register char *cp;
+ register char *cp;
int rowlen, x, y;
rowlen= ibuf->x;
- if(ibuf->rect) {
+
+ if (ibuf->rect_float) {
+ float *temprect;
+ float *row1f, *row2f, *row3f;
+ float *fp;
+ temprect= MEM_dupallocN(ibuf->rect_float);
+
+ for(y=1; y<=ibuf->y; y++) {
+ /* setup rows */
+ row1f= (float *)(temprect + (y-2)*rowlen*4);
+ row2f= row1f + 4*rowlen;
+ row3f= row2f + 4*rowlen;
+ if(y==1)
+ row1f= row2f;
+ else if(y==ibuf->y)
+ row3f= row2f;
+
+ fp= (float *)(ibuf->rect_float + (y-1)*rowlen*4);
+
+ for(x=0; x<rowlen; x++) {
+ if((mask==NULL && fp[3]==0.0f) || (mask && mask[((y-1)*rowlen)+x]==1)) {
+ int tot= 0;
+ float r=0.0f, g=0.0f, b=0.0f, a=0.0f;
+
+ EXTEND_PIXEL(row1f, 1);
+ EXTEND_PIXEL(row2f, 2);
+ EXTEND_PIXEL(row3f, 1);
+ EXTEND_PIXEL(row1f+4, 2);
+ EXTEND_PIXEL(row3f+4, 2);
+ if(x!=rowlen-1) {
+ EXTEND_PIXEL(row1f+8, 1);
+ EXTEND_PIXEL(row2f+8, 2);
+ EXTEND_PIXEL(row3f+8, 1);
+ }
+ if(tot) {
+ fp[0]= r/tot;
+ fp[1]= g/tot;
+ fp[2]= b/tot;
+ fp[3]= a/tot;
+ }
+ }
+ fp+=4;
+
+ if(x!=0) {
+ row1f+=4; row2f+=4; row3f+=4;
+ }
+ }
+ }
+
+ MEM_freeN(temprect);
+ }
+ else if(ibuf->rect) {
int *temprect;
/* make a copy, to prevent flooding */
@@ -267,8 +338,9 @@ void IMB_filter_extend(struct ImBuf *ibuf)
cp= (char *)(ibuf->rect + (y-1)*rowlen);
for(x=0; x<rowlen; x++) {
- if(cp[3]==0) {
- int tot= 0, r=0, g=0, b=0;
+ /*if(cp[3]==0) {*/
+ if((mask==NULL && cp[3]==0) || (mask && mask[((y-1)*rowlen)+x]==1)) {
+ int tot= 0, r=0, g=0, b=0, a=0;
EXTEND_PIXEL(row1, 1);
EXTEND_PIXEL(row2, 2);
@@ -284,10 +356,10 @@ void IMB_filter_extend(struct ImBuf *ibuf)
cp[0]= r/tot;
cp[1]= g/tot;
cp[2]= b/tot;
- cp[3]= 255;
+ cp[3]= a/tot;
}
}
- cp+=4;
+ cp+=4;
if(x!=0) {
row1+=4; row2+=4; row3+=4;
diff --git a/source/blender/imbuf/intern/gen_dynlibtiff.py b/source/blender/imbuf/intern/gen_dynlibtiff.py
index 9cd6b638658..4dba5b13aa0 100755
--- a/source/blender/imbuf/intern/gen_dynlibtiff.py
+++ b/source/blender/imbuf/intern/gen_dynlibtiff.py
@@ -119,13 +119,19 @@ void libtiff_loadlibtiff(void)
/* Try to find libtiff in a couple of standard places */
libtiff = PIL_dynlib_open("libtiff.so");
if (libtiff != NULL) return;
+ libtiff = PIL_dynlib_open("libtiff.so.3");
+ if (libtiff != NULL) return;
libtiff = PIL_dynlib_open("libtiff.dll");
if (libtiff != NULL) return;
libtiff = PIL_dynlib_open("/usr/lib/libtiff.so");
if (libtiff != NULL) return;
- /* OSX has version specific library */
libtiff = PIL_dynlib_open("/usr/lib/libtiff.so.3");
if (libtiff != NULL) return;
+ /* OSX has version specific library */
+#ifdef __x86_64__
+ libtiff = PIL_dynlib_open("/usr/lib64/libtiff.so.3");
+ if (libtiff != NULL) return;
+#endif
libtiff = PIL_dynlib_open("/usr/local/lib/libtiff.so");
if (libtiff != NULL) return;
/* For solaris */
diff --git a/source/blender/imbuf/intern/hamx.c b/source/blender/imbuf/intern/hamx.c
index 8db21fc64f1..2f32d155407 100644
--- a/source/blender/imbuf/intern/hamx.c
+++ b/source/blender/imbuf/intern/hamx.c
@@ -53,7 +53,7 @@
#define SWAP_S(x) (((x << 8) & 0xff00) | ((x >> 8) & 0xff))
/* more endianness... should move to a separate file... */
-#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
+#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__hppa__) || defined (__BIG_ENDIAN__)
#define GET_ID GET_BIG_LONG
#define LITTLE_LONG SWAP_LONG
#else
diff --git a/source/blender/imbuf/intern/imageprocess.c b/source/blender/imbuf/intern/imageprocess.c
index 4890e240c6b..d7f1ab4419d 100644
--- a/source/blender/imbuf/intern/imageprocess.c
+++ b/source/blender/imbuf/intern/imageprocess.c
@@ -48,22 +48,28 @@ I stole it from util.h in the plugins api */
/* Only this one is used liberally here, and in imbuf */
void IMB_convert_rgba_to_abgr(struct ImBuf *ibuf)
{
- int size, do_float=0;
+ int size;
unsigned char rt, *cp = (unsigned char *)ibuf->rect;
float rtf, *cpf = ibuf->rect_float;
-
- if (ibuf->rect_float) do_float = 1;
- size = ibuf->x * ibuf->y;
- while(size-- > 0) {
- rt= cp[0];
- cp[0]= cp[3];
- cp[3]= rt;
- rt= cp[1];
- cp[1]= cp[2];
- cp[2]= rt;
- cp+= 4;
- if (do_float) {
+ if (ibuf->rect) {
+ size = ibuf->x * ibuf->y;
+
+ while(size-- > 0) {
+ rt= cp[0];
+ cp[0]= cp[3];
+ cp[3]= rt;
+ rt= cp[1];
+ cp[1]= cp[2];
+ cp[2]= rt;
+ cp+= 4;
+ }
+ }
+
+ if (ibuf->rect_float) {
+ size = ibuf->x * ibuf->y;
+
+ while(size-- > 0) {
rtf= cpf[0];
cpf[0]= cpf[3];
cpf[3]= rtf;
@@ -87,16 +93,14 @@ void IMB_convert_rgba_to_abgr(struct ImBuf *ibuf)
*/
/* function assumes out to be zero'ed, only does RGBA */
static float P(float k){
- float aux;
- aux=(float)(1.0f/6.0f)*( pow( MAX2(k+2.0f,0) , 3.0f ) - 4.0f * pow( MAX2(k+1.0f,0) , 3.0f ) + 6.0f * pow( MAX2(k,0) , 3.0f ) - 4.0f * pow( MAX2(k-1.0f,0) , 3.0f));
- return aux ;
+ return (float)(1.0f/6.0f)*( pow( MAX2(k+2.0f,0) , 3.0f ) - 4.0f * pow( MAX2(k+1.0f,0) , 3.0f ) + 6.0f * pow( MAX2(k,0) , 3.0f ) - 4.0f * pow( MAX2(k-1.0f,0) , 3.0f));
}
void bicubic_interpolation(ImBuf *in, ImBuf *out, float x, float y, int xout, int yout)
{
int i,j,n,m,x1,y1;
unsigned char *dataI,*outI;
- float a,b, outR,outG,outB,outA,*dataF,*outF;
+ float a,b,w,wx,wy[4], outR,outG,outB,outA,*dataF,*outF;
int do_rect, do_float;
if (in == NULL) return;
@@ -114,24 +118,39 @@ void bicubic_interpolation(ImBuf *in, ImBuf *out, float x, float y, int xout, in
outG= 0.0f;
outB= 0.0f;
outA= 0.0f;
+
+ /* avoid calling multiple times */
+ wy[0] = P(b-(-1));
+ wy[1] = P(b- 0);
+ wy[2] = P(b- 1);
+ wy[3] = P(b- 2);
+
for(n= -1; n<= 2; n++){
- for(m= -1; m<= 2; m++){
- x1= i+n;
- y1= j+m;
- if (x1>0 && x1 < in->x && y1>0 && y1<in->y) {
- if (do_float) {
- dataF= in->rect_float + in->x * y1 * 4 + 4*x1;
- outR+= dataF[0] * P(n-a) * P(b-m);
- outG+= dataF[1] * P(n-a) * P(b-m);
- outB+= dataF[2] * P(n-a) * P(b-m);
- outA+= dataF[3] * P(n-a) * P(b-m);
- }
- if (do_rect) {
- dataI= (unsigned char*)in->rect + in->x * y1 * 4 + 4*x1;
- outR+= dataI[0] * P(n-a) * P(b-m);
- outG+= dataI[1] * P(n-a) * P(b-m);
- outB+= dataI[2] * P(n-a) * P(b-m);
- outA+= dataI[3] * P(n-a) * P(b-m);
+ x1= i+n;
+ if (x1>0 && x1 < in->x) {
+ wx = P(n-a);
+ for(m= -1; m<= 2; m++){
+ y1= j+m;
+ if (y1>0 && y1<in->y) {
+ /* normally we could do this */
+ /* w = P(n-a) * P(b-m); */
+ /* except that would call P() 16 times per pixel therefor pow() 64 times, better precalc these */
+ w = wx * wy[m+1];
+
+ if (do_float) {
+ dataF= in->rect_float + in->x * y1 * 4 + 4*x1;
+ outR+= dataF[0] * w;
+ outG+= dataF[1] * w;
+ outB+= dataF[2] * w;
+ outA+= dataF[3] * w;
+ }
+ if (do_rect) {
+ dataI= (unsigned char*)in->rect + in->x * y1 * 4 + 4*x1;
+ outR+= dataI[0] * w;
+ outG+= dataI[1] * w;
+ outB+= dataI[2] * w;
+ outA+= dataI[3] * w;
+ }
}
}
}
diff --git a/source/blender/imbuf/intern/imbuf.h b/source/blender/imbuf/intern/imbuf.h
index 9bdcd278f66..bd2a0d3082f 100644
--- a/source/blender/imbuf/intern/imbuf.h
+++ b/source/blender/imbuf/intern/imbuf.h
@@ -60,7 +60,7 @@
#define ENDIAN_NOP(x) (x)
-#if defined(__sgi) || defined(__sparc) || defined(__sparc__) || defined (__PPC__) || (defined (__APPLE__) && !defined(__LITTLE_ENDIAN__))
+#if defined(__sgi) || defined(__sparc) || defined(__sparc__) || defined (__PPC__) || defined (__hppa__) || (defined (__APPLE__) && !defined(__LITTLE_ENDIAN__))
#define LITTLE_SHORT SWAP_SHORT
#define LITTLE_LONG SWAP_LONG
#define BIG_SHORT ENDIAN_NOP
diff --git a/source/blender/imbuf/intern/imbuf_patch.h b/source/blender/imbuf/intern/imbuf_patch.h
index 0405ce7bc05..cdd6048f1ad 100644
--- a/source/blender/imbuf/intern/imbuf_patch.h
+++ b/source/blender/imbuf/intern/imbuf_patch.h
@@ -50,7 +50,7 @@ typedef unsigned char uchar;
/* Endianness: flip the byte order. It's strange that this is needed..
* After all, there is an internal endian.{c,h}... */
-#if defined(__sgi) || defined (__sparc) || defined(__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
+#if defined(__sgi) || defined (__sparc) || defined(__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__hppa__) || defined (__BIG_ENDIAN__)
#define MAKE_ID(a,b,c,d) ( (int)(a)<<24 | (int)(b)<<16 | (c)<<8 | (d) )
#else
#define MAKE_ID(a,b,c,d) ( (int)(d)<<24 | (int)(c)<<16 | (b)<<8 | (a) )
diff --git a/source/blender/imbuf/intern/openexr/openexr_api.cpp b/source/blender/imbuf/intern/openexr/openexr_api.cpp
index 3cbada812b9..3e618a483e3 100644
--- a/source/blender/imbuf/intern/openexr/openexr_api.cpp
+++ b/source/blender/imbuf/intern/openexr/openexr_api.cpp
@@ -180,7 +180,7 @@ static void openexr_header_compression(Header *header, int compression)
static short imb_save_openexr_half(struct ImBuf *ibuf, char *name, int flags)
{
-
+ int channels = ibuf->channels;
int width = ibuf->x;
int height = ibuf->y;
int write_zbuf = (flags & IB_zbuffloat) && ibuf->zbuf_float != NULL; // summarize
@@ -194,7 +194,7 @@ static short imb_save_openexr_half(struct ImBuf *ibuf, char *name, int flags)
header.channels().insert ("R", Channel (HALF));
header.channels().insert ("G", Channel (HALF));
header.channels().insert ("B", Channel (HALF));
- if (ibuf->depth==32)
+ if (ibuf->depth==32 && channels >= 4)
header.channels().insert ("A", Channel (HALF));
if (write_zbuf) // z we do as float always
header.channels().insert ("Z", Channel (FLOAT));
@@ -207,29 +207,29 @@ static short imb_save_openexr_half(struct ImBuf *ibuf, char *name, int flags)
RGBAZ *to = pixels;
int xstride= sizeof (RGBAZ);
int ystride= xstride*width;
-
+
/* indicate used buffers */
frameBuffer.insert ("R", Slice (HALF, (char *) &pixels[0].r, xstride, ystride));
frameBuffer.insert ("G", Slice (HALF, (char *) &pixels[0].g, xstride, ystride));
frameBuffer.insert ("B", Slice (HALF, (char *) &pixels[0].b, xstride, ystride));
- if (ibuf->depth==32)
+ if (ibuf->depth==32 && channels >= 4)
frameBuffer.insert ("A", Slice (HALF, (char *) &pixels[0].a, xstride, ystride));
if (write_zbuf)
- frameBuffer.insert ("Z", Slice (FLOAT, (char *) ibuf->zbuf_float + 4*(height-1)*width,
+ frameBuffer.insert ("Z", Slice (FLOAT, (char *)(ibuf->zbuf_float + (height-1)*width),
sizeof(float), sizeof(float) * -width));
if(ibuf->rect_float) {
float *from;
for (int i = ibuf->y-1; i >= 0; i--)
{
- from= ibuf->rect_float + 4*i*width;
+ from= ibuf->rect_float + channels*i*width;
for (int j = ibuf->x; j > 0; j--)
{
to->r = from[0];
- to->g = from[1];
- to->b = from[2];
- to->a = from[3];
+ to->g = (channels >= 2)? from[1]: from[0];
+ to->b = (channels >= 3)? from[2]: from[0];
+ to->a = (channels >= 4)? from[3]: from[0];
to++; from += 4;
}
}
@@ -239,14 +239,14 @@ static short imb_save_openexr_half(struct ImBuf *ibuf, char *name, int flags)
for (int i = ibuf->y-1; i >= 0; i--)
{
- from= (unsigned char *)(ibuf->rect + i*width);
+ from= (unsigned char *)ibuf->rect + channels*i*width;
for (int j = ibuf->x; j > 0; j--)
{
to->r = (float)(from[0])/255.0;
- to->g = (float)(from[1])/255.0;
- to->b = (float)(from[2])/255.0;
- to->a = (float)(from[3])/255.0;
+ to->g = (float)((channels >= 2)? from[1]: from[0])/255.0;
+ to->b = (float)((channels >= 3)? from[2]: from[0])/255.0;
+ to->a = (float)((channels >= 4)? from[3]: from[0])/255.0;
to++; from += 4;
}
}
@@ -272,7 +272,7 @@ static short imb_save_openexr_half(struct ImBuf *ibuf, char *name, int flags)
static short imb_save_openexr_float(struct ImBuf *ibuf, char *name, int flags)
{
-
+ int channels = ibuf->channels;
int width = ibuf->x;
int height = ibuf->y;
int write_zbuf = (flags & IB_zbuffloat) && ibuf->zbuf_float != NULL; // summarize
@@ -286,24 +286,29 @@ static short imb_save_openexr_float(struct ImBuf *ibuf, char *name, int flags)
header.channels().insert ("R", Channel (FLOAT));
header.channels().insert ("G", Channel (FLOAT));
header.channels().insert ("B", Channel (FLOAT));
- if (ibuf->depth==32)
+ if (ibuf->depth==32 && channels >= 4)
header.channels().insert ("A", Channel (FLOAT));
if (write_zbuf)
header.channels().insert ("Z", Channel (FLOAT));
FrameBuffer frameBuffer;
OutputFile *file = new OutputFile(name, header);
- float *first= ibuf->rect_float + 4*(height-1)*width;
- int xstride = sizeof(float) * 4;
+ int xstride = sizeof(float) * channels;
int ystride = - xstride*width;
-
- frameBuffer.insert ("R", Slice (FLOAT, (char *) first, xstride, ystride));
- frameBuffer.insert ("G", Slice (FLOAT, (char *) (first+1), xstride, ystride));
- frameBuffer.insert ("B", Slice (FLOAT, (char *) (first+2), xstride, ystride));
- if (ibuf->depth==32)
- frameBuffer.insert ("A", Slice (FLOAT, (char *) (first+3), xstride, ystride));
+ float *rect[4] = {NULL, NULL, NULL, NULL};
+
+ rect[0]= ibuf->rect_float + channels*(height-1)*width;
+ rect[1]= (channels >= 2)? rect[0]+1: rect[0];
+ rect[2]= (channels >= 3)? rect[0]+2: rect[0];
+ rect[3]= (channels >= 4)? rect[0]+3: rect[0];
+
+ frameBuffer.insert ("R", Slice (FLOAT, (char *)rect[0], xstride, ystride));
+ frameBuffer.insert ("G", Slice (FLOAT, (char *)rect[1], xstride, ystride));
+ frameBuffer.insert ("B", Slice (FLOAT, (char *)rect[2], xstride, ystride));
+ if (ibuf->depth==32 && channels >= 4)
+ frameBuffer.insert ("A", Slice (FLOAT, (char *)rect[3], xstride, ystride));
if (write_zbuf)
- frameBuffer.insert ("Z", Slice (FLOAT, (char *) ibuf->zbuf_float + 4*(height-1)*width,
+ frameBuffer.insert ("Z", Slice (FLOAT, (char *) (ibuf->zbuf_float + (height-1)*width),
sizeof(float), sizeof(float) * -width));
file->setFrameBuffer (frameBuffer);
file->writePixels (height);
@@ -362,6 +367,7 @@ typedef struct ExrHandle {
OutputFile *ofile;
int tilex, tiley;
int width, height;
+ int mipmap;
ListBase channels; /* flattened out, ExrChannel */
ListBase layers; /* hierarchical, pointing in end to ExrChannel */
@@ -445,12 +451,12 @@ void IMB_exr_begin_write(void *handle, char *filename, int width, int height, in
openexr_header_compression(&header, compress);
/* header.lineOrder() = DECREASING_Y; this crashes in windows for file read! */
- header.insert ("BlenderMultiChannel", StringAttribute ("Blender V2.43"));
+ header.insert ("BlenderMultiChannel", StringAttribute ("Blender V2.43 and newer"));
data->ofile = new OutputFile(filename, header);
}
-void IMB_exrtile_begin_write(void *handle, char *filename, int width, int height, int tilex, int tiley)
+void IMB_exrtile_begin_write(void *handle, char *filename, int mipmap, int width, int height, int tilex, int tiley)
{
ExrHandle *data= (ExrHandle *)handle;
Header header (width, height);
@@ -460,11 +466,12 @@ void IMB_exrtile_begin_write(void *handle, char *filename, int width, int height
data->tiley= tiley;
data->width= width;
data->height= height;
+ data->mipmap= mipmap;
for(echan= (ExrChannel *)data->channels.first; echan; echan= echan->next)
header.channels().insert (echan->name, Channel (FLOAT));
- header.setTileDescription (TileDescription (tilex, tiley, ONE_LEVEL));
+ header.setTileDescription (TileDescription (tilex, tiley, (mipmap)? MIPMAP_LEVELS: ONE_LEVEL));
header.lineOrder() = RANDOM_Y;
header.compression() = RLE_COMPRESSION;
@@ -478,7 +485,7 @@ int IMB_exr_begin_read(void *handle, char *filename, int *width, int *height)
{
ExrHandle *data= (ExrHandle *)handle;
- if(BLI_exists(filename)) {
+ if(BLI_exists(filename) && BLI_filepathsize(filename)>32) { /* 32 is arbitrary, but zero length files crashes exr */
data->ifile = new InputFile(filename);
if(data->ifile) {
Box2i dw = data->ifile->header().dataWindow();
@@ -533,7 +540,7 @@ void IMB_exrtile_clear_channels(void *handle)
BLI_freelistN(&data->channels);
}
-void IMB_exrtile_write_channels(void *handle, int partx, int party)
+void IMB_exrtile_write_channels(void *handle, int partx, int party, int level)
{
ExrHandle *data= (ExrHandle *)handle;
FrameBuffer frameBuffer;
@@ -547,9 +554,14 @@ void IMB_exrtile_write_channels(void *handle, int partx, int party)
}
data->tofile->setFrameBuffer (frameBuffer);
- // printf("write tile %d %d\n", partx/data->tilex, party/data->tiley);
- data->tofile->writeTile (partx/data->tilex, party/data->tiley);
-
+
+ try {
+ // printf("write tile %d %d\n", partx/data->tilex, party/data->tiley);
+ data->tofile->writeTile (partx/data->tilex, party/data->tiley, level);
+ }
+ catch (const std::exception &exc) {
+ std::cerr << "OpenEXR-writeTile: ERROR: " << exc.what() << std::endl;
+ }
}
void IMB_exr_write_channels(void *handle)
@@ -615,7 +627,6 @@ void IMB_exr_multilayer_convert(void *handle, void *base,
void IMB_exr_close(void *handle)
{
ExrHandle *data= (ExrHandle *)handle;
- ExrChannel *echan;
ExrLayer *lay;
ExrPass *pass;
@@ -778,28 +789,28 @@ static ExrHandle *imb_exr_begin_read_mem(InputFile *file, int width, int height)
/* we can have RGB(A), XYZ(W), UVA */
if(pass->totchan==3 || pass->totchan==4) {
if(pass->chan[0]->chan_id=='B' || pass->chan[1]->chan_id=='B' || pass->chan[2]->chan_id=='B') {
- lookup['R']= 0;
- lookup['G']= 1;
- lookup['B']= 2;
- lookup['A']= 3;
+ lookup[(unsigned int)'R']= 0;
+ lookup[(unsigned int)'G']= 1;
+ lookup[(unsigned int)'B']= 2;
+ lookup[(unsigned int)'A']= 3;
}
else if(pass->chan[0]->chan_id=='Y' || pass->chan[1]->chan_id=='Y' || pass->chan[2]->chan_id=='Y') {
- lookup['X']= 0;
- lookup['Y']= 1;
- lookup['Z']= 2;
- lookup['W']= 3;
+ lookup[(unsigned int)'X']= 0;
+ lookup[(unsigned int)'Y']= 1;
+ lookup[(unsigned int)'Z']= 2;
+ lookup[(unsigned int)'W']= 3;
}
else {
- lookup['U']= 0;
- lookup['V']= 1;
- lookup['A']= 2;
+ lookup[(unsigned int)'U']= 0;
+ lookup[(unsigned int)'V']= 1;
+ lookup[(unsigned int)'A']= 2;
}
for(a=0; a<pass->totchan; a++) {
echan= pass->chan[a];
- echan->rect= pass->rect + lookup[echan->chan_id];
+ echan->rect= pass->rect + lookup[(unsigned int)echan->chan_id];
echan->xstride= pass->totchan;
echan->ystride= width*pass->totchan;
- pass->chan_id[ lookup[echan->chan_id] ]= echan->chan_id;
+ pass->chan_id[ (unsigned int)lookup[(unsigned int)echan->chan_id] ]= echan->chan_id;
}
}
else { /* unknown */
@@ -831,6 +842,7 @@ typedef struct RGBA
} RGBA;
+/* debug only */
static void exr_print_filecontents(InputFile *file)
{
const ChannelList &channels = file->header().channels();
@@ -842,13 +854,33 @@ static void exr_print_filecontents(InputFile *file)
}
}
-static int exr_has_zbuffer(InputFile *file)
+/* for non-multilayer, map R G B A channel names to something that's in this file */
+static const char *exr_rgba_channelname(InputFile *file, const char *chan)
{
const ChannelList &channels = file->header().channels();
for (ChannelList::ConstIterator i = channels.begin(); i != channels.end(); ++i)
{
const Channel &channel = i.channel();
+ const char *str= i.name();
+ int len= strlen(str);
+ if(len) {
+ if(BLI_strcasecmp(chan, str+len-1)==0) {
+ return str;
+ }
+ }
+ }
+ return chan;
+}
+
+
+
+static int exr_has_zbuffer(InputFile *file)
+{
+ const ChannelList &channels = file->header().channels();
+
+ for (ChannelList::ConstIterator i = channels.begin(); i != channels.end(); ++i)
+ {
if(strcmp("Z", i.name())==0)
return 1;
}
@@ -884,7 +916,8 @@ struct ImBuf *imb_load_openexr(unsigned char *mem, int size, int flags)
//printf("OpenEXR-load: image data window %d %d %d %d\n",
// dw.min.x, dw.min.y, dw.max.x, dw.max.y);
- // exr_print_filecontents(file);
+ if(0) // debug
+ exr_print_filecontents(file);
is_multi= exr_is_renderresult(file);
@@ -923,11 +956,15 @@ struct ImBuf *imb_load_openexr(unsigned char *mem, int size, int flags)
/* but, since we read y-flipped (negative y stride) we move to last scanline */
first+= 4*(height-1)*width;
- frameBuffer.insert ("R", Slice (FLOAT, (char *) first, xstride, ystride));
- frameBuffer.insert ("G", Slice (FLOAT, (char *) (first+1), xstride, ystride));
- frameBuffer.insert ("B", Slice (FLOAT, (char *) (first+2), xstride, ystride));
- /* 1.0 is fill value */
- frameBuffer.insert ("A", Slice (FLOAT, (char *) (first+3), xstride, ystride, 1, 1, 1.0f));
+ frameBuffer.insert ( exr_rgba_channelname(file, "R"),
+ Slice (FLOAT, (char *) first, xstride, ystride));
+ frameBuffer.insert ( exr_rgba_channelname(file, "G"),
+ Slice (FLOAT, (char *) (first+1), xstride, ystride));
+ frameBuffer.insert ( exr_rgba_channelname(file, "B"),
+ Slice (FLOAT, (char *) (first+2), xstride, ystride));
+
+ frameBuffer.insert ( exr_rgba_channelname(file, "A"),
+ Slice (FLOAT, (char *) (first+3), xstride, ystride, 1, 1, 1.0f)); /* 1.0 is fill value */
if(exr_has_zbuffer(file))
{
diff --git a/source/blender/imbuf/intern/openexr/openexr_multi.h b/source/blender/imbuf/intern/openexr/openexr_multi.h
index ca4f7405f44..be4d1314a80 100644
--- a/source/blender/imbuf/intern/openexr/openexr_multi.h
+++ b/source/blender/imbuf/intern/openexr/openexr_multi.h
@@ -46,13 +46,13 @@ void IMB_exr_add_channel (void *handle, const char *layname, const char *passn
int IMB_exr_begin_read (void *handle, char *filename, int *width, int *height);
void IMB_exr_begin_write (void *handle, char *filename, int width, int height, int compress);
-void IMB_exrtile_begin_write (void *handle, char *filename, int width, int height, int tilex, int tiley);
+void IMB_exrtile_begin_write (void *handle, char *filename, int mipmap, int width, int height, int tilex, int tiley);
void IMB_exr_set_channel (void *handle, char *layname, char *passname, int xstride, int ystride, float *rect);
void IMB_exr_read_channels (void *handle);
void IMB_exr_write_channels (void *handle);
-void IMB_exrtile_write_channels (void *handle, int partx, int party);
+void IMB_exrtile_write_channels (void *handle, int partx, int party, int level);
void IMB_exrtile_clear_channels (void *handle);
void IMB_exr_multilayer_convert (void *handle, void *base,
@@ -71,13 +71,13 @@ void IMB_exr_add_channel (void *handle, const char *layname, const char *chann
int IMB_exr_begin_read (void *handle, char *filename, int *width, int *height) {return 0;}
void IMB_exr_begin_write (void *handle, char *filename, int width, int height, int compress) {}
-void IMB_exrtile_begin_write (void *handle, char *filename, int width, int height, int tilex, int tiley) {}
+void IMB_exrtile_begin_write (void *handle, char *filename, int mipmap, int width, int height, int tilex, int tiley) {}
void IMB_exr_set_channel (void *handle, char *layname, char *channame, int xstride, int ystride, float *rect) {}
void IMB_exr_read_channels (void *handle) {}
void IMB_exr_write_channels (void *handle) {}
-void IMB_exrtile_write_channels (void *handle, int partx, int party) {}
+void IMB_exrtile_write_channels (void *handle, int partx, int party, int level) {}
void IMB_exrtile_clear_channels (void *handle) {}
void IMB_exr_multilayer_convert (void *handle, void *base,
diff --git a/source/blender/imbuf/intern/radiance_hdr.c b/source/blender/imbuf/intern/radiance_hdr.c
index 3cb9ca79ffc..b4e384ada72 100644
--- a/source/blender/imbuf/intern/radiance_hdr.c
+++ b/source/blender/imbuf/intern/radiance_hdr.c
@@ -61,6 +61,7 @@
#define BLU 2
#define EXP 3
#define COLXS 128
+#define STR_MAX 540
typedef unsigned char RGBE[4];
typedef float fCOLOR[3];
/* copy source -> dest */
@@ -192,7 +193,8 @@ struct ImBuf *imb_loadhdr(unsigned char *mem, int size, int flags)
}
}
if (found) {
- sscanf((char*)&mem[x+1], "%s %d %s %d", (char*)&oriY, &height, (char*)&oriX, &width);
+ if (sscanf((char *)&mem[x+1], "%79s %d %79s %d", (char*)&oriY, &height,
+ (char*)&oriX, &width) != 4) return NULL;
/* find end of this line, data right behind it */
ptr = (unsigned char *)strchr((char*)&mem[x+1], '\n');
@@ -249,7 +251,7 @@ struct ImBuf *imb_loadhdr(unsigned char *mem, int size, int flags)
}
/* ImBuf write */
-static int fwritecolrs(FILE* file, int width, unsigned char* ibufscan, float* fpscan)
+static int fwritecolrs(FILE* file, int width, int channels, unsigned char* ibufscan, float* fpscan)
{
int x, i, j, beg, c2, cnt=0;
fCOLOR fcol;
@@ -264,16 +266,16 @@ static int fwritecolrs(FILE* file, int width, unsigned char* ibufscan, float* fp
for (i=0;i<width;i++) {
if (fpscan) {
fcol[RED] = fpscan[j];
- fcol[GRN] = fpscan[j+1];
- fcol[BLU] = fpscan[j+2];
+ fcol[GRN] = (channels >= 2)? fpscan[j+1]: fpscan[j];
+ fcol[BLU] = (channels >= 3)? fpscan[j+2]: fpscan[j];
} else {
fcol[RED] = (float)ibufscan[j] / 255.f;
- fcol[GRN] = (float)ibufscan[j+1] / 255.f;
- fcol[BLU] = (float)ibufscan[j+2] /255.f;
+ fcol[GRN] = (float)((channels >= 2)? ibufscan[j+1]: ibufscan[j]) / 255.f;
+ fcol[BLU] = (float)((channels >= 3)? ibufscan[j+2]: ibufscan[j]) / 255.f;
}
FLOAT2RGBE(fcol, rgbe);
copy_rgbe(rgbe, rgbe_scan[i]);
- j+=4;
+ j+=channels;
}
if ((width < MINELEN) | (width > MAXELEN)) { /* OOBs, write out flat */
@@ -346,18 +348,18 @@ short imb_savehdr(struct ImBuf *ibuf, char *name, int flags)
writeHeader(file, width, height);
if(ibuf->rect)
- cp= (unsigned char *)(ibuf->rect + (height-1)*width);
+ cp= (unsigned char *)ibuf->rect + ibuf->channels*(height-1)*width;
if(ibuf->rect_float)
- fp= ibuf->rect_float + 4*(height-1)*width;
+ fp= ibuf->rect_float + ibuf->channels*(height-1)*width;
for (y=height-1;y>=0;y--) {
- if (fwritecolrs(file, width, cp, fp) < 0) {
+ if (fwritecolrs(file, width, ibuf->channels, cp, fp) < 0) {
fclose(file);
printf("HDR write error\n");
return 0;
}
- if(cp) cp-= 4*width;
- if(fp) fp-= 4*width;
+ if(cp) cp-= ibuf->channels*width;
+ if(fp) fp-= ibuf->channels*width;
}
fclose(file);
diff --git a/source/blender/imbuf/intern/readimage.c b/source/blender/imbuf/intern/readimage.c
index b9c04e621ed..05e7921665b 100644
--- a/source/blender/imbuf/intern/readimage.c
+++ b/source/blender/imbuf/intern/readimage.c
@@ -29,8 +29,14 @@
* $Id$
*/
-#ifdef WIN32
+#ifdef _WIN32
#include <io.h>
+#include <stddef.h>
+#include <sys/types.h>
+#include "mmap_win.h"
+#define open _open
+#define read _read
+#define close _close
#endif
#include "BLI_blenlib.h"
@@ -73,7 +79,7 @@
#define SWAP_S(x) (((x << 8) & 0xff00) | ((x >> 8) & 0xff))
/* more endianness... should move to a separate file... */
-#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
+#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined(__hppa__) || defined (__BIG_ENDIAN__)
#define GET_ID GET_BIG_LONG
#define LITTLE_LONG SWAP_LONG
#else
@@ -229,7 +235,7 @@ struct ImBuf *IMB_loadifffile(int file, int flags) {
size = BLI_filesize(file);
-#if defined(AMIGA) || defined(__BeOS) || defined(WIN32)
+#if defined(AMIGA) || defined(__BeOS)
mem= (int *)malloc(size);
if (mem==0) {
printf("Out of mem\n");
diff --git a/source/blender/imbuf/intern/rectop.c b/source/blender/imbuf/intern/rectop.c
index 8b3902f77bf..56714c3b481 100644
--- a/source/blender/imbuf/intern/rectop.c
+++ b/source/blender/imbuf/intern/rectop.c
@@ -37,6 +37,7 @@
#include "IMB_imbuf.h"
#include "IMB_allocimbuf.h"
+#include "BKE_utildefines.h"
/* blend modes */
@@ -514,15 +515,13 @@ void IMB_rectfill(struct ImBuf *drect, float col[4])
}
}
-/* maybe we should use BKE_utildefines.h */
-#define FTOCHAR(val) (val<=0.0f ? 0: (val>=1.0f ? 255: (char)(255.99f*val)))
-#define CLAMP(a, b, c) if((a)<(b)) (a)=(b); else if((a)>(c)) (a)=(c)
-#define SWAP(type, a, b) { type sw_ap; sw_ap=(a); (a)=(b); (b)=sw_ap; }
void buf_rectfill_area(unsigned char *rect, float *rectf, int width, int height, float *col, int x1, int y1, int x2, int y2)
{
int i, j;
- float a, ai;
+ float a; /* alpha */
+ float ai; /* alpha inverted */
+ float aich; /* alpha, inverted, ai/255.0 - Convert char to float at the same time */
if ((!rect && !rectf) || (!col) || col[3]==0.0)
return;
@@ -538,7 +537,7 @@ void buf_rectfill_area(unsigned char *rect, float *rectf, int width, int height,
a = col[3];
ai = 1-a;
-
+ aich = ai/255.0f;
if (rect) {
unsigned char *pixel;
@@ -563,9 +562,9 @@ void buf_rectfill_area(unsigned char *rect, float *rectf, int width, int height,
pixel[1] = chg;
pixel[2] = chb;
} else {
- pixel[0] = (char)(fr + ((float)pixel[0]*ai));
- pixel[1] = (char)(fg + ((float)pixel[1]*ai));
- pixel[2] = (char)(fb + ((float)pixel[2]*ai));
+ pixel[0] = (char)((fr + ((float)pixel[0]*aich))*255.0f);
+ pixel[1] = (char)((fg + ((float)pixel[1]*aich))*255.0f);
+ pixel[2] = (char)((fb + ((float)pixel[2]*aich))*255.0f);
}
}
}
diff --git a/source/blender/imbuf/intern/rotate.c b/source/blender/imbuf/intern/rotate.c
index ca7ea01eaa6..c04987b3e71 100644
--- a/source/blender/imbuf/intern/rotate.c
+++ b/source/blender/imbuf/intern/rotate.c
@@ -40,48 +40,55 @@
void IMB_flipy(struct ImBuf * ibuf)
{
- short x, y;
- unsigned int *top, *bottom, do_float=0, *line;
- float *topf=NULL, *bottomf=NULL, *linef=NULL;
+ int x, y;
if (ibuf == NULL) return;
- if (ibuf->rect == NULL) return;
-
- if (ibuf->rect_float) do_float =1;
- x = ibuf->x;
- y = ibuf->y;
+ if (ibuf->rect) {
+ unsigned int *top, *bottom, *line;
+
+ x = ibuf->x;
+ y = ibuf->y;
- top = ibuf->rect;
- bottom = top + ((y-1) * x);
- line= MEM_mallocN(x*sizeof(int), "linebuf");
+ top = ibuf->rect;
+ bottom = top + ((y-1) * x);
+ line= MEM_mallocN(x*sizeof(int), "linebuf");
- if (do_float) {
+ y >>= 1;
+
+ for(;y>0;y--) {
+ memcpy(line, top, x*sizeof(int));
+ memcpy(top, bottom, x*sizeof(int));
+ memcpy(bottom, line, x*sizeof(int));
+ bottom -= x;
+ top+= x;
+ }
+
+ MEM_freeN(line);
+ }
+
+ if (ibuf->rect_float) {
+ float *topf=NULL, *bottomf=NULL, *linef=NULL;
+
+ x = ibuf->x;
+ y = ibuf->y;
+
topf= ibuf->rect_float;
bottomf = topf + 4*((y-1) * x);
linef= MEM_mallocN(4*x*sizeof(float), "linebuff");
- }
- y >>= 1;
-
- for(;y>0;y--) {
-
- memcpy(line, top, x*sizeof(int));
- memcpy(top, bottom, x*sizeof(int));
- memcpy(bottom, line, x*sizeof(int));
- bottom -= x;
- top+= x;
-
- if(do_float) {
+
+ y >>= 1;
+
+ for(;y>0;y--) {
memcpy(linef, topf, 4*x*sizeof(float));
memcpy(topf, bottomf, 4*x*sizeof(float));
memcpy(bottomf, linef, 4*x*sizeof(float));
bottomf -= 4*x;
topf+= 4*x;
}
+
+ MEM_freeN(linef);
}
-
- MEM_freeN(line);
- if(linef) MEM_freeN(linef);
}
void IMB_flipx(struct ImBuf * ibuf)
diff --git a/source/blender/imbuf/intern/scaling.c b/source/blender/imbuf/intern/scaling.c
index c46a4bf1e93..8257eb4643e 100644
--- a/source/blender/imbuf/intern/scaling.c
+++ b/source/blender/imbuf/intern/scaling.c
@@ -39,6 +39,8 @@
#include "IMB_allocimbuf.h"
#include "IMB_filter.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
/************************************************************************/
/* SCALING */
/************************************************************************/
@@ -480,6 +482,468 @@ struct ImBuf *IMB_halflace(struct ImBuf *ibuf1)
return (ibuf2);
}
+/* q_scale_linear_interpolation helper functions */
+
+static void enlarge_picture_byte(
+ unsigned char* src, unsigned char* dst, int src_width,
+ int src_height, int dst_width, int dst_height)
+{
+ double ratiox = (double) (dst_width - 1.0)
+ / (double) (src_width - 1.001);
+ double ratioy = (double) (dst_height - 1.0)
+ / (double) (src_height - 1.001);
+ uintptr_t x_src, dx_src, x_dst;
+ uintptr_t y_src, dy_src, y_dst;
+
+ dx_src = 65536.0 / ratiox;
+ dy_src = 65536.0 / ratioy;
+
+ y_src = 0;
+ for (y_dst = 0; y_dst < dst_height; y_dst++) {
+ unsigned char* line1 = src + (y_src >> 16) * 4 * src_width;
+ unsigned char* line2 = line1 + 4 * src_width;
+ uintptr_t weight1y = 65536 - (y_src & 0xffff);
+ uintptr_t weight2y = 65536 - weight1y;
+
+ if ((y_src >> 16) == src_height - 1) {
+ line2 = line1;
+ }
+
+ x_src = 0;
+ for (x_dst = 0; x_dst < dst_width; x_dst++) {
+ uintptr_t weight1x = 65536 - (x_src & 0xffff);
+ uintptr_t weight2x = 65536 - weight1x;
+
+ unsigned long x = (x_src >> 16) * 4;
+
+ *dst++ = ((((line1[x] * weight1y) >> 16)
+ * weight1x) >> 16)
+ + ((((line2[x] * weight2y) >> 16)
+ * weight1x) >> 16)
+ + ((((line1[4 + x] * weight1y) >> 16)
+ * weight2x) >> 16)
+ + ((((line2[4 + x] * weight2y) >> 16)
+ * weight2x) >> 16);
+
+ *dst++ = ((((line1[x + 1] * weight1y) >> 16)
+ * weight1x) >> 16)
+ + ((((line2[x + 1] * weight2y) >> 16)
+ * weight1x) >> 16)
+ + ((((line1[4 + x + 1] * weight1y) >> 16)
+ * weight2x) >> 16)
+ + ((((line2[4 + x + 1] * weight2y) >> 16)
+ * weight2x) >> 16);
+
+ *dst++ = ((((line1[x + 2] * weight1y) >> 16)
+ * weight1x) >> 16)
+ + ((((line2[x + 2] * weight2y) >> 16)
+ * weight1x) >> 16)
+ + ((((line1[4 + x + 2] * weight1y) >> 16)
+ * weight2x) >> 16)
+ + ((((line2[4 + x + 2] * weight2y) >> 16)
+ * weight2x) >> 16);
+
+ *dst++ = ((((line1[x + 3] * weight1y) >> 16)
+ * weight1x) >> 16)
+ + ((((line2[x + 3] * weight2y) >> 16)
+ * weight1x) >> 16)
+ + ((((line1[4 + x + 3] * weight1y) >> 16)
+ * weight2x) >> 16)
+ + ((((line2[4 + x + 3] * weight2y) >> 16)
+ * weight2x) >> 16);
+
+ x_src += dx_src;
+ }
+ y_src += dy_src;
+ }
+}
+
+struct scale_outpix_byte {
+ uintptr_t r;
+ uintptr_t g;
+ uintptr_t b;
+ uintptr_t a;
+
+ uintptr_t weight;
+};
+
+static void shrink_picture_byte(
+ unsigned char* src, unsigned char* dst, int src_width,
+ int src_height, int dst_width, int dst_height)
+{
+ double ratiox = (double) (dst_width) / (double) (src_width);
+ double ratioy = (double) (dst_height) / (double) (src_height);
+ uintptr_t x_src, dx_dst, x_dst;
+ uintptr_t y_src, dy_dst, y_dst;
+ intptr_t y_counter;
+ unsigned char * dst_begin = dst;
+
+ struct scale_outpix_byte * dst_line1 = NULL;
+ struct scale_outpix_byte * dst_line2 = NULL;
+
+ dst_line1 = (struct scale_outpix_byte*) MEM_callocN(
+ (dst_width + 1) * sizeof(struct scale_outpix_byte),
+ "shrink_picture_byte 1");
+ dst_line2 = (struct scale_outpix_byte*) MEM_callocN(
+ (dst_width + 1) * sizeof(struct scale_outpix_byte),
+ "shrink_picture_byte 2");
+
+ dx_dst = 65536.0 * ratiox;
+ dy_dst = 65536.0 * ratioy;
+
+ y_dst = 0;
+ y_counter = 65536;
+ for (y_src = 0; y_src < src_height; y_src++) {
+ unsigned char* line = src + y_src * 4 * src_width;
+ uintptr_t weight1y = 65536 - (y_dst & 0xffff);
+ uintptr_t weight2y = 65536 - weight1y;
+ x_dst = 0;
+ for (x_src = 0; x_src < src_width; x_src++) {
+ uintptr_t weight1x = 65536 - (x_dst & 0xffff);
+ uintptr_t weight2x = 65536 - weight1x;
+
+ uintptr_t x = x_dst >> 16;
+
+ uintptr_t w;
+
+ w = (weight1y * weight1x) >> 16;
+
+ dst_line1[x].r += (line[0] * w) >> 16;
+ dst_line1[x].g += (line[1] * w) >> 16;
+ dst_line1[x].b += (line[2] * w) >> 16;
+ dst_line1[x].a += (line[3] * w) >> 16;
+ dst_line1[x].weight += w;
+
+ w = (weight2y * weight1x) >> 16;
+
+ dst_line2[x].r += (line[0] * w) >> 16;
+ dst_line2[x].g += (line[1] * w) >> 16;
+ dst_line2[x].b += (line[2] * w) >> 16;
+ dst_line2[x].a += (line[3] * w) >> 16;
+ dst_line2[x].weight += w;
+
+ w = (weight1y * weight2x) >> 16;
+
+ dst_line1[x+1].r += (line[0] * w) >> 16;
+ dst_line1[x+1].g += (line[1] * w) >> 16;
+ dst_line1[x+1].b += (line[2] * w) >> 16;
+ dst_line1[x+1].a += (line[3] * w) >> 16;
+ dst_line1[x+1].weight += w;
+
+ w = (weight2y * weight2x) >> 16;
+
+ dst_line2[x+1].r += (line[0] * w) >> 16;
+ dst_line2[x+1].g += (line[1] * w) >> 16;
+ dst_line2[x+1].b += (line[2] * w) >> 16;
+ dst_line2[x+1].a += (line[3] * w) >> 16;
+ dst_line2[x+1].weight += w;
+
+ x_dst += dx_dst;
+ line += 4;
+ }
+
+ y_dst += dy_dst;
+ y_counter -= dy_dst;
+ if (y_counter < 0) {
+ uintptr_t x;
+ struct scale_outpix_byte * temp;
+
+ y_counter += 65536;
+
+ for (x=0; x < dst_width; x++) {
+ uintptr_t f = 0x80000000UL
+ / dst_line1[x].weight;
+ *dst++ = (dst_line1[x].r * f) >> 15;
+ *dst++ = (dst_line1[x].g * f) >> 15;
+ *dst++ = (dst_line1[x].b * f) >> 15;
+ *dst++ = (dst_line1[x].a * f) >> 15;
+ }
+ memset(dst_line1, 0, dst_width *
+ sizeof(struct scale_outpix_byte));
+ temp = dst_line1;
+ dst_line1 = dst_line2;
+ dst_line2 = temp;
+ }
+ }
+ if (dst - dst_begin < dst_width * dst_height * 4) {
+ uintptr_t x;
+ for (x = 0; x < dst_width; x++) {
+ uintptr_t f = 0x80000000UL / dst_line1[x].weight;
+ *dst++ = (dst_line1[x].r * f) >> 15;
+ *dst++ = (dst_line1[x].g * f) >> 15;
+ *dst++ = (dst_line1[x].b * f) >> 15;
+ *dst++ = (dst_line1[x].a * f) >> 15;
+ }
+ }
+ MEM_freeN(dst_line1);
+ MEM_freeN(dst_line2);
+}
+
+
+static void q_scale_byte(unsigned char* in, unsigned char* out, int in_width,
+ int in_height, int dst_width, int dst_height)
+{
+ if (dst_width > in_width && dst_height > in_height) {
+ enlarge_picture_byte(in, out, in_width, in_height,
+ dst_width, dst_height);
+ } else if (dst_width < in_width && dst_height < in_height) {
+ shrink_picture_byte(in, out, in_width, in_height,
+ dst_width, dst_height);
+ }
+}
+
+static void enlarge_picture_float(
+ float* src, float* dst, int src_width,
+ int src_height, int dst_width, int dst_height)
+{
+ double ratiox = (double) (dst_width - 1.0)
+ / (double) (src_width - 1.001);
+ double ratioy = (double) (dst_height - 1.0)
+ / (double) (src_height - 1.001);
+ uintptr_t x_dst;
+ uintptr_t y_dst;
+ double x_src, dx_src;
+ double y_src, dy_src;
+
+ dx_src = 1.0 / ratiox;
+ dy_src = 1.0 / ratioy;
+
+ y_src = 0;
+ for (y_dst = 0; y_dst < dst_height; y_dst++) {
+ float* line1 = src + ((int) y_src) * 4 * src_width;
+ float* line2 = line1 + 4 * src_width;
+ float weight1y = 1.0 - (y_src - (int) y_src);
+ float weight2y = 1.0 - weight1y;
+
+ if ((int) y_src == src_height - 1) {
+ line2 = line1;
+ }
+
+ x_src = 0;
+ for (x_dst = 0; x_dst < dst_width; x_dst++) {
+ float weight1x = 1.0 - (x_src - (int) x_src);
+ float weight2x = 1.0 - weight1x;
+
+ float w11 = weight1y * weight1x;
+ float w21 = weight2y * weight1x;
+ float w12 = weight1y * weight2x;
+ float w22 = weight2y * weight2x;
+
+ uintptr_t x = ((int) x_src) * 4;
+
+ *dst++ = line1[x] * w11
+ + line2[x] * w21
+ + line1[4 + x] * w12
+ + line2[4 + x] * w22;
+
+ *dst++ = line1[x + 1] * w11
+ + line2[x + 1] * w21
+ + line1[4 + x + 1] * w12
+ + line2[4 + x + 1] * w22;
+
+ *dst++ = line1[x + 2] * w11
+ + line2[x + 2] * w21
+ + line1[4 + x + 2] * w12
+ + line2[4 + x + 2] * w22;
+
+ *dst++ = line1[x + 3] * w11
+ + line2[x + 3] * w21
+ + line1[4 + x + 3] * w12
+ + line2[4 + x + 3] * w22;
+
+ x_src += dx_src;
+ }
+ y_src += dy_src;
+ }
+}
+
+struct scale_outpix_float {
+ float r;
+ float g;
+ float b;
+ float a;
+
+ float weight;
+};
+
+static void shrink_picture_float(
+ float* src, float* dst, int src_width,
+ int src_height, int dst_width, int dst_height)
+{
+ double ratiox = (double) (dst_width) / (double) (src_width);
+ double ratioy = (double) (dst_height) / (double) (src_height);
+ uintptr_t x_src;
+ uintptr_t y_src;
+ float dx_dst, x_dst;
+ float dy_dst, y_dst;
+ float y_counter;
+ float * dst_begin = dst;
+
+ struct scale_outpix_float * dst_line1;
+ struct scale_outpix_float * dst_line2;
+
+ dst_line1 = (struct scale_outpix_float*) MEM_callocN(
+ (dst_width + 1) * sizeof(struct scale_outpix_float),
+ "shrink_picture_float 1");
+ dst_line2 = (struct scale_outpix_float*) MEM_callocN(
+ (dst_width + 1) * sizeof(struct scale_outpix_float),
+ "shrink_picture_float 2");
+
+ dx_dst = ratiox;
+ dy_dst = ratioy;
+
+ y_dst = 0;
+ y_counter = 1.0;
+ for (y_src = 0; y_src < src_height; y_src++) {
+ float* line = src + y_src * 4 * src_width;
+ uintptr_t weight1y = 1.0 - (y_dst - (int) y_dst);
+ uintptr_t weight2y = 1.0 - weight1y;
+ x_dst = 0;
+ for (x_src = 0; x_src < src_width; x_src++) {
+ uintptr_t weight1x = 1.0 - (x_dst - (int) x_dst);
+ uintptr_t weight2x = 1.0 - weight1x;
+
+ uintptr_t x = (int) x_dst;
+
+ float w;
+
+ w = weight1y * weight1x;
+
+ dst_line1[x].r += line[0] * w;
+ dst_line1[x].g += line[1] * w;
+ dst_line1[x].b += line[2] * w;
+ dst_line1[x].a += line[3] * w;
+ dst_line1[x].weight += w;
+
+ w = weight2y * weight1x;
+
+ dst_line2[x].r += line[0] * w;
+ dst_line2[x].g += line[1] * w;
+ dst_line2[x].b += line[2] * w;
+ dst_line2[x].a += line[3] * w;
+ dst_line2[x].weight += w;
+
+ w = weight1y * weight2x;
+
+ dst_line1[x+1].r += line[0] * w;
+ dst_line1[x+1].g += line[1] * w;
+ dst_line1[x+1].b += line[2] * w;
+ dst_line1[x+1].a += line[3] * w;
+ dst_line1[x+1].weight += w;
+
+ w = weight2y * weight2x;
+
+ dst_line2[x+1].r += line[0] * w;
+ dst_line2[x+1].g += line[1] * w;
+ dst_line2[x+1].b += line[2] * w;
+ dst_line2[x+1].a += line[3] * w;
+ dst_line2[x+1].weight += w;
+
+ x_dst += dx_dst;
+ line += 4;
+ }
+
+ y_dst += dy_dst;
+ y_counter -= dy_dst;
+ if (y_counter < 0) {
+ uintptr_t x;
+ struct scale_outpix_float * temp;
+
+ y_counter += 1.0;
+
+ for (x=0; x < dst_width; x++) {
+ float f = 1.0 / dst_line1[x].weight;
+ *dst++ = dst_line1[x].r * f;
+ *dst++ = dst_line1[x].g * f;
+ *dst++ = dst_line1[x].b * f;
+ *dst++ = dst_line1[x].a * f;
+ }
+ memset(dst_line1, 0, dst_width *
+ sizeof(struct scale_outpix_float));
+ temp = dst_line1;
+ dst_line1 = dst_line2;
+ dst_line2 = temp;
+ }
+ }
+ if (dst - dst_begin < dst_width * dst_height * 4) {
+ uintptr_t x;
+ for (x = 0; x < dst_width; x++) {
+ float f = 1.0 / dst_line1[x].weight;
+ *dst++ = dst_line1[x].r * f;
+ *dst++ = dst_line1[x].g * f;
+ *dst++ = dst_line1[x].b * f;
+ *dst++ = dst_line1[x].a * f;
+ }
+ }
+ MEM_freeN(dst_line1);
+ MEM_freeN(dst_line2);
+}
+
+
+static void q_scale_float(float* in, float* out, int in_width,
+ int in_height, int dst_width, int dst_height)
+{
+ if (dst_width > in_width && dst_height > in_height) {
+ enlarge_picture_float(in, out, in_width, in_height,
+ dst_width, dst_height);
+ } else if (dst_width < in_width && dst_height < in_height) {
+ shrink_picture_float(in, out, in_width, in_height,
+ dst_width, dst_height);
+ }
+}
+
+/* q_scale_linear_interpolation (derived from ppmqscale, http://libdv.sf.net)
+
+ q stands for quick _and_ quality :)
+
+ only handles common cases when we either
+
+ scale both, x and y or
+ shrink both, x and y
+
+ but that is pretty fast:
+ * does only blit once instead of two passes like the old code
+ (fewer cache misses)
+ * uses fixed point integer arithmetic for byte buffers
+ * doesn't branch in tight loops
+
+ Should be comparable in speed to the ImBuf ..._fast functions at least
+ for byte-buffers.
+
+*/
+static int q_scale_linear_interpolation(
+ struct ImBuf *ibuf, int newx, int newy)
+{
+ if ((newx >= ibuf->x && newy <= ibuf->y) ||
+ (newx <= ibuf->x && newy >= ibuf->y)) {
+ return FALSE;
+ }
+
+ if (ibuf->rect) {
+ unsigned char * newrect =
+ MEM_mallocN(newx * newy * sizeof(int), "q_scale rect");
+ q_scale_byte((unsigned char *)ibuf->rect, newrect, ibuf->x, ibuf->y,
+ newx, newy);
+
+ imb_freerectImBuf(ibuf);
+ ibuf->mall |= IB_rect;
+ ibuf->rect = (unsigned int *) newrect;
+ }
+ if (ibuf->rect_float) {
+ float * newrect =
+ MEM_mallocN(newx * newy * 4 *sizeof(float),
+ "q_scale rectfloat");
+ q_scale_float(ibuf->rect_float, newrect, ibuf->x, ibuf->y,
+ newx, newy);
+ imb_freerectfloatImBuf(ibuf);
+ ibuf->mall |= IB_rectfloat;
+ ibuf->rect_float = newrect;
+ }
+ ibuf->x = newx;
+ ibuf->y = newy;
+
+ return TRUE;
+}
static struct ImBuf *scaledownx(struct ImBuf *ibuf, int newx)
{
@@ -1110,11 +1574,18 @@ struct ImBuf *IMB_scaleImBuf(struct ImBuf * ibuf, short newx, short newy)
{
if (ibuf==NULL) return (0);
if (ibuf->rect==NULL && ibuf->rect_float==NULL) return (ibuf);
+
+ if (newx == ibuf->x && newy == ibuf->y) { return ibuf; }
- // scaleup / scaledown functions below change ibuf->x and ibuf->y
- // so we first scale the Z-buffer (if any)
+ /* scaleup / scaledown functions below change ibuf->x and ibuf->y
+ so we first scale the Z-buffer (if any) */
scalefast_Z_ImBuf(ibuf, newx, newy);
+ /* try to scale common cases in a fast way */
+ if (q_scale_linear_interpolation(ibuf, newx, newy)) {
+ return ibuf;
+ }
+
if (newx < ibuf->x) if (newx) scaledownx(ibuf,newx);
if (newy < ibuf->y) if (newy) scaledowny(ibuf,newy);
if (newx > ibuf->x) if (newx) scaleupx(ibuf,newx);
diff --git a/source/blender/imbuf/intern/thumbs.c b/source/blender/imbuf/intern/thumbs.c
index 9097fb84dcd..14d6cb2d54b 100644
--- a/source/blender/imbuf/intern/thumbs.c
+++ b/source/blender/imbuf/intern/thumbs.c
@@ -78,18 +78,17 @@ static int get_thumb_dir( char* dir , ThumbSize size)
#endif
switch(size) {
case THB_NORMAL:
- strcat(dir, "/.thumbnails/normal");
+ strcat(dir, "/.thumbnails/normal/");
break;
case THB_LARGE:
- strcat(dir, "/.thumbnails/large");
+ strcat(dir, "/.thumbnails/large/");
break;
case THB_FAIL:
- strcat(dir, "/.thumbnails/fail/blender");
+ strcat(dir, "/.thumbnails/fail/blender/");
break;
default:
return 0; /* unknown size */
}
- BLI_cleanup_dir(G.sce, dir);
return 1;
}
diff --git a/source/blender/imbuf/intern/tiff.c b/source/blender/imbuf/intern/tiff.c
index 34d486fff11..194082d3e19 100644
--- a/source/blender/imbuf/intern/tiff.c
+++ b/source/blender/imbuf/intern/tiff.c
@@ -309,7 +309,7 @@ struct ImBuf *imb_loadtiff(unsigned char *mem, int size, int flags)
struct ImBuf *ibuf = NULL;
struct ImbTIFFMemFile memFile;
uint32 width, height;
- int bytesperpixel;
+ int bytesperpixel, bitspersample;
int success;
unsigned int pixel_i, byte_i;
uint32 *raster = NULL;
@@ -321,7 +321,7 @@ struct ImBuf *imb_loadtiff(unsigned char *mem, int size, int flags)
memFile.size = size;
/* check whether or not we have a TIFF file */
- if (size < IMB_TIFF_NCB) {
+ if (size < IMB_TIFF_NCB) {
fprintf(stderr, "imb_loadtiff: size < IMB_TIFF_NCB\n");
return NULL;
}
@@ -343,6 +343,7 @@ struct ImBuf *imb_loadtiff(unsigned char *mem, int size, int flags)
bytesperpixel = 4; /* 1 byte per channel, 4 channels */
libtiff_TIFFGetField(image, TIFFTAG_IMAGEWIDTH, &width);
libtiff_TIFFGetField(image, TIFFTAG_IMAGELENGTH, &height);
+ libtiff_TIFFGetField(image, TIFFTAG_BITSPERSAMPLE, &bitspersample);
ibuf = IMB_allocImBuf(width, height, 8*bytesperpixel, 0, 0);
if (ibuf) {
ibuf->ftype = TIF;
@@ -415,8 +416,6 @@ struct ImBuf *imb_loadtiff(unsigned char *mem, int size, int flags)
return (ibuf);
}
-
-
/**
* Saves a TIFF file.
*
@@ -432,14 +431,19 @@ struct ImBuf *imb_loadtiff(unsigned char *mem, int size, int flags)
*
* @return: 1 if the function is successful, 0 on failure.
*/
+
+#define FTOUSHORT(val) ((val >= 1.0f-0.5f/65535)? 65535: (val <= 0.0f)? 0: (unsigned short)(val*65535.0f + 0.5f))
+
short imb_savetiff(struct ImBuf *ibuf, char *name, int flags)
{
TIFF *image = NULL;
- uint16 samplesperpixel;
+ uint16 samplesperpixel, bitspersample;
size_t npixels;
unsigned char *pixels = NULL;
unsigned char *from = NULL, *to = NULL;
- int x, y, from_i, to_i;
+ unsigned short *pixels16 = NULL, *to16 = NULL;
+ float *fromf = NULL;
+ int x, y, from_i, to_i, i;
int extraSampleTypes[1] = { EXTRASAMPLE_ASSOCALPHA };
/* check for a valid number of bytes per pixel. Like the PNG writer,
@@ -453,6 +457,11 @@ short imb_savetiff(struct ImBuf *ibuf, char *name, int flags)
return (0);
}
+ if((ibuf->ftype & TIF_16BIT) && ibuf->rect_float)
+ bitspersample = 16;
+ else
+ bitspersample = 8;
+
/* open TIFF file for writing */
if (flags & IB_mem) {
/* bork at the creation of a TIFF in memory */
@@ -472,67 +481,67 @@ short imb_savetiff(struct ImBuf *ibuf, char *name, int flags)
/* allocate array for pixel data */
npixels = ibuf->x * ibuf->y;
- pixels = (unsigned char*)libtiff__TIFFmalloc(npixels *
- samplesperpixel * sizeof(unsigned char));
- if (pixels == NULL) {
+ if(bitspersample == 16)
+ pixels16 = (unsigned short*)libtiff__TIFFmalloc(npixels *
+ samplesperpixel * sizeof(unsigned short));
+ else
+ pixels = (unsigned char*)libtiff__TIFFmalloc(npixels *
+ samplesperpixel * sizeof(unsigned char));
+
+ if (pixels == NULL && pixels16 == NULL) {
fprintf(stderr,
"imb_savetiff: could not allocate pixels array.\n");
libtiff_TIFFClose(image);
return (0);
}
- /* copy pixel data. While copying, we flip the image
- * vertically. */
- from = (unsigned char*)ibuf->rect;
- to = pixels;
+ /* setup pointers */
+ if(bitspersample == 16) {
+ fromf = ibuf->rect_float;
+ to16 = pixels16;
+ }
+ else {
+ from = (unsigned char*)ibuf->rect;
+ to = pixels;
+ }
+
+ /* setup samples per pixel */
+ libtiff_TIFFSetField(image, TIFFTAG_BITSPERSAMPLE, bitspersample);
libtiff_TIFFSetField(image, TIFFTAG_SAMPLESPERPIXEL, samplesperpixel);
- switch (samplesperpixel) {
- case 4: /* RGBA images, 8 bits per channel */
- libtiff_TIFFSetField(image, TIFFTAG_EXTRASAMPLES, 1,
- extraSampleTypes);
- libtiff_TIFFSetField(image, TIFFTAG_BITSPERSAMPLE, 8);
- libtiff_TIFFSetField(image, TIFFTAG_PHOTOMETRIC,
- PHOTOMETRIC_RGB);
- for (x = 0; x < ibuf->x; x++) {
- for (y = 0; y < ibuf->y; y++) {
- from_i = 4*(y*ibuf->x+x);
- to_i = 4*((ibuf->y-y-1)*ibuf->x+x);
-
- to[to_i++] = from[from_i++];
- to[to_i++] = from[from_i++];
- to[to_i++] = from[from_i++];
- to[to_i] = from[from_i];
- }
- }
- break;
- case 3: /* RGB images, 8 bits per channel */
- libtiff_TIFFSetField(image, TIFFTAG_BITSPERSAMPLE, 8);
- libtiff_TIFFSetField(image, TIFFTAG_PHOTOMETRIC,
- PHOTOMETRIC_RGB);
- for (x = 0; x < ibuf->x; x++) {
- for (y = 0; y < ibuf->y; y++) {
- from_i = 4*(y*ibuf->x+x);
- to_i = 3*((ibuf->y-y-1)*ibuf->x+x);
-
- to[to_i++] = from[from_i++];
- to[to_i++] = from[from_i++];
- to[to_i] = from[from_i];
- }
- }
- break;
- case 1: /* greyscale images, 1 channel with 8 bits */
- libtiff_TIFFSetField(image, TIFFTAG_BITSPERSAMPLE, 8);
- libtiff_TIFFSetField(image, TIFFTAG_PHOTOMETRIC,
- PHOTOMETRIC_MINISBLACK);
- for (x = 0; x < ibuf->x; x++) {
- for (y = 0; y < ibuf->y; y++) {
- from_i = 4*(y*ibuf->x+x);
- to_i = 1*((ibuf->y-y-1)*ibuf->x+x);
+ if(samplesperpixel == 4) {
+ /* RGBA images */
+ libtiff_TIFFSetField(image, TIFFTAG_EXTRASAMPLES, 1,
+ extraSampleTypes);
+ libtiff_TIFFSetField(image, TIFFTAG_PHOTOMETRIC,
+ PHOTOMETRIC_RGB);
+ }
+ else if(samplesperpixel == 3) {
+ /* RGB images */
+ libtiff_TIFFSetField(image, TIFFTAG_PHOTOMETRIC,
+ PHOTOMETRIC_RGB);
+ }
+ else if(samplesperpixel == 1) {
+ /* greyscale images, 1 channel */
+ libtiff_TIFFSetField(image, TIFFTAG_PHOTOMETRIC,
+ PHOTOMETRIC_MINISBLACK);
+ }
+
+ /* copy pixel data. While copying, we flip the image vertically. */
+ for (x = 0; x < ibuf->x; x++) {
+ for (y = 0; y < ibuf->y; y++) {
+ from_i = 4*(y*ibuf->x+x);
+ to_i = samplesperpixel*((ibuf->y-y-1)*ibuf->x+x);
+
+ if(pixels16) {
+ for (i = 0; i < samplesperpixel; i++, to_i++, from_i++)
+ to16[to_i] = FTOUSHORT(fromf[from_i]);
+ }
+ else {
+ for (i = 0; i < samplesperpixel; i++, to_i++, from_i++)
to[to_i] = from[from_i];
- }
}
- break;
+ }
}
/* write the actual TIFF file */
@@ -545,18 +554,21 @@ short imb_savetiff(struct ImBuf *ibuf, char *name, int flags)
libtiff_TIFFSetField(image, TIFFTAG_XRESOLUTION, 150.0);
libtiff_TIFFSetField(image, TIFFTAG_YRESOLUTION, 150.0);
libtiff_TIFFSetField(image, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH);
- if (libtiff_TIFFWriteEncodedStrip(image, 0, pixels,
- ibuf->x*ibuf->y*samplesperpixel) == -1) {
+ if (libtiff_TIFFWriteEncodedStrip(image, 0,
+ (bitspersample == 16)? (unsigned char*)pixels16: pixels,
+ ibuf->x*ibuf->y*samplesperpixel*bitspersample/8) == -1) {
fprintf(stderr,
"imb_savetiff: Could not write encoded TIFF.\n");
libtiff_TIFFClose(image);
- libtiff__TIFFfree(pixels);
+ if(pixels) libtiff__TIFFfree(pixels);
+ if(pixels16) libtiff__TIFFfree(pixels16);
return (1);
}
/* close the TIFF file */
libtiff_TIFFClose(image);
- libtiff__TIFFfree(pixels);
+ if(pixels) libtiff__TIFFfree(pixels);
+ if(pixels16) libtiff__TIFFfree(pixels16);
return (1);
}
diff --git a/source/blender/imbuf/intern/util.c b/source/blender/imbuf/intern/util.c
index 4620797518a..c86f9b017bf 100644
--- a/source/blender/imbuf/intern/util.c
+++ b/source/blender/imbuf/intern/util.c
@@ -29,6 +29,13 @@
* $Id$
*/
+#ifdef _WIN32
+#include <io.h>
+#define open _open
+#define read _read
+#define close _close
+#endif
+
#include "BLI_blenlib.h"
#include "DNA_userdef_types.h"
@@ -64,6 +71,8 @@
#ifdef WITH_FFMPEG
#include <ffmpeg/avcodec.h>
#include <ffmpeg/avformat.h>
+//#include <ffmpeg/avdevice.h>
+#include <ffmpeg/log.h>
#if LIBAVFORMAT_VERSION_INT < (49 << 16)
#define FFMPEG_OLD_FRAME_RATE 1
@@ -229,12 +238,32 @@ static int isqtime (char *name) {
#endif
#ifdef WITH_FFMPEG
+
+void silence_log_ffmpeg(int quiet)
+{
+ if (quiet)
+ {
+ av_log_set_level(AV_LOG_QUIET);
+ }
+ else
+ {
+ av_log_set_level(AV_LOG_INFO);
+ }
+}
+
+extern void do_init_ffmpeg();
void do_init_ffmpeg()
{
static int ffmpeg_init = 0;
if (!ffmpeg_init) {
ffmpeg_init = 1;
av_register_all();
+ //avdevice_register_all();
+
+ if ((G.f & G_DEBUG) == 0)
+ {
+ silence_log_ffmpeg(1);
+ }
}
}
@@ -253,7 +282,8 @@ static AVCodecContext* get_codec_from_stream(AVStream* stream)
static int isffmpeg (char *filename) {
AVFormatContext *pFormatCtx;
- int i, videoStream;
+ unsigned int i;
+ int videoStream;
AVCodec *pCodec;
AVCodecContext *pCodecCtx;
@@ -286,8 +316,9 @@ static int isffmpeg (char *filename) {
/* Find the first video stream */
videoStream=-1;
for(i=0; i<pFormatCtx->nb_streams; i++)
- if(get_codec_from_stream(pFormatCtx->streams[i])
- ->codec_type==CODEC_TYPE_VIDEO)
+ if(pFormatCtx->streams[i] &&
+ get_codec_from_stream(pFormatCtx->streams[i]) &&
+ (get_codec_from_stream(pFormatCtx->streams[i])->codec_type==CODEC_TYPE_VIDEO))
{
videoStream=i;
break;
@@ -303,13 +334,11 @@ static int isffmpeg (char *filename) {
/* Find the decoder for the video stream */
pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
if(pCodec==NULL) {
- avcodec_close(pCodecCtx);
av_close_input_file(pFormatCtx);
return 0;
}
if(avcodec_open(pCodecCtx, pCodec)<0) {
- avcodec_close(pCodecCtx);
av_close_input_file(pFormatCtx);
return 0;
}
@@ -321,6 +350,19 @@ static int isffmpeg (char *filename) {
}
#endif
+#ifdef WITH_REDCODE
+static int isredcode(char * filename)
+{
+ struct redcode_handle * h = redcode_open(filename);
+ if (!h) {
+ return 0;
+ }
+ redcode_close(h);
+ return 1;
+}
+
+#endif
+
int imb_get_anim_type(char * name) {
int type;
struct stat st;
@@ -355,6 +397,9 @@ int imb_get_anim_type(char * name) {
if (isffmpeg(name)) return (ANIM_FFMPEG);
# endif
#endif
+#ifdef WITH_REDCODE
+ if (isredcode(name)) return (ANIM_REDCODE);
+#endif
type = IMB_ispic(name);
if (type == ANIM) return (ANIM_ANIM5);
if (type) return(ANIM_SEQUENCE);
@@ -369,6 +414,7 @@ int IMB_isanim(char *filename) {
if( BLI_testextensie(filename, ".avi")
|| BLI_testextensie(filename, ".flc")
|| BLI_testextensie(filename, ".dv")
+ || BLI_testextensie(filename, ".r3d")
|| BLI_testextensie(filename, ".mov")
|| BLI_testextensie(filename, ".movie")
|| BLI_testextensie(filename, ".mv")) {
@@ -379,6 +425,7 @@ int IMB_isanim(char *filename) {
} else { // no quicktime
if( BLI_testextensie(filename, ".avi")
|| BLI_testextensie(filename, ".dv")
+ || BLI_testextensie(filename, ".r3d")
|| BLI_testextensie(filename, ".mv")) {
type = imb_get_anim_type(filename);
}
diff --git a/source/blender/makesdna/DNA_ID.h b/source/blender/makesdna/DNA_ID.h
index 8db04b37581..ccf9becbce5 100644
--- a/source/blender/makesdna/DNA_ID.h
+++ b/source/blender/makesdna/DNA_ID.h
@@ -46,7 +46,7 @@ struct ID;
typedef struct IDPropertyData {
void *pointer;
ListBase group;
- int val, pad;
+ int val, val2; /*note, we actually fit a double into these two ints*/
} IDPropertyData;
typedef struct IDProperty {
@@ -77,6 +77,7 @@ typedef struct IDProperty {
/* the ID link property type hasn't been implemented yet, this will require
some cleanup of blenkernel, most likely.*/
#define IDP_ID 7
+#define IDP_DOUBLE 8
/* add any future new id property types here.*/
@@ -139,7 +140,7 @@ typedef struct PreviewImage {
*
**/
-#if defined(__sgi) || defined(__sparc) || defined(__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
+#if defined(__sgi) || defined(__sparc) || defined(__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__hppa__) || defined (__BIG_ENDIAN__)
/* big endian */
#define MAKE_ID2(c, d) ( (c)<<8 | (d) )
#define MOST_SIG_BYTE 0
diff --git a/source/blender/makesdna/DNA_action_types.h b/source/blender/makesdna/DNA_action_types.h
index db6a2bda53c..4a10ecf2368 100644
--- a/source/blender/makesdna/DNA_action_types.h
+++ b/source/blender/makesdna/DNA_action_types.h
@@ -32,11 +32,15 @@
#include "DNA_listBase.h"
#include "DNA_ID.h"
+#include "DNA_gpencil_types.h"
#include "DNA_view2d_types.h"
+#include "DNA_userdef_types.h"
struct SpaceLink;
struct Object;
+/* -------------- Poses ----------------- */
+
/* PoseChannel stores the results of Actions (ipos) and transform information
with respect to the restposition of Armature bones */
typedef struct bPoseChannel {
@@ -49,7 +53,7 @@ typedef struct bPoseChannel {
short ikflag; /* settings for IK bones */
short selectflag; /* copy of bone flag, so you can work with library armatures */
short protectflag; /* protect channels from being transformed */
- short customCol; /* index of custom color set to use (0=default - used for all old files) */
+ short agrp_index; /* index of action-group this bone belongs to (0 = default/no group) */
int pathlen; /* for drawing paths, the amount of frames */
int pathsf; /* for drawing paths, the start frame number */
@@ -90,17 +94,59 @@ typedef struct bPoseChannel {
*/
typedef struct bPose {
ListBase chanbase; /* list of pose channels */
+
short flag, proxy_layer; /* proxy layer: copy from armature, gets synced */
+
float ctime; /* local action time of this pose */
float stride_offset[3]; /* applied to object */
float cyclic_offset[3]; /* result of match and cycles, applied in where_is_pose() */
+
+
+ ListBase agroups; /* list of bActionGroups */
+
+ int active_group; /* index of active group (starts from 1) */
+ int pad;
} bPose;
+
+/* ------------- Action ---------------- */
+
+/* Action-Channel Group. These are stored as a list per-Action, and are only used to
+ * group that Action's Action-Channels when displayed in the Action Editor.
+ *
+ * Even though all Action-Channels live in a big list per Action, each group they are in also
+ * holds references to the achans within that list which belong to it. Care must be taken to
+ * ensure that action-groups never end up being the sole 'owner' of a channel.
+ *
+ *
+ * This is also exploited for bone-groups. Bone-Groups are stored per bPose, and are used
+ * primarily to colour bones in the 3d-view. There are other benefits too, but those are mostly related
+ * to Action-Groups.
+ */
+typedef struct bActionGroup {
+ struct bActionGroup *next, *prev;
+
+ ListBase channels; /* Note: this must not be touched by standard listbase functions */
+
+ int flag; /* settings for this action-group */
+ int customCol; /* index of custom color set to use when used for bones (0=default - used for all old files, -1=custom set) */
+ char name[32]; /* name of the group */
+
+ ThemeWireColor cs; /* color set to use when customCol == -1 */
+} bActionGroup;
+
/* Action Channels belong to Actions. They are linked with an IPO block, and can also own
* Constraint Channels in certain situations.
+ *
+ * Action-Channels can only belong to one group at a time, but they still live the Action's
+ * list of achans (to preserve backwards compatability, and also minimise the code
+ * that would need to be recoded). Grouped achans are stored at the start of the list, according
+ * to the position of the group in the list, and their position within the group.
*/
typedef struct bActionChannel {
struct bActionChannel *next, *prev;
+ bActionGroup *grp; /* Action Group this Action Channel belongs to */
+
struct Ipo *ipo; /* IPO block this action channel references */
ListBase constraintChannels; /* Constraint Channels (when Action Channel represents an Object or Bone) */
@@ -114,9 +160,18 @@ typedef struct bActionChannel {
*/
typedef struct bAction {
ID id;
+
ListBase chanbase; /* Action Channels in this Action */
+ ListBase groups; /* Action Groups in the Action */
+ ListBase markers; /* TimeMarkers local to this Action for labelling 'poses' */
+
+ int active_marker; /* Index of active-marker (first marker = 1) */
+ int pad;
} bAction;
+
+/* ------------- Action Editor --------------------- */
+
/* Action Editor Space. This is defined here instead of in DNA_space_types.h */
typedef struct SpaceAction {
struct SpaceLink *next, *prev;
@@ -129,12 +184,17 @@ typedef struct SpaceAction {
View2D v2d;
bAction *action; /* the currently active action */
- short flag, autosnap; /* flag: bitmapped settings; autosnap: automatic keyframe snapping mode */
- short pin, actnr, lock; /* pin: keep showing current action; actnr: used for finding chosen action from menu; lock: lock time to other windows */
+
+ char mode, autosnap; /* mode: editing context; autosnap: automatic keyframe snapping mode */
+ short flag, actnr; /* flag: bitmapped settings; */
+ short pin, lock; /* pin: keep showing current action; actnr: used for finding chosen action from menu; lock: lock time to other windows */
short actwidth; /* width of the left-hand side name panel (in pixels?) */
float timeslide; /* for Time-Slide transform mode drawing - current frame? */
} SpaceAction;
+
+/* -------------- Action Flags -------------- */
+
/* Action Channel flags */
typedef enum ACHAN_FLAG {
ACHAN_SELECTED = (1<<0),
@@ -147,18 +207,52 @@ typedef enum ACHAN_FLAG {
ACHAN_MOVED = (1<<31),
} ACHAN_FLAG;
+
+/* Action Group flags */
+typedef enum AGRP_FLAG {
+ AGRP_SELECTED = (1<<0),
+ AGRP_ACTIVE = (1<<1),
+ AGRP_PROTECTED = (1<<2),
+ AGRP_EXPANDED = (1<<3),
+
+ AGRP_TEMP = (1<<30),
+ AGRP_MOVED = (1<<31)
+} AGRP_FLAG;
+
+/* ------------ Action Editor Flags -------------- */
+
/* SpaceAction flag */
typedef enum SACTION_FLAG {
- /* during transform */
+ /* during transform (only set for TimeSlide) */
SACTION_MOVING = (1<<0),
/* show sliders (if relevant) */
SACTION_SLIDERS = (1<<1),
/* draw time in seconds instead of time in frames */
SACTION_DRAWTIME = (1<<2),
/* don't filter action channels according to visibility */
- SACTION_NOHIDE = (1<<3)
+ SACTION_NOHIDE = (1<<3),
+ /* don't kill overlapping keyframes after transform */
+ SACTION_NOTRANSKEYCULL = (1<<4),
+ /* don't include keyframes that are out of view */
+ SACTION_HORIZOPTIMISEON = (1<<5),
+ /* hack for moving pose-markers (temp flag) */
+ SACTION_POSEMARKERS_MOVE = (1<<6),
+ /* don't draw action channels using group colours (where applicable) */
+ SACTION_NODRAWGCOLORS = (1<<7)
} SACTION_FLAG;
+/* SpaceAction Mode Settings */
+typedef enum SACTCONT_MODES {
+ /* action (default) */
+ SACTCONT_ACTION = 0,
+ /* editing of shapekey's IPO block */
+ SACTCONT_SHAPEKEY,
+ /* editing of gpencil data */
+ SACTCONT_GPENCIL,
+ /* dopesheet (unimplemented... future idea?) */
+ SACTCONT_DOPESHEET
+} SACTCONTEXT_MODES;
+
/* SpaceAction AutoSnap Settings (also used by SpaceNLA) */
typedef enum SACTSNAP_MODES {
/* no auto-snap */
@@ -170,6 +264,9 @@ typedef enum SACTSNAP_MODES {
/* snap to nearest marker */
SACTSNAP_MARKER,
} SACTSNAP_MODES;
+
+
+/* --------- Pose Flags --------------- */
/* Pose->flag */
typedef enum POSE_FLAG {
@@ -178,7 +275,11 @@ typedef enum POSE_FLAG {
/* prevents any channel from getting overridden by anim from IPO */
POSE_LOCKED = (1<<1),
/* clears the POSE_LOCKED flag for the next time the pose is evaluated */
- POSE_DO_UNLOCK = (1<<2)
+ POSE_DO_UNLOCK = (1<<2),
+ /* pose has constraints which depend on time (used when depsgraph updates for a new frame) */
+ POSE_CONSTRAINTS_TIMEDEPEND = (1<<3),
+ /* recalculate bone paths */
+ POSE_RECALCPATHS = (1<<4),
} POSE_FLAG;
/* PoseChannel (transform) flags */
diff --git a/source/blender/makesdna/DNA_actuator_types.h b/source/blender/makesdna/DNA_actuator_types.h
index 53f167a99dc..43dada97d0e 100644
--- a/source/blender/makesdna/DNA_actuator_types.h
+++ b/source/blender/makesdna/DNA_actuator_types.h
@@ -35,6 +35,7 @@ struct Object;
struct Mesh;
struct Scene;
struct Group;
+struct Text;
/* ****************** ACTUATORS ********************* */
@@ -49,8 +50,10 @@ typedef struct bActionActuator {
short type, flag; /* Playback type */
int sta, end; /* Start & End frames */
char name[32]; /* For property-driven playback */
- int blendin; /* Number of frames of blending */
- short priority; /* Execution priority */
+ char frameProp[32]; /* Set this property to the actions current frame */
+ short blendin; /* Number of frames of blending */
+ short priority; /* Execution priority */
+ short end_reset; /* Ending the actuator (negative pulse) wont reset the the action to its starting frame */
short strideaxis; /* Displacement axis */
float stridelength; /* Displacement incurred by cycle */
} bActionActuator;
@@ -78,8 +81,10 @@ typedef struct bEditObjectActuator {
struct Mesh *me;
char name[32];
float linVelocity[3]; /* initial lin. velocity on creation */
- short localflag; /* flag for the lin. vel: apply locally */
- short pad;
+ float angVelocity[3]; /* initial ang. velocity on creation */
+ float pad;
+ short localflag; /* flag for the lin & ang. vel: apply locally */
+ short dyn_operation;
} bEditObjectActuator;
typedef struct bSceneActuator {
@@ -96,7 +101,8 @@ typedef struct bPropertyActuator {
} bPropertyActuator;
typedef struct bObjectActuator {
- int flag, type;
+ short flag, type, otype;
+ short damping;
float forceloc[3], forcerot[3];
float loc[3], rot[3];
float dloc[3], drot[3];
@@ -107,6 +113,7 @@ typedef struct bIpoActuator {
short flag, type;
int sta, end;
char name[32];
+ char frameProp[32]; /* Set this property to the actions current frame */
short pad1, cur, butsta, butend;
@@ -121,10 +128,13 @@ typedef struct bCameraActuator {
} bCameraActuator ;
typedef struct bConstraintActuator {
+ short type, mode;
short flag, damp;
- float slow;
+ short time, rotdamp;
+ int pad;
float minloc[3], maxloc[3];
float minrot[3], maxrot[3];
+ char matprop[32];
} bConstraintActuator;
typedef struct bGroupActuator {
@@ -184,10 +194,35 @@ typedef struct bGameActuator {
} bGameActuator;
typedef struct bVisibilityActuator {
- /** bit 0: Is this object visible? */
+ /** bit 0: Is this object visible?
+ ** bit 1: Apply recursively */
int flag;
} bVisibilityActuator;
+typedef struct bTwoDFilterActuator{
+ char pad[4];
+ /* Tells what type of 2D Filter */
+ short type;
+ /* (flag == 0) means 2D filter is activate and
+ (flag != 0) means 2D filter is inactive */
+ short flag;
+ int int_arg;
+ /* a float argument */
+ float float_arg;
+ struct Text *text;
+}bTwoDFilterActuator;
+
+typedef struct bParentActuator {
+ char pad[4];
+ int type;
+ struct Object *ob;
+} bParentActuator;
+
+typedef struct bStateActuator {
+ int type; /* 0=Set, 1=Add, 2=Rem, 3=Chg */
+ unsigned int mask; /* the bits to change */
+} bStateActuator;
+
typedef struct bActuator {
struct bActuator *next, *prev, *mynew;
short type;
@@ -220,19 +255,19 @@ typedef struct FreeCamera {
/* objectactuator->flag */
#define ACT_FORCE_LOCAL 1
#define ACT_TORQUE_LOCAL 2
+#define ACT_SERVO_LIMIT_X 2
#define ACT_DLOC_LOCAL 4
+#define ACT_SERVO_LIMIT_Y 4
#define ACT_DROT_LOCAL 8
+#define ACT_SERVO_LIMIT_Z 8
#define ACT_LIN_VEL_LOCAL 16
#define ACT_ANG_VEL_LOCAL 32
//#define ACT_ADD_LIN_VEL_LOCAL 64
#define ACT_ADD_LIN_VEL 64
-#define ACT_OBJECT_FORCE 0
-#define ACT_OBJECT_TORQUE 1
-#define ACT_OBJECT_DLOC 2
-#define ACT_OBJECT_DROT 3
-#define ACT_OBJECT_LINV 4
-#define ACT_OBJECT_ANGV 5
+/* objectactuator->type */
+#define ACT_OBJECT_NORMAL 0
+#define ACT_OBJECT_SERVO 1
/* actuator->type */
#define ACT_OBJECT 0
@@ -256,11 +291,18 @@ typedef struct FreeCamera {
#define ACT_CD 16
#define ACT_GAME 17
#define ACT_VISIBILITY 18
+#define ACT_2DFILTER 19
+#define ACT_PARENT 20
+#define ACT_SHAPEACTION 21
+#define ACT_STATE 22
/* actuator flag */
#define ACT_SHOW 1
#define ACT_DEL 2
#define ACT_NEW 4
+#define ACT_LINKED 8
+#define ACT_VISIBLE 16
+#define ACT_PIN 32
/* link codes */
#define LINK_SENSOR 0
@@ -301,8 +343,9 @@ typedef struct FreeCamera {
/* ipoactuator->flag */
#define ACT_IPOFORCE (1 << 0)
#define ACT_IPOEND (1 << 1)
-#define ACT_IPOFORCE_LOCAL (1 << 2)
-#define ACT_IPOCHILD (1 << 4)
+#define ACT_IPOLOCAL (1 << 2)
+#define ACT_IPOCHILD (1 << 4)
+#define ACT_IPOADD (1 << 5)
/* ipoactuator->flag for k2k */
#define ACT_K2K_PREV 1
@@ -322,14 +365,38 @@ typedef struct FreeCamera {
#define ACT_CONST_ROTX 8
#define ACT_CONST_ROTY 16
#define ACT_CONST_ROTZ 32
+#define ACT_CONST_NORMAL 64
+#define ACT_CONST_MATERIAL 128
+#define ACT_CONST_PERMANENT 256
+#define ACT_CONST_DISTANCE 512
+#define ACT_CONST_LOCAL 1024
+#define ACT_CONST_DOROTFH 2048
+
+/* constraint mode */
+#define ACT_CONST_DIRPX 1
+#define ACT_CONST_DIRPY 2
+#define ACT_CONST_DIRPZ 4
+#define ACT_CONST_DIRNX 8
+#define ACT_CONST_DIRNY 16
+#define ACT_CONST_DIRNZ 32
+
+/* constraint type */
+#define ACT_CONST_TYPE_LOC 0
+#define ACT_CONST_TYPE_DIST 1
+#define ACT_CONST_TYPE_ORI 2
+#define ACT_CONST_TYPE_FH 3
/* editObjectActuator->type */
#define ACT_EDOB_ADD_OBJECT 0
#define ACT_EDOB_END_OBJECT 1
-#define ACT_EDOB_REPLACE_MESH 2
+#define ACT_EDOB_REPLACE_MESH 2
#define ACT_EDOB_TRACK_TO 3
-#define ACT_EDOB_MAKE_CHILD 4
-#define ACT_EDOB_END_CHILD 5
+#define ACT_EDOB_DYNAMICS 4
+
+/* editObjectActuator->localflag */
+#define ACT_EDOB_LOCAL_LINV 2
+#define ACT_EDOB_LOCAL_ANGV 4
+
/* editObjectActuator->flag */
#define ACT_TRACK_3D 1
@@ -383,10 +450,35 @@ typedef struct FreeCamera {
#define ACT_GAME_START 1
#define ACT_GAME_RESTART 2
#define ACT_GAME_QUIT 3
+#define ACT_GAME_SAVECFG 4
+#define ACT_GAME_LOADCFG 5
/* visibilityact->flag */
/* Set means the object will become invisible */
#define ACT_VISIBILITY_INVISIBLE (1 << 0)
-
+#define ACT_VISIBILITY_RECURSIVE (1 << 1)
+
+/* twodfilter->type */
+#define ACT_2DFILTER_ENABLED -2
+#define ACT_2DFILTER_DISABLED -1
+#define ACT_2DFILTER_NOFILTER 0
+#define ACT_2DFILTER_MOTIONBLUR 1
+#define ACT_2DFILTER_BLUR 2
+#define ACT_2DFILTER_SHARPEN 3
+#define ACT_2DFILTER_DILATION 4
+#define ACT_2DFILTER_EROSION 5
+#define ACT_2DFILTER_LAPLACIAN 6
+#define ACT_2DFILTER_SOBEL 7
+#define ACT_2DFILTER_PREWITT 8
+#define ACT_2DFILTER_GRAYSCALE 9
+#define ACT_2DFILTER_SEPIA 10
+#define ACT_2DFILTER_INVERT 11
+#define ACT_2DFILTER_CUSTOMFILTER 12
+#define ACT_2DFILTER_NUMBER_OF_FILTERS 13
+
+/* parentactuator->type */
+#define ACT_PARENT_SET 0
+#define ACT_PARENT_REMOVE 1
#endif
+
diff --git a/source/blender/makesdna/DNA_armature_types.h b/source/blender/makesdna/DNA_armature_types.h
index 21f88c71a6e..93cb9f59860 100644
--- a/source/blender/makesdna/DNA_armature_types.h
+++ b/source/blender/makesdna/DNA_armature_types.h
@@ -97,7 +97,7 @@ typedef enum eArmature_Flag {
ARM_MIRROR_EDIT = (1<<8),
ARM_AUTO_IK = (1<<9),
ARM_NO_CUSTOM = (1<<10), /* made option negative, for backwards compat */
- ARM_COL_CUSTOM = (1<<11), /* draw custom colours - not yet used... */
+ ARM_COL_CUSTOM = (1<<11), /* draw custom colours */
ARM_GHOST_ONLYSEL = (1<<12) /* when ghosting, only show selected bones (this should belong to ghostflag instead) */
} eArmature_Flag;
@@ -140,7 +140,7 @@ typedef enum eBone_Flag {
BONE_ROOTSEL = (1<<1),
BONE_TIPSEL = (1<<2),
BONE_TRANSFORM = (1<<3), /* Used instead of BONE_SELECTED during transform */
- BONE_CONNECTED = (1<<4),
+ BONE_CONNECTED = (1<<4), /* when bone has a parent, connect head of bone to parent's tail*/
/* 32 used to be quatrot, was always set in files, do not reuse unless you clear it always */
BONE_HIDDEN_P = (1<<6), /* hidden Bones when drawing PoseChannels */
BONE_DONE = (1<<7), /* For detecting cyclic dependancies */
@@ -148,11 +148,15 @@ typedef enum eBone_Flag {
BONE_HINGE = (1<<9), /* No parent rotation or scale */
BONE_HIDDEN_A = (1<<10), /* hidden Bones when drawing Armature Editmode */
BONE_MULT_VG_ENV = (1<<11), /* multiplies vgroup with envelope */
- BONE_NO_DEFORM = (1<<12),
+ BONE_NO_DEFORM = (1<<12), /* bone doesn't deform geometry */
BONE_UNKEYED = (1<<13), /* set to prevent destruction of its unkeyframed pose (after transform) */
BONE_HINGE_CHILD_TRANSFORM = (1<<14), /* set to prevent hinge child bones from influencing the transform center */
BONE_NO_SCALE = (1<<15), /* No parent scale */
- BONE_HIDDEN_PG = (1<<16) /* hidden bone when drawing PoseChannels (for ghost drawing) */
+ BONE_HIDDEN_PG = (1<<16), /* hidden bone when drawing PoseChannels (for ghost drawing) */
+ BONE_DRAWWIRE = (1<<17), /* bone should be drawn as OB_WIRE, regardless of draw-types of view+armature */
+ BONE_NO_CYCLICOFFSET = (1<<18), /* when no parent, bone will not get cyclic offset */
+ BONE_EDITMODE_LOCKED = (1<<19), /* bone transforms are locked in EditMode */
+ BONE_TRANSFORM_CHILD = (1<<20), /* Indicates that a parent is also being transformed */
} eBone_Flag;
#endif
diff --git a/source/blender/makesdna/DNA_brush_types.h b/source/blender/makesdna/DNA_brush_types.h
index 1c272105067..c7196763358 100644
--- a/source/blender/makesdna/DNA_brush_types.h
+++ b/source/blender/makesdna/DNA_brush_types.h
@@ -33,7 +33,7 @@
#include "DNA_ID.h"
#ifndef MAX_MTEX
-#define MAX_MTEX 10
+#define MAX_MTEX 18
#endif
struct MTex;
@@ -58,7 +58,7 @@ typedef struct Brush {
float alpha; /* opacity */
short texact, pad;
- struct MTex *mtex[10];
+ struct MTex *mtex[18]; /* MAX_MTEX */
struct BrushClone clone;
} Brush;
diff --git a/source/blender/makesdna/DNA_cloth_types.h b/source/blender/makesdna/DNA_cloth_types.h
new file mode 100644
index 00000000000..c99dc44cd5e
--- /dev/null
+++ b/source/blender/makesdna/DNA_cloth_types.h
@@ -0,0 +1,95 @@
+/**
+* $Id: DNA_cloth_types.h,v 1.1 2007/08/01 02:28:34 daniel Exp $
+*
+* ***** BEGIN GPL LICENSE BLOCK *****
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 2
+* of the License, or (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software Foundation,
+* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*
+* The Original Code is Copyright (C) 2006 by NaN Holding BV.
+* All rights reserved.
+*
+* The Original Code is: all of this file.
+*
+* Contributor(s): Daniel (Genscher)
+*
+* ***** END GPL LICENSE BLOCK *****
+*/
+#ifndef DNA_CLOTH_TYPES_H
+#define DNA_CLOTH_TYPES_H
+
+/**
+* This struct contains all the global data required to run a simulation.
+* At the time of this writing, this structure contains data appropriate
+* to run a simulation as described in Deformation Constraints in a
+* Mass-Spring Model to Describe Rigid Cloth Behavior by Xavier Provot.
+*
+* I've tried to keep similar, if not exact names for the variables as
+* are presented in the paper. Where I've changed the concept slightly,
+* as in stepsPerFrame comapred to the time step in the paper, I've used
+* variables with different names to minimize confusion.
+**/
+
+typedef struct ClothSimSettings
+{
+ struct LinkNode *cache; /* UNUSED atm */
+ float mingoal; /* see SB */
+ float Cdis; /* Mechanical damping of springs. */
+ float Cvi; /* Viscous/fluid damping. */
+ float gravity [3]; /* Gravity/external force vector. */
+ float dt; /* This is the duration of our time step, computed. */
+ float mass; /* The mass of the entire cloth. */
+ float structural; /* Structural spring stiffness. */
+ float shear; /* Shear spring stiffness. */
+ float bending; /* Flexion spring stiffness. */
+ float max_bend; /* max bending scaling value, min is "bending" */
+ float max_struct; /* max structural scaling value, min is "structural" */
+ float max_shear; /* max shear scaling value, UNUSED */
+ float avg_spring_len; /* used for normalized springs */
+ float timescale; /* parameter how fast cloth runs */
+ float maxgoal; /* see SB */
+ float eff_force_scale;/* Scaling of effector forces (see softbody_calc_forces).*/
+ float eff_wind_scale; /* Scaling of effector wind (see softbody_calc_forces). */
+ float sim_time_old;
+ float defgoal;
+ float goalspring;
+ float goalfrict;
+ int stepsPerFrame; /* Number of time steps per frame. */
+ int flags; /* flags, see CSIMSETT_FLAGS enum above. */
+ int preroll; /* How many frames of simulation to do before we start. */
+ int maxspringlen; /* in percent!; if tearing enabled, a spring will get cut */
+ short solver_type; /* which solver should be used? txold */
+ short vgroup_bend; /* vertex group for scaling bending stiffness */
+ short vgroup_mass; /* optional vertexgroup name for assigning weight.*/
+ short vgroup_struct; /* vertex group for scaling structural stiffness */
+ short presets; /* used for presets on GUI */
+ short pad;
+ int pad2;
+} ClothSimSettings;
+
+
+typedef struct ClothCollSettings
+{
+ struct LinkNode *collision_list; /* e.g. pointer to temp memory for collisions */
+ float epsilon; /* min distance for collisions. */
+ float self_friction; /* Fiction/damping with self contact. */
+ float friction; /* Friction/damping applied on contact with other object.*/
+ float selfepsilon; /* for selfcollision */
+ int flags; /* collision flags defined in BKE_cloth.h */
+ short self_loop_count; /* How many iterations for the selfcollision loop */
+ short loop_count; /* How many iterations for the collision loop. */
+} ClothCollSettings;
+
+
+#endif
diff --git a/source/blender/makesdna/DNA_color_types.h b/source/blender/makesdna/DNA_color_types.h
index a4224976f5f..3caa74c9a72 100644
--- a/source/blender/makesdna/DNA_color_types.h
+++ b/source/blender/makesdna/DNA_color_types.h
@@ -69,13 +69,16 @@ typedef struct CurveMapping {
CurveMap cm[4]; /* max 4 builtin curves per mapping struct now */
float black[3], white[3]; /* black/white point (black[0] abused for current frame) */
- float bwmul[3], padf; /* black/white point multiply value, for speed */
+ float bwmul[3]; /* black/white point multiply value, for speed */
+
+ float sample[3]; /* sample values, if flag set it draws line and intersection */
} CurveMapping;
/* cumapping->flag */
#define CUMA_DO_CLIP 1
#define CUMA_PREMULLED 2
#define CUMA_DRAW_CFRA 4
+#define CUMA_DRAW_SAMPLE 8
#endif
diff --git a/source/blender/makesdna/DNA_constraint_types.h b/source/blender/makesdna/DNA_constraint_types.h
index 1a82ec07f00..fe19cf60f12 100644
--- a/source/blender/makesdna/DNA_constraint_types.h
+++ b/source/blender/makesdna/DNA_constraint_types.h
@@ -304,6 +304,19 @@ typedef struct bSizeLimitConstraint {
short flag2;
} bSizeLimitConstraint;
+/* Limit Distance Constraint */
+typedef struct bDistLimitConstraint {
+ Object *tar;
+ char subtarget[32];
+
+ float dist; /* distance (radius of clamping sphere) from target */
+ float soft; /* distance from clamping-sphere to start applying 'fade' */
+
+ short flag; /* settings */
+ short mode; /* how to limit in relation to clamping sphere */
+ int pad;
+} bDistLimitConstraint;
+
/* ------------------------------------------ */
/* bConstraint->type
@@ -325,13 +338,14 @@ typedef enum B_CONSTAINT_TYPES {
CONSTRAINT_TYPE_PYTHON, /* Unimplemented no longer :) - Aligorith. Scripts */
CONSTRAINT_TYPE_ACTION,
CONSTRAINT_TYPE_LOCKTRACK, /* New Tracking constraint that locks an axis in place - theeth */
- CONSTRAINT_TYPE_DISTANCELIMIT, /* was never properly coded - removed! */
+ CONSTRAINT_TYPE_DISTLIMIT, /* limit distance */
CONSTRAINT_TYPE_STRETCHTO, /* claiming this to be mine :) is in tuhopuu bjornmose */
CONSTRAINT_TYPE_MINMAX, /* floor constraint */
CONSTRAINT_TYPE_RIGIDBODYJOINT, /* rigidbody constraint */
CONSTRAINT_TYPE_CLAMPTO, /* clampto constraint */
CONSTRAINT_TYPE_TRANSFORM, /* transformation (loc/rot/size -> loc/rot/size) constraint */
+
/* NOTE: everytime a new constraint is added, update this */
NUM_CONSTRAINT_TYPES= CONSTRAINT_TYPE_TRANSFORM
} B_CONSTRAINT_TYPES;
@@ -349,7 +363,9 @@ typedef enum B_CONSTRAINT_FLAG {
/* to indicate that the owner's space should only be changed into ownspace, but not out of it */
CONSTRAINT_SPACEONCE = (1<<6),
/* influence ipo is on constraint itself, not in action channel */
- CONSTRAINT_OWN_IPO = (1<<7)
+ CONSTRAINT_OWN_IPO = (1<<7),
+ /* indicates that constraint was added locally (i.e. didn't come from the proxy-lib) */
+ CONSTRAINT_PROXY_LOCAL = (1<<8)
} B_CONSTRAINT_FLAG;
/* bConstraint->ownspace/tarspace */
@@ -359,11 +375,13 @@ typedef enum B_CONSTRAINT_SPACETYPES {
/* for objects (relative to parent/without parent influence),
* for bones (along normals of bone, without parent/restpositions)
*/
- CONSTRAINT_SPACE_LOCAL,
+ CONSTRAINT_SPACE_LOCAL, /* = 1 */
/* for posechannels - pose space */
- CONSTRAINT_SPACE_POSE,
- /* for posechannels - local with parent */
- CONSTRAINT_SPACE_PARLOCAL,
+ CONSTRAINT_SPACE_POSE, /* = 2 */
+ /* for posechannels - local with parent */
+ CONSTRAINT_SPACE_PARLOCAL, /* = 3 */
+ /* for files from between 2.43-2.46 (should have been parlocal) */
+ CONSTRAINT_SPACE_INVALID, /* = 4. do not exchange for anything! */
} B_CONSTRAINT_SPACETYPES;
/* bConstraintChannel.flag */
@@ -445,7 +463,9 @@ typedef enum B_CONSTRAINTCHANNEL_FLAG {
/* bKinematicConstraint->flag */
#define CONSTRAINT_IK_TIP 1
#define CONSTRAINT_IK_ROT 2
+ /* targetless */
#define CONSTRAINT_IK_AUTO 4
+ /* autoik */
#define CONSTRAINT_IK_TEMP 8
#define CONSTRAINT_IK_STRETCH 16
#define CONSTRAINT_IK_POS 32
@@ -473,6 +493,15 @@ typedef enum B_CONSTRAINTCHANNEL_FLAG {
#define LIMIT_NOPARENT 0x01
/* for all Limit constraints - allow to be used during transform? */
#define LIMIT_TRANSFORM 0x02
+
+/* distance limit constraint */
+ /* bDistLimitConstraint->flag */
+#define LIMITDIST_USESOFT (1<<0)
+
+ /* bDistLimitConstraint->mode */
+#define LIMITDIST_INSIDE 0
+#define LIMITDIST_OUTSIDE 1
+#define LIMITDIST_ONSURFACE 2
/* python constraint -> flag */
#define PYCON_USETARGETS 0x01
@@ -491,6 +520,7 @@ typedef enum B_CONSTRAINTCHANNEL_FLAG {
/* Rigid-Body Constraint */
#define CONSTRAINT_DRAW_PIVOT 0x40
+#define CONSTRAINT_DISABLE_LINKED_COLLISION 0x80
/* important: these defines need to match up with PHY_DynamicTypes headerfile */
#define CONSTRAINT_RB_BALL 1
diff --git a/source/blender/makesdna/DNA_controller_types.h b/source/blender/makesdna/DNA_controller_types.h
index 95c9b0d0cf7..376f95b0145 100644
--- a/source/blender/makesdna/DNA_controller_types.h
+++ b/source/blender/makesdna/DNA_controller_types.h
@@ -57,7 +57,7 @@ typedef struct bController {
struct bSensor **slinks;
short val, valo;
- int pad5;
+ unsigned int state_mask;
} bController;
@@ -66,11 +66,16 @@ typedef struct bController {
#define CONT_LOGIC_OR 1
#define CONT_EXPRESSION 2
#define CONT_PYTHON 3
+#define CONT_LOGIC_NAND 4
+#define CONT_LOGIC_NOR 5
+#define CONT_LOGIC_XOR 6
+#define CONT_LOGIC_XNOR 7
/* controller->flag */
#define CONT_SHOW 1
#define CONT_DEL 2
#define CONT_NEW 4
+#define CONT_MASK 8
#endif
diff --git a/source/blender/makesdna/DNA_curve_types.h b/source/blender/makesdna/DNA_curve_types.h
index a4fb8dc1150..f809cac037d 100644
--- a/source/blender/makesdna/DNA_curve_types.h
+++ b/source/blender/makesdna/DNA_curve_types.h
@@ -68,7 +68,7 @@ typedef struct BevList {
#
#
typedef struct BevPoint {
- float x, y, z, alfa, sina, cosa, mat[3][3];
+ float x, y, z, alfa, radius, sina, cosa, mat[3][3];
short f1, f2;
} BevPoint;
@@ -115,7 +115,7 @@ typedef struct Nurb {
BezTriple *bezt;
short tilt_interp; /* KEY_LINEAR, KEY_CARDINAL, KEY_BSPLINE */
- short pad;
+ short radius_interp;
int charidx;
} Nurb;
@@ -187,37 +187,6 @@ typedef struct Curve {
struct CharInfo curinfo;
} Curve;
-typedef struct IpoDriver {
- struct Object *ob;
- short blocktype, adrcode, type, flag;
- char name[128]; /* bone or constraint(?), or python expression here */
-} IpoDriver;
-
-/* temp? we store more bone names in 1 driver... */
-#define DRIVER_NAME_OFFS 32
-
-typedef struct IpoCurve {
- struct IpoCurve *next, *prev;
-
- struct BPoint *bp; /* are these even used anywhere? */
- struct BezTriple *bezt; /* array of BezTriples (sizeof(BezTriple)*totvert. i.e. keyframes */
-
- rctf maxrct, totrct; /* bounding boxes */
-
- short blocktype, adrcode, vartype; /* blocktype= ipo-blocktype; adrcode= type of ipo-curve; vartype= 'format' of data */
- short totvert; /* total number of BezTriples (i.e. keyframes) on curve */
- short ipo, extrap; /* interpolation and extrapolation modes */
- short flag, rt; /* flag= settings; rt= ??? */
- float ymin, ymax; /* minimum/maximum y-extents for curve */
- unsigned int bitmask; /* ??? */
-
- float slide_min, slide_max; /* minimum/maximum values for sliders (in action editor) */
- float curval; /* value of ipo-curve for current frame */
-
- IpoDriver *driver; /* pointer to ipo-driver for this curve */
-
-} IpoCurve;
-
/* **************** CURVE ********************* */
/* texflag */
@@ -273,15 +242,5 @@ typedef struct IpoCurve {
#define CU_UNDERLINE 4
#define CU_WRAP 8 /* wordwrap occured here */
-/* *************** driver ****************** */
-
-/* driver->type */
-#define IPO_DRIVER_TYPE_NORMAL 0
-#define IPO_DRIVER_TYPE_PYTHON 1
-
-/* driver->flag */
-/* invalid flag: currently only used for buggy pydriver expressions: */
-#define IPO_DRIVER_FLAG_INVALID 1
-
#endif
diff --git a/source/blender/makesdna/DNA_customdata_types.h b/source/blender/makesdna/DNA_customdata_types.h
index 73a39abac55..6c098e220bb 100644
--- a/source/blender/makesdna/DNA_customdata_types.h
+++ b/source/blender/makesdna/DNA_customdata_types.h
@@ -26,6 +26,7 @@
*
* ***** END GPL LICENSE BLOCK *****
*/
+
#ifndef DNA_CUSTOMDATA_TYPES_H
#define DNA_CUSTOMDATA_TYPES_H
@@ -48,6 +49,7 @@ typedef struct CustomData {
CustomDataLayer *layers; /* CustomDataLayers, ordered by type */
int totlayer, maxlayer; /* number of layers, size of layers array */
int totsize, pad; /* in editmode, total size of all data layers */
+ void *pool; /* for Bmesh: Memory pool for allocation of blocks*/
} CustomData;
/* CustomData.type */
@@ -66,7 +68,11 @@ typedef struct CustomData {
#define CD_PROP_STR 12
#define CD_ORIGSPACE 13 /* for modifier stack face location mapping */
#define CD_ORCO 14
-#define CD_NUMTYPES 15
+#define CD_MTEXPOLY 15
+#define CD_MLOOPUV 16
+#define CD_MLOOPCOL 17
+#define CD_TANGENT 18
+#define CD_NUMTYPES 19
/* Bits for CustomDataMask */
#define CD_MASK_MVERT (1 << CD_MVERT)
@@ -84,6 +90,10 @@ typedef struct CustomData {
#define CD_MASK_PROP_STR (1 << CD_PROP_STR)
#define CD_MASK_ORIGSPACE (1 << CD_ORIGSPACE)
#define CD_MASK_ORCO (1 << CD_ORCO)
+#define CD_MASK_MTEXPOLY (1 << CD_MTEXPOLY)
+#define CD_MASK_MLOOPUV (1 << CD_MLOOPUV)
+#define CD_MASK_MLOOPCOL (1 << CD_MLOOPCOL)
+#define CD_MASK_TANGENT (1 << CD_TANGENT)
/* CustomData.flag */
diff --git a/source/blender/makesdna/DNA_gpencil_types.h b/source/blender/makesdna/DNA_gpencil_types.h
new file mode 100644
index 00000000000..70f469b2bb8
--- /dev/null
+++ b/source/blender/makesdna/DNA_gpencil_types.h
@@ -0,0 +1,145 @@
+/**
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2008, Blender Foundation.
+ * This is a new part of Blender
+ *
+ * Contributor(s): Joshua Leung
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef DNA_GPENCIL_TYPES_H
+#define DNA_GPENCIL_TYPES_H
+
+#include "DNA_listBase.h"
+#include "DNA_ID.h"
+
+/* Grease-Pencil Annotations - 'Stroke Point'
+ * -> Coordinates may either be 2d or 3d depending on settings at the time
+ * -> Coordinates of point on stroke, in proportions of window size
+ * (i.e. n/1000). This assumes that the bottom-left corner is (0,0)
+ */
+typedef struct bGPDspoint {
+ float x, y, z; /* co-ordinates of point (usually 2d, but can be 3d as well) */
+ float pressure; /* pressure of input device (from 0 to 1) at this point */
+} bGPDspoint;
+
+/* Grease-Pencil Annotations - 'Stroke'
+ * -> A stroke represents a (simplified version) of the curve
+ * drawn by the user in one 'mousedown'->'mouseup' operation
+ */
+typedef struct bGPDstroke {
+ struct bGPDstroke *next, *prev;
+
+ bGPDspoint *points; /* array of data-points for stroke */
+ int totpoints; /* number of data-points in array */
+
+ short thickness; /* thickness of stroke (currently not used) */
+ short flag; /* various settings about this stroke */
+} bGPDstroke;
+
+/* bGPDstroke->flag */
+ /* stroke is in 3d-space */
+#define GP_STROKE_3DSPACE (1<<0)
+ /* stroke is in 2d-space */
+#define GP_STROKE_2DSPACE (1<<1)
+ /* stroke is in 2d-space (but with special 'image' scaling) */
+#define GP_STROKE_2DIMAGE (1<<2)
+ /* only for use with stroke-buffer (while drawing eraser) */
+#define GP_STROKE_ERASER (1<<15)
+
+
+/* Grease-Pencil Annotations - 'Frame'
+ * -> Acts as storage for the 'image' formed by strokes
+ */
+typedef struct bGPDframe {
+ struct bGPDframe *next, *prev;
+
+ ListBase strokes; /* list of the simplified 'strokes' that make up the frame's data */
+
+ int framenum; /* frame number of this frame */
+ int flag; /* temp settings */
+} bGPDframe;
+
+/* bGPDframe->flag */
+ /* frame is being painted on */
+#define GP_FRAME_PAINT (1<<0)
+ /* for editing in Action Editor */
+#define GP_FRAME_SELECT (1<<1)
+
+
+/* Grease-Pencil Annotations - 'Layer' */
+typedef struct bGPDlayer {
+ struct bGPDlayer *next, *prev;
+
+ ListBase frames; /* list of annotations to display for frames (bGPDframe list) */
+ bGPDframe *actframe; /* active frame (should be the frame that is currently being displayed) */
+
+ int flag; /* settings for layer */
+ short thickness; /* current thickness to apply to strokes */
+ short gstep; /* max number of frames between active and ghost to show (0=only those on either side) */
+
+ float color[4]; /* color that should be used to draw all the strokes in this layer */
+
+ char info[128]; /* optional reference info about this layer (i.e. "director's comments, 12/3") */
+} bGPDlayer;
+
+/* bGPDlayer->flag */
+ /* don't display layer */
+#define GP_LAYER_HIDE (1<<0)
+ /* protected from further editing */
+#define GP_LAYER_LOCKED (1<<1)
+ /* layer is 'active' layer being edited */
+#define GP_LAYER_ACTIVE (1<<2)
+ /* draw points of stroke for debugging purposes */
+#define GP_LAYER_DRAWDEBUG (1<<3)
+ /* do onionskinning */
+#define GP_LAYER_ONIONSKIN (1<<4)
+ /* for editing in Action Editor */
+#define GP_LAYER_SELECT (1<<5)
+
+
+/* Grease-Pencil Annotations - 'DataBlock' */
+typedef struct bGPdata {
+ /* saved Grease-Pencil data */
+ ListBase layers; /* bGPDlayers */
+ int flag; /* settings for this datablock */
+
+ /* not-saved stroke buffer data (only used during paint-session)
+ * - buffer must be initialised before use, but freed after
+ * whole paint operation is over
+ */
+ short sbuffer_size; /* number of elements currently in cache */
+ short sbuffer_sflag; /* flags for stroke that cache represents */
+ void *sbuffer; /* stroke buffer (can hold GP_STROKE_BUFFER_MAX) */
+} bGPdata;
+
+/* bGPdata->flag */
+ /* don't allow painting to occur at all */
+#define GP_DATA_LMBPLOCK (1<<0)
+ /* show debugging info in viewport (i.e. status print) */
+#define GP_DATA_DISPINFO (1<<1)
+ /* in Action Editor, show as expanded channel */
+#define GP_DATA_EXPAND (1<<2)
+ /* is the block overriding all clicks? */
+#define GP_DATA_EDITPAINT (1<<3)
+ /* new strokes are added in viewport space */
+#define GP_DATA_VIEWALIGN (1<<4)
+
+#endif /* DNA_GPENCIL_TYPES_H */
diff --git a/source/blender/makesdna/DNA_group_types.h b/source/blender/makesdna/DNA_group_types.h
index 1bb18ca2ca2..0987050261d 100644
--- a/source/blender/makesdna/DNA_group_types.h
+++ b/source/blender/makesdna/DNA_group_types.h
@@ -54,7 +54,7 @@ typedef struct Group {
* the objects that show in the group can change depending
* on the last used scene */
unsigned int layer;
- int pad;
+ float dupli_ofs[3];
} Group;
diff --git a/source/blender/makesdna/DNA_image_types.h b/source/blender/makesdna/DNA_image_types.h
index b1e632661e8..e1d79f0f875 100644
--- a/source/blender/makesdna/DNA_image_types.h
+++ b/source/blender/makesdna/DNA_image_types.h
@@ -37,6 +37,7 @@ struct PackedFile;
struct anim;
struct ImBuf;
struct RenderResult;
+struct GPUTexture;
/* ImageUser is in Texture, in Nodes, Background Image, Image Window, .... */
@@ -55,13 +56,15 @@ typedef struct ImageUser {
/* iuser->flag */
#define IMA_ANIM_ALWAYS 1
#define IMA_ANIM_REFRESHED 2
+/* #define IMA_DO_PREMUL 4 */
typedef struct Image {
ID id;
char name[240]; /* file path */
- ListBase ibufs; /* not written in file */
+ ListBase ibufs; /* not written in file */
+ struct GPUTexture *gputexture; /* not written in file */
/* sources from: */
struct anim *anim;
@@ -101,11 +104,12 @@ typedef struct Image {
/* flag */
#define IMA_FIELDS 1
#define IMA_STD_FIELD 2
+#define IMA_DO_PREMUL 4
#define IMA_REFLECT 16
#define IMA_NOCOLLECT 32
#define IMA_ANTIALI 64
-#define IMA_DO_PREMUL 128
+#define IMA_OLD_PREMUL 128
/* tpageflag */
#define IMA_TILES 1
diff --git a/source/blender/makesdna/DNA_ipo_types.h b/source/blender/makesdna/DNA_ipo_types.h
index 3954a500dc7..432399e3581 100644
--- a/source/blender/makesdna/DNA_ipo_types.h
+++ b/source/blender/makesdna/DNA_ipo_types.h
@@ -24,7 +24,7 @@
*
* The Original Code is: all of this file.
*
- * Contributor(s): none yet.
+ * Contributor(s): Joshua Leung
*
* ***** END GPL LICENSE BLOCK *****
*/
@@ -32,10 +32,54 @@
#define DNA_IPO_TYPES_H
#include "DNA_listBase.h"
+#include "DNA_curve_types.h"
#include "DNA_vec_types.h"
#include "DNA_ID.h"
+/* -------------------------- Type Defines --------------------------- */
+
+/* sometimes used - mainly for GE/Ketsji */
+typedef short IPO_Channel;
+
+
+/* --- IPO Curve Driver --- */
+
+/* IPO Curve Driver */
+typedef struct IpoDriver {
+ struct Object *ob; /* target/driver ob */
+ short blocktype, adrcode; /* sub-channel to use */
+
+ short type, flag; /* driver settings */
+ char name[128]; /* bone, or python expression here */
+} IpoDriver;
+
+/* --- IPO Curve --- */
+
+/* IPO Curve */
+typedef struct IpoCurve {
+ struct IpoCurve *next, *prev;
+
+ struct BPoint *bp; /* array of BPoints (sizeof(BPoint)*totvert) - i.e. baked/imported data */
+ struct BezTriple *bezt; /* array of BezTriples (sizeof(BezTriple)*totvert) - i.e. user-editable keyframes */
+
+ rctf maxrct, totrct; /* bounding boxes */
+
+ short blocktype, adrcode, vartype; /* blocktype= ipo-blocktype; adrcode= type of ipo-curve; vartype= 'format' of data */
+ short totvert; /* total number of BezTriples (i.e. keyframes) on curve */
+ short ipo, extrap; /* interpolation and extrapolation modes */
+ short flag, rt; /* flag= settings; rt= ??? */
+ float ymin, ymax; /* minimum/maximum y-extents for curve */
+ unsigned int bitmask; /* ??? */
+
+ float slide_min, slide_max; /* minimum/maximum values for sliders (in action editor) */
+ float curval; /* value of ipo-curve for current frame */
+
+ IpoDriver *driver; /* pointer to ipo-driver for this curve */
+} IpoCurve;
+
+/* --- ID-Datablock --- */
+
/* IPO Data-Block */
typedef struct Ipo {
ID id;
@@ -47,13 +91,9 @@ typedef struct Ipo {
short muteipo, pad; /* muteipo: either 0 or 1 (whether ipo block is muted) */
} Ipo;
-/* NOTE: IpoCurve struct is defined in DNA_curve_types.h, not in here... */
-
-/* sometimes used */
-typedef short IPO_Channel;
+/* ----------- adrcodes (for matching ipo-curves to data) ------------- */
/* defines: are these duped or new? */
-
#define IPOBUTY 17
#define TOB_IPO 1
@@ -64,7 +104,7 @@ typedef short IPO_Channel;
#define IPO_DISPBITS 2
#define IPO_DISPTIME 3
-/* ******************** */
+/* ********** Object (ID_OB) ********** */
#define OB_TOTIPO 30
#define OB_TOTNAM 30
@@ -110,7 +150,7 @@ typedef short IPO_Channel;
#define OB_ROT_DIFF 100
-/* ******************** */
+/* ********** Material (ID_MA) ********** */
#define MA_TOTIPO 40
#define MA_TOTNAM 26
@@ -142,16 +182,26 @@ typedef short IPO_Channel;
#define MA_FRESTRAI 25
#define MA_ADD 26
-#define MA_MAP1 0x20
-#define MA_MAP2 0x40
-#define MA_MAP3 0x80
-#define MA_MAP4 0x100
-#define MA_MAP5 0x200
-#define MA_MAP6 0x400
-#define MA_MAP7 0x800
-#define MA_MAP8 0x1000
-#define MA_MAP9 0x2000
-#define MA_MAP10 0x4000
+#define MA_MAP1 (1<<5)
+#define MA_MAP2 (1<<6)
+#define MA_MAP3 (1<<7)
+#define MA_MAP4 (1<<8)
+#define MA_MAP5 (1<<9)
+#define MA_MAP6 (1<<10)
+#define MA_MAP7 (1<<11)
+#define MA_MAP8 (1<<12)
+#define MA_MAP9 (1<<13)
+#define MA_MAP10 (1<<14)
+#define MA_MAP11 (1<<15)
+#define MA_MAP12 (1<<16)
+#define MA_MAP13 (1<<17)
+#define MA_MAP14 (1<<18)
+#define MA_MAP15 (1<<19)
+#define MA_MAP16 (1<<20)
+#define MA_MAP17 (1<<21)
+#define MA_MAP18 (1<<22)
+
+/* ********** Texture Slots (MTex) ********** */
#define TEX_TOTNAM 14
@@ -171,7 +221,7 @@ typedef short IPO_Channel;
#define MAP_VARF 13
#define MAP_DISP 14
-/* ******************** */
+/* ********** Texture (ID_TE) ********** */
#define TE_TOTIPO 26
#define TE_TOTNAM 26
@@ -208,21 +258,21 @@ typedef short IPO_Channel;
#define TE_BRIGHT 25
#define TE_CONTRA 26
-/* ******************** */
+/* ******** Sequence (ID_SEQ) ********** */
#define SEQ_TOTIPO 1
#define SEQ_TOTNAM 1
#define SEQ_FAC1 1
-/* ******************** */
+/* ********* Curve (ID_CU) *********** */
#define CU_TOTIPO 1
#define CU_TOTNAM 1
#define CU_SPEED 1
-/* ******************** */
+/* ********* ShapeKey (ID_KE) *********** */
#define KEY_TOTIPO 64
#define KEY_TOTNAM 64
@@ -230,7 +280,7 @@ typedef short IPO_Channel;
#define KEY_SPEED 0
#define KEY_NR 1
-/* ******************** */
+/* ********* World (ID_WO) *********** */
#define WO_TOTIPO 29
#define WO_TOTNAM 16
@@ -255,7 +305,7 @@ typedef short IPO_Channel;
#define WO_STARDIST 15
#define WO_STARSIZE 16
-/* ******************** */
+/* ********** Lamp (ID_LA) ********** */
#define LA_TOTIPO 21
#define LA_TOTNAM 10
@@ -271,9 +321,8 @@ typedef short IPO_Channel;
#define LA_QUAD2 9
#define LA_HALOINT 10
-/* ******************** */
+/* ********* Camera (ID_CA) ************ */
-/* yafray: totipo & totnam +2 because of added curves */
#define CAM_TOTIPO 7
#define CAM_TOTNAM 7
@@ -288,7 +337,7 @@ typedef short IPO_Channel;
#define CAM_SHIFT_X 6
#define CAM_SHIFT_Y 7
-/* ******************** */
+/* ********* Sound (ID_SO) *********** */
#define SND_TOTIPO 4
#define SND_TOTNAM 4
@@ -298,9 +347,9 @@ typedef short IPO_Channel;
#define SND_PANNING 3
#define SND_ATTEN 4
-/* ******************** */
+/* ******* PoseChannel (ID_PO) ********* */
-#define AC_TOTIPO 10 /* __NLA */
+#define AC_TOTIPO 10
#define AC_TOTNAM 10
#define AC_LOC_X 1
@@ -316,28 +365,18 @@ typedef short IPO_Channel;
#define AC_QUAT_Y 27
#define AC_QUAT_Z 28
-/* ******************** */
-#define CO_TOTIPO 2 /* Constraint Ipos */
+/* ******** Constraint (ID_CO) ********** */
+
+#define CO_TOTIPO 2
#define CO_TOTNAM 2
#define CO_ENFORCE 1
#define CO_HEADTAIL 2
-/*
-#define CO_TIME 2
-#define CO_OFFSET_X 3
-#define CO_OFFSET_Y 4
-#define CO_OFFSET_Z 5
-#define CO_ORIENT_X 6
-#define CO_ORIENT_Y 7
-#define CO_ORIENT_Z 8
-#define CO_ROLL 9
-*/
-/* ******************** */
-/* fluidsim ipos NT */
+/* ****** FluidSim (ID_FLUIDSIM) ****** */
-#define FLUIDSIM_TOTIPO 9
-#define FLUIDSIM_TOTNAM 9
+#define FLUIDSIM_TOTIPO 13
+#define FLUIDSIM_TOTNAM 13
#define FLUIDSIM_VISC 1
#define FLUIDSIM_TIME 2
@@ -352,10 +391,17 @@ typedef short IPO_Channel;
#define FLUIDSIM_ACTIVE 9
+#define FLUIDSIM_ATTR_FORCE_STR 10
+#define FLUIDSIM_ATTR_FORCE_RADIUS 11
+#define FLUIDSIM_VEL_FORCE_STR 12
+#define FLUIDSIM_VEL_FORCE_RADIUS 13
+
/* ******************** */
/* particle ipos */
-#define PART_TOTIPO 19
-#define PART_TOTNAM 19
+
+/* ******* Particle (ID_PA) ******** */
+#define PART_TOTIPO 25
+#define PART_TOTNAM 25
#define PART_EMIT_FREQ 1
#define PART_EMIT_LIFE 2
@@ -381,9 +427,18 @@ typedef short IPO_Channel;
#define PART_BB_TILT 19
+#define PART_PD_FSTR 20
+#define PART_PD_FFALL 21
+#define PART_PD_FMAXD 22
+
+#define PART_PD2_FSTR 23
+#define PART_PD2_FFALL 24
+#define PART_PD2_FMAXD 25
+
+
+/* -------------------- Defines: Flags and Types ------------------ */
-/* these are IpoCurve specific */
-/* **************** IPO ********************* */
+/* ----- IPO Curve Defines ------- */
/* icu->vartype */
#define IPO_CHAR 0
@@ -393,6 +448,7 @@ typedef short IPO_Channel;
#define IPO_FLOAT 4
#define IPO_DOUBLE 5
#define IPO_FLOAT_DEGR 6
+
/* very special case, in keys */
#define IPO_BEZTRIPLE 100
#define IPO_BPOINT 101
@@ -407,7 +463,8 @@ typedef short IPO_Channel;
#define IPO_CONST 0
#define IPO_LIN 1
#define IPO_BEZ 2
-#define IPO_MIXED 3 /* not used yet */
+ /* not used yet */
+#define IPO_MIXED 3
/* icu->extrap */
#define IPO_HORIZ 0
@@ -425,6 +482,19 @@ typedef short IPO_Channel;
#define IPO_PROTECT 64
#define IPO_MUTE 128
+/* ---------- IPO Drivers ----------- */
+
+/* offset in driver->name for finding second posechannel for rot-diff */
+#define DRIVER_NAME_OFFS 32
+
+/* driver->type */
+#define IPO_DRIVER_TYPE_NORMAL 0
+#define IPO_DRIVER_TYPE_PYTHON 1
+
+/* driver->flag */
+ /* invalid flag: currently only used for buggy pydriver expressions */
+#define IPO_DRIVER_FLAG_INVALID (1<<0)
+
#endif
diff --git a/source/blender/makesdna/DNA_lamp_types.h b/source/blender/makesdna/DNA_lamp_types.h
index 2afe78289c1..f8f2255c1a7 100644
--- a/source/blender/makesdna/DNA_lamp_types.h
+++ b/source/blender/makesdna/DNA_lamp_types.h
@@ -35,7 +35,7 @@
#include "DNA_scriptlink_types.h"
#ifndef MAX_MTEX
-#define MAX_MTEX 10
+#define MAX_MTEX 18
#endif
struct MTex;
@@ -45,20 +45,21 @@ struct CurveMapping;
typedef struct Lamp {
ID id;
- short type, mode;
+ short type, pad3;
+ int mode;
short colormodel, totex;
float r, g, b, k;
+ float shdwr, shdwg, shdwb, shdwpad;
float energy, dist, spotsize, spotblend;
float haint;
float att1, att2; /* Quad1 and Quad2 attenuation */
- int pad2;
struct CurveMapping *curfalloff;
short falloff_type;
- short pad3;
+ short pad2;
float clipsta, clipend, shadspotsize;
float bias, soft;
@@ -76,6 +77,23 @@ typedef struct Lamp {
/* texact is for buttons */
short texact, shadhalostep;
+ /* sun/sky */
+ short sun_effect_type;
+ short skyblendtype;
+ float horizon_brightness;
+ float spread;
+ float sun_brightness;
+ float sun_size;
+ float backscattered_light;
+ float sun_intensity;
+ float atm_turbidity;
+ float atm_inscattering_factor;
+ float atm_extinction_factor;
+ float atm_distance_factor;
+ float skyblendfac;
+ float sky_exposure;
+ short sky_colorspace, pad4;
+
/* yafray: photonlight params */
int YF_numphotons, YF_numsearch;
short YF_phdepth, YF_useqmc, YF_bufsize, YF_pad;
@@ -84,7 +102,7 @@ typedef struct Lamp {
float YF_glowint, YF_glowofs;
short YF_glowtype, YF_pad2;
- struct MTex *mtex[10];
+ struct MTex *mtex[18]; /* MAX_MTEX */
struct Ipo *ipo;
/* preview */
@@ -122,6 +140,17 @@ typedef struct Lamp {
/* yafray: lamp shadowbuffer flag, softlight */
/* Since it is used with LOCAL lamp, can't use LA_SHAD */
#define LA_YF_SOFT 16384
+#define LA_LAYER_SHADOW 32768
+#define LA_SHAD_TEX (1<<16)
+
+/* layer_shadow */
+#define LA_LAYER_SHADOW_BOTH 0
+#define LA_LAYER_SHADOW_CAST 1
+#define LA_LAYER_SHADOW_RECEIVE 2
+
+/* sun effect type*/
+#define LA_SUN_EFFECT_SKY 1
+#define LA_SUN_EFFECT_AP 2
/* falloff_type */
#define LA_FALLOFF_CONSTANT 0
@@ -165,6 +194,7 @@ typedef struct Lamp {
/* mapto */
#define LAMAP_COL 1
+#define LAMAP_SHAD 2
#endif /* DNA_LAMP_TYPES_H */
diff --git a/source/blender/makesdna/DNA_material_types.h b/source/blender/makesdna/DNA_material_types.h
index 701041319e5..aa847050581 100644
--- a/source/blender/makesdna/DNA_material_types.h
+++ b/source/blender/makesdna/DNA_material_types.h
@@ -36,7 +36,7 @@
#include "DNA_listBase.h"
#ifndef MAX_MTEX
-#define MAX_MTEX 10
+#define MAX_MTEX 18
#endif
struct MTex;
@@ -76,21 +76,23 @@ typedef struct Material {
float aniso_gloss_mir;
float dist_mir;
short fadeto_mir;
- short pad1;
+ short shade_flag; /* like Cubic interpolation */
int mode, mode_l; /* mode_l is the or-ed result of all layer modes */
short flarec, starc, linec, ringc;
float hasize, flaresize, subsize, flareboost;
float strand_sta, strand_end, strand_ease, strand_surfnor;
- float strand_min, strand_pad;
+ float strand_min, strand_widthfade;
char strand_uvname[32];
- float sbias; /* shadow bias */
+ float sbias; /* shadow bias to prevent terminator prob */
+ float lbias; /* factor to multiply lampbias with (0.0 = no mult) */
float shad_alpha; /* in use for irregular shadowbuffer */
+ int septex;
/* for buttons and render*/
char rgbsel, texact, pr_type, use_nodes;
- short pr_back, pr_lamp, septex, ml_flag; /* ml_flag is for disable base material */
+ short pr_back, pr_lamp, pad4, ml_flag; /* ml_flag is for disable base material */
/* shaders */
short diff_shader, spec_shader;
@@ -108,7 +110,7 @@ typedef struct Material {
short ramp_show, pad3;
float rampfac_col, rampfac_spec;
- struct MTex *mtex[10];
+ struct MTex *mtex[18]; /* MAX_MTEX */
struct bNodeTree *nodetree;
struct Ipo *ipo;
struct Group *group; /* light group */
@@ -131,6 +133,8 @@ typedef struct Material {
int YF_dsmp, YF_preset, YF_djit;
ScriptLink scriptlink;
+
+ ListBase gpumaterial; /* runtime */
} Material;
/* **************** MATERIAL ********************* */
@@ -156,6 +160,7 @@ typedef struct Material {
#define MA_SHLESS 4
#define MA_WIRE 8
#define MA_VERTEXCOL 16
+#define MA_HALO_SOFT 16
#define MA_HALO 32
#define MA_ZTRA 64
#define MA_VERTEXCOLP 128
@@ -192,12 +197,16 @@ typedef struct Material {
#define MA_STR_B_UNITS 0x40000000
#define MA_STR_SURFDIFF 0x80000000
-#define MA_MODE_MASK 0x4fffffff /* all valid mode bits */
+#define MA_MODE_MASK 0x6fffffff /* all valid mode bits */
/* ray mirror fadeout */
#define MA_RAYMIR_FADETOSKY 0
#define MA_RAYMIR_FADETOMAT 1
+/* shade_flag */
+#define MA_CUBIC 1
+#define MA_OBCOLOR 2
+
/* diff_shader */
#define MA_DIFF_LAMBERT 0
#define MA_DIFF_ORENNAYAR 1
@@ -311,6 +320,7 @@ typedef struct Material {
#define MA_LAMP 6
#define MA_SKY 7
#define MA_HAIR 10
+#define MA_ATMOS 11
/* pr_back */
#define MA_DARK 1
diff --git a/source/blender/makesdna/DNA_meshdata_types.h b/source/blender/makesdna/DNA_meshdata_types.h
index 819711a7875..fc686a4cc10 100644
--- a/source/blender/makesdna/DNA_meshdata_types.h
+++ b/source/blender/makesdna/DNA_meshdata_types.h
@@ -42,7 +42,7 @@ typedef struct MFace {
typedef struct MEdge {
unsigned int v1, v2;
- char crease, pad;
+ char crease, bweight;
short flag;
} MEdge;
@@ -60,7 +60,7 @@ typedef struct MDeformVert {
typedef struct MVert {
float co[3];
short no[3];
- char flag, mat_nr;
+ char flag, mat_nr, bweight, pad[3];
} MVert;
/* at the moment alpha is abused for vertex painting
@@ -69,6 +69,22 @@ typedef struct MCol {
char a, r, g, b;
} MCol;
+/*bmesh custom data stuff*/
+typedef struct MTexPoly{
+ struct Image *tpage;
+ char flag, transp;
+ short mode,tile,unwrap;
+}MTexPoly;
+
+typedef struct MLoopUV{
+ float uv[2];
+}MLoopUV;
+
+typedef struct MLoopCol{
+ char a, r, g, b;
+ int pad; /*waste!*/
+}MLoopCol;
+
typedef struct MSticky {
float co[2];
} MSticky;
@@ -143,7 +159,7 @@ typedef struct Multires {
MVert *verts;
unsigned char level_count, current, newlvl, edgelvl, pinlvl, renderlvl;
- unsigned char use_col, pad;
+ unsigned char use_col, flag;
/* Special level 1 data that cannot be modified from other levels */
CustomData vdata;
@@ -213,7 +229,7 @@ typedef struct PartialVisibility {
/* mtface->mode */
#define TF_DYNAMIC 1
-#define TF_DEPRECATED 2
+#define TF_ALPHASORT 2
#define TF_TEX 4
#define TF_SHAREDVERT 8
#define TF_LIGHT 16
@@ -229,14 +245,16 @@ typedef struct PartialVisibility {
#define TF_SHADOW 8192
#define TF_BMFONT 16384
-/* mtface->transp */
+/* mtface->transp, values 1-4 are used as flags in the GL, WARNING, TF_SUB cant work with this */
#define TF_SOLID 0
#define TF_ADD 1
#define TF_ALPHA 2
+#define TF_CLIP 4 /* clipmap alpha/binary alpha all or nothing! */
/* sub is not available in the user interface anymore */
#define TF_SUB 3
+
/* mtface->unwrap */
#define TF_DEPRECATED1 1
#define TF_DEPRECATED2 2
@@ -247,4 +265,7 @@ typedef struct PartialVisibility {
#define TF_PIN3 64
#define TF_PIN4 128
+/* multires->flag */
+#define MULTIRES_NO_RENDER 1
+
#endif
diff --git a/source/blender/makesdna/DNA_modifier_types.h b/source/blender/makesdna/DNA_modifier_types.h
index 51f0e961709..ae07434a37f 100644
--- a/source/blender/makesdna/DNA_modifier_types.h
+++ b/source/blender/makesdna/DNA_modifier_types.h
@@ -32,6 +32,13 @@ typedef enum ModifierType {
eModifierType_ParticleSystem,
eModifierType_ParticleInstance,
eModifierType_Explode,
+ eModifierType_Cloth,
+ eModifierType_Collision,
+ eModifierType_Bevel,
+ eModifierType_Shrinkwrap,
+ eModifierType_Fluidsim,
+ eModifierType_Mask,
+ eModifierType_SimpleDeform,
NUM_MODIFIER_TYPES
} ModifierType;
@@ -100,6 +107,24 @@ typedef struct BuildModifierData {
int randomize, seed;
} BuildModifierData;
+/* Mask Modifier */
+typedef struct MaskModifierData {
+ ModifierData modifier;
+
+ struct Object *ob_arm; /* armature to use to in place of hardcoded vgroup */
+ char vgroup[32]; /* name of vertex group to use to mask */
+
+ int mode; /* using armature or hardcoded vgroup */
+ int flag; /* flags for various things */
+} MaskModifierData;
+
+/* Mask Modifier -> mode */
+#define MOD_MASK_MODE_VGROUP 0
+#define MOD_MASK_MODE_ARM 1
+
+/* Mask Modifier -> flag */
+#define MOD_MASK_INV (1<<0)
+
typedef struct ArrayModifierData {
ModifierData modifier;
@@ -173,6 +198,7 @@ typedef struct MirrorModifierData {
#define MOD_MIR_AXIS_X 1<<3
#define MOD_MIR_AXIS_Y 1<<4
#define MOD_MIR_AXIS_Z 1<<5
+#define MOD_MIR_VGROUP 1<<6
typedef struct EdgeSplitModifierData {
ModifierData modifier;
@@ -185,6 +211,27 @@ typedef struct EdgeSplitModifierData {
#define MOD_EDGESPLIT_FROMANGLE 1<<1
#define MOD_EDGESPLIT_FROMFLAG 1<<2
+typedef struct BevelModifierData {
+ ModifierData modifier;
+
+ float value; /* the "raw" bevel value (distance/amount to bevel) */
+ int res; /* the resolution (as originally coded, it is the number of recursive bevels) */
+ int pad;
+ short flags; /* general option flags */
+ short val_flags; /* flags used to interpret the bevel value */
+ short lim_flags; /* flags to tell the tool how to limit the bevel */
+ short e_flags; /* flags to direct how edge weights are applied to verts */
+ float bevel_angle; /* if the BME_BEVEL_ANGLE is set, this will be how "sharp" an edge must be before it gets beveled */
+ char defgrp_name[32]; /* if the BME_BEVEL_VWEIGHT option is set, this will be the name of the vert group */
+} BevelModifierData;
+
+typedef struct BMeshModifierData {
+ ModifierData modifier;
+
+ float pad;
+ int type;
+} BMeshModifierData;
+
typedef struct DisplaceModifierData {
ModifierData modifier;
@@ -304,13 +351,14 @@ typedef struct WaveModifierData {
short flag, pad;
float startx, starty, height, width;
- float narrow, speed, damp;
+ float narrow, speed, damp, falloff;
int texmapping, uvlayer_tmp;
char uvlayer_name[32];
-
+
float timeoffs, lifetime;
+ float pad1;
} WaveModifierData;
typedef struct ArmatureModifierData {
@@ -341,6 +389,35 @@ typedef struct SoftbodyModifierData {
ModifierData modifier;
} SoftbodyModifierData;
+typedef struct ClothModifierData {
+ ModifierData modifier;
+
+ struct Cloth *clothObject; /* The internal data structure for cloth. */
+ struct ClothSimSettings *sim_parms; /* definition is in DNA_cloth_types.h */
+ struct ClothCollSettings *coll_parms; /* definition is in DNA_cloth_types.h */
+ struct PointCache *point_cache; /* definition is in DNA_object_force.h */
+} ClothModifierData;
+
+typedef struct CollisionModifierData {
+ ModifierData modifier;
+
+ struct MVert *x; /* position at the beginning of the frame */
+ struct MVert *xnew; /* position at the end of the frame */
+ struct MVert *xold; /* unsued atm, but was discussed during sprint */
+ struct MVert *current_xnew; /* new position at the actual inter-frame step */
+ struct MVert *current_x; /* position at the actual inter-frame step */
+ struct MVert *current_v; /* (xnew - x) at the actual inter-frame step */
+
+ struct MFace *mfaces; /* object face data */
+
+ unsigned int numverts;
+ unsigned int numfaces;
+ short absorption; /* used for forces, in % */
+ short pad;
+ float time; /* cfra time of modifier */
+ struct BVHTree *bvhtree; /* bounding volume hierarchy for this cloth object */
+} CollisionModifierData;
+
typedef enum {
eBooleanModifierOp_Intersect,
eBooleanModifierOp_Union,
@@ -436,4 +513,80 @@ typedef struct ExplodeModifierData {
float protect;
} ExplodeModifierData;
+typedef struct FluidsimModifierData {
+ ModifierData modifier;
+
+ struct FluidsimSettings *fss; /* definition is is DNA_object_fluidsim.h */
+ struct PointCache *point_cache; /* definition is in DNA_object_force.h */
+} FluidsimModifierData;
+
+typedef struct ShrinkwrapModifierData {
+ ModifierData modifier;
+
+ struct Object *target; /* shrink target */
+ struct Object *auxTarget; /* additional shrink target */
+ char vgroup_name[32]; /* optional vertexgroup name */
+ float keepDist; /* distance offset to keep from mesh/projection point */
+ short shrinkType; /* shrink type projection */
+ short shrinkOpts; /* shrink options */
+ char projAxis; /* axis to project over */
+
+ /*
+ * if using projection over vertex normal this controls the
+ * the level of subsurface that must be done before getting the
+ * vertex coordinates and normal
+ */
+ char subsurfLevels;
+
+ char pad[6];
+
+} ShrinkwrapModifierData;
+
+/* Shrinkwrap->shrinkType */
+#define MOD_SHRINKWRAP_NEAREST_SURFACE 0
+#define MOD_SHRINKWRAP_PROJECT 1
+#define MOD_SHRINKWRAP_NEAREST_VERTEX 2
+
+/* Shrinkwrap->shrinkOpts */
+#define MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR (1<<0) /* allow shrinkwrap to move the vertex in the positive direction of axis */
+#define MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR (1<<1) /* allow shrinkwrap to move the vertex in the negative direction of axis */
+
+#define MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE (1<<3) /* ignore vertex moves if a vertex ends projected on a front face of the target */
+#define MOD_SHRINKWRAP_CULL_TARGET_BACKFACE (1<<4) /* ignore vertex moves if a vertex ends projected on a back face of the target */
+
+#define MOD_SHRINKWRAP_KEEP_ABOVE_SURFACE (1<<5) /* distance is measure to the front face of the target */
+
+#define MOD_SHRINKWRAP_PROJECT_OVER_X_AXIS (1<<0)
+#define MOD_SHRINKWRAP_PROJECT_OVER_Y_AXIS (1<<1)
+#define MOD_SHRINKWRAP_PROJECT_OVER_Z_AXIS (1<<2)
+#define MOD_SHRINKWRAP_PROJECT_OVER_NORMAL 0 /* projection over normal is used if no axis is selected */
+
+
+typedef struct SimpleDeformModifierData {
+ ModifierData modifier;
+
+ struct Object *origin; /* object to control the origin of modifier space coordinates */
+ char vgroup_name[32]; /* optional vertexgroup name */
+ float factor; /* factors to control simple deforms */
+ float limit[2]; /* lower and upper limit */
+
+ char mode; /* deform function */
+ char axis; /* lock axis (for taper and strech) */
+ char originOpts; /* originOptions */
+ char pad;
+
+} SimpleDeformModifierData;
+
+#define MOD_SIMPLEDEFORM_MODE_TWIST 1
+#define MOD_SIMPLEDEFORM_MODE_BEND 2
+#define MOD_SIMPLEDEFORM_MODE_TAPER 3
+#define MOD_SIMPLEDEFORM_MODE_STRETCH 4
+
+#define MOD_SIMPLEDEFORM_LOCK_AXIS_X (1<<0)
+#define MOD_SIMPLEDEFORM_LOCK_AXIS_Y (1<<1)
+
+/* indicates whether simple deform should use the local
+ coordinates or global coordinates of origin */
+#define MOD_SIMPLEDEFORM_ORIGIN_LOCAL (1<<0)
+
#endif
diff --git a/source/blender/makesdna/DNA_node_types.h b/source/blender/makesdna/DNA_node_types.h
index 5f20939fc23..eda37d952c1 100644
--- a/source/blender/makesdna/DNA_node_types.h
+++ b/source/blender/makesdna/DNA_node_types.h
@@ -58,7 +58,7 @@ typedef struct bNodeStack {
#define NS_OSA_VALUES 2
typedef struct bNodeSocket {
- struct bNodeSocket *next, *prev;
+ struct bNodeSocket *next, *prev, *new_sock;
char name[32];
bNodeStack ns; /* custom data for inputs, only UI writes in this */
@@ -92,7 +92,8 @@ typedef struct bNodeSocket {
#define SOCK_IN_USE 4
/* unavailable is for dynamic sockets */
#define SOCK_UNAVAIL 8
-
+ /* flag for selection status */
+#define SOCK_SEL 16
#
#
typedef struct bNodePreview {
@@ -106,6 +107,7 @@ typedef struct bNode {
struct bNode *next, *prev, *new_node;
char name[32];
+ char username[32]; /* custom name defined by user */
short type, flag;
short done, level; /* both for dependency and sorting */
short lasty, menunr; /* lasty: check preview render status, menunr: browse ID blocks */
@@ -142,6 +144,8 @@ typedef struct bNode {
#define NODE_GROUP_EDIT 128
/* free test flag, undefined */
#define NODE_TEST 256
+ /* composite: don't do node but pass on buffer(s) */
+#define NODE_MUTED 512
typedef struct bNodeLink {
struct bNodeLink *next, *prev;
@@ -158,7 +162,8 @@ typedef struct bNodeTree {
ListBase nodes, links;
- bNodeStack **stack; /* stack is only while executing, no read/write in file */
+ bNodeStack *stack; /* stack is only while executing, no read/write in file */
+ struct ListBase *threadstack; /* same as above */
int type, init; /* set init on fileread */
int stacksize; /* amount of elements in stack */
@@ -167,6 +172,10 @@ typedef struct bNodeTree {
ListBase alltypes; /* type definitions */
struct bNodeType *owntype; /* for groups or dynamic trees, no read/write */
+ /* selected input/output socket */
+ bNodeSocket *selin;
+ bNodeSocket *selout;
+
/* callbacks */
void (*timecursor)(int nr);
void (*stats_draw)(char *str);
@@ -191,13 +200,27 @@ typedef struct NodeImageAnim {
} NodeImageAnim;
typedef struct NodeBlurData {
- short sizex, sizey, samples, maxspeed, minspeed, pad1;
- float fac;
+ short sizex, sizey;
+ short samples, maxspeed, minspeed, relative;
+ float fac, percentx, percenty;
short filtertype;
char bokeh, gamma;
- int pad2;
+ short curved;
+ short pad;
+ int image_in_width, image_in_height; /* needed for absolute/relative conversions */
} NodeBlurData;
+typedef struct NodeDBlurData {
+ float center_x, center_y, distance, angle, spin, zoom;
+ short iter;
+ char wrap, pad;
+} NodeDBlurData;
+
+typedef struct NodeBilateralBlurData {
+ float sigma_color, sigma_space;
+ short iter, pad;
+} NodeBilateralBlurData;
+
typedef struct NodeHueSat {
float hue, sat, val;
} NodeHueSat;
@@ -218,6 +241,10 @@ typedef struct NodeTwoXYs {
short x1, x2, y1, y2;
} NodeTwoXYs;
+typedef struct NodeTwoFloats {
+ float x, y;
+} NodeTwoFloats;
+
typedef struct NodeGeometry {
char uvname[32];
char colname[32];
@@ -234,6 +261,10 @@ typedef struct NodeDefocus {
float fstop, maxblur, bthresh, scale;
} NodeDefocus;
+typedef struct NodeScriptDict {
+ void *dict; /* for PyObject *dict */
+ void *node; /* for BPy_Node *node */
+} NodeScriptDict;
/* qdn: glare node */
typedef struct NodeGlare {
diff --git a/source/blender/makesdna/DNA_object_fluidsim.h b/source/blender/makesdna/DNA_object_fluidsim.h
index 9b1e4fb56cb..2914330a2b0 100644
--- a/source/blender/makesdna/DNA_object_fluidsim.h
+++ b/source/blender/makesdna/DNA_object_fluidsim.h
@@ -108,7 +108,7 @@ typedef struct FluidsimSettings {
float surfaceSmoothing;
/* number of surface subdivisions*/
int surfaceSubdivs;
- int unusedDNADummy;
+ int flag; /* GUI flags */
/* particle display - size scaling, and alpha influence */
float particleInfSize, particleInfAlpha;
@@ -117,6 +117,18 @@ typedef struct FluidsimSettings {
/* save fluidsurface normals in mvert.no, and surface vertex velocities (if available) in mvert.co */
struct MVert *meshSurfNormals;
+
+ /* Fluid control settings */
+ float cpsTimeStart;
+ float cpsTimeEnd;
+ float cpsQuality;
+
+ float attractforceStrength;
+ float attractforceRadius;
+ float velocityforceStrength;
+ float velocityforceRadius;
+
+ int lastgoodframe;
} FluidsimSettings;
@@ -128,8 +140,9 @@ typedef struct FluidsimSettings {
#define OB_FLUIDSIM_INFLOW 16
#define OB_FLUIDSIM_OUTFLOW 32
#define OB_FLUIDSIM_PARTICLE 64
+#define OB_FLUIDSIM_CONTROL 128
-#define OB_TYPEFLAG_START 0
+#define OB_TYPEFLAG_START 7
#define OB_FSGEO_THIN (1<<(OB_TYPEFLAG_START+1))
#define OB_FSBND_NOSLIP (1<<(OB_TYPEFLAG_START+2))
#define OB_FSBND_PARTSLIP (1<<(OB_TYPEFLAG_START+3))
@@ -145,6 +158,9 @@ typedef struct FluidsimSettings {
#define OB_FSPART_NEWPART (1<<3)
#define OB_FSPART_FLOAT (1<<4)
+// new fluid bit flags for fss->flags - dg
+#define OB_FLUIDSIM_REVERSE (1 << 0)
+
#ifdef __cplusplus
}
#endif
diff --git a/source/blender/makesdna/DNA_object_force.h b/source/blender/makesdna/DNA_object_force.h
index bbd12fee7c2..21c5242a703 100644
--- a/source/blender/makesdna/DNA_object_force.h
+++ b/source/blender/makesdna/DNA_object_force.h
@@ -67,13 +67,75 @@ typedef struct PartDeflect {
float tex_nabla;
short tex_mode, kink, kink_axis, rt2;
struct Tex *tex; /* Texture of the texture effector */
+ struct RNG *rng; /* random noise generator for e.g. wind */
+ float f_noise; /* noise of force (currently used for wind) */
+ int pad;
} PartDeflect;
+typedef struct PointCache {
+ int flag; /* generic flag */
+ int simframe; /* current frame of simulation (only if SIMULATION_VALID) */
+ int startframe; /* simulation start frame */
+ int endframe; /* simulation end frame */
+ int editframe; /* frame being edited (runtime only) */
+} PointCache;
typedef struct SBVertex {
float vec[4];
} SBVertex;
+typedef struct BulletSoftBody {
+ int flag; /* various boolean options */
+ float linStiff; /* linear stiffness 0..1 */
+ float angStiff; /* angular stiffness 0..1 */
+ float volume; /* volume preservation 0..1 */
+
+ int viterations; /* Velocities solver iterations */
+ int piterations; /* Positions solver iterations */
+ int diterations; /* Drift solver iterations */
+ int citerations; /* Cluster solver iterations */
+
+ float kSRHR_CL; /* Soft vs rigid hardness [0,1] (cluster only) */
+ float kSKHR_CL; /* Soft vs kinetic hardness [0,1] (cluster only) */
+ float kSSHR_CL; /* Soft vs soft hardness [0,1] (cluster only) */
+ float kSR_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+
+ float kSK_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+ float kSS_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */
+ float kVCF; /* Velocities correction factor (Baumgarte) */
+ float kDP; /* Damping coefficient [0,1] */
+
+ float kDG; /* Drag coefficient [0,+inf] */
+ float kLF; /* Lift coefficient [0,+inf] */
+ float kPR; /* Pressure coefficient [-inf,+inf] */
+ float kVC; /* Volume conversation coefficient [0,+inf] */
+
+ float kDF; /* Dynamic friction coefficient [0,1] */
+ float kMT; /* Pose matching coefficient [0,1] */
+ float kCHR; /* Rigid contacts hardness [0,1] */
+ float kKHR; /* Kinetic contacts hardness [0,1] */
+
+ float kSHR; /* Soft contacts hardness [0,1] */
+ float kAHR; /* Anchors hardness [0,1] */
+ int collisionflags; /* Vertex/Face or Signed Distance Field(SDF) or Clusters, Soft versus Soft or Rigid */
+ int numclusteriterations; /* number of iterations to refine collision clusters*/
+
+} BulletSoftBody;
+
+/* BulletSoftBody.flag */
+#define OB_BSB_SHAPE_MATCHING 2
+#define OB_BSB_UNUSED 4
+#define OB_BSB_BENDING_CONSTRAINTS 8
+#define OB_BSB_AERO_VPOINT 16 /* aero model, Vertex normals are oriented toward velocity*/
+#define OB_BSB_AERO_VTWOSIDE 32 /* aero model, Vertex normals are flipped to match velocity */
+
+/* BulletSoftBody.collisionflags */
+#define OB_BSB_COL_SDF_RS 2 /* SDF based rigid vs soft */
+#define OB_BSB_COL_CL_RS 4 /* Cluster based rigid vs soft */
+#define OB_BSB_COL_CL_SS 8 /* Cluster based soft vs soft */
+#define OB_BSB_COL_VF_SS 16 /* Vertex/Face based soft vs soft */
+
+
typedef struct SoftBody {
struct ParticleSystem *particles; /* particlesystem softbody */
@@ -81,7 +143,7 @@ typedef struct SoftBody {
int totpoint, totspring;
struct BodyPoint *bpoint; /* not saved in file */
struct BodySpring *bspring; /* not saved in file */
- float ctime; /* last time calculated */
+ float pad;
/* part of UI: */
@@ -126,10 +188,15 @@ typedef struct SoftBody {
minloops,
maxloops,
choke,
- pad3,pad4,pad5
+ solver_ID,
+ plastic,springpreload
;
struct SBScratch *scratch; /* scratch pad/cache on live time not saved in file */
+ float shearstiff;
+ float inpush;
+
+ struct PointCache *pointcache;
} SoftBody;
@@ -141,8 +208,8 @@ typedef struct SoftBody {
#define PFIELD_GUIDE 5
#define PFIELD_TEXTURE 6
#define PFIELD_HARMONIC 7
-#define PFIELD_NUCLEAR 8
-#define PFIELD_MDIPOLE 9
+#define PFIELD_CHARGE 8
+#define PFIELD_LENNARDJ 9
/* pd->flag: various settings */
@@ -157,6 +224,7 @@ typedef struct SoftBody {
#define PFIELD_USEMIN 256
#define PFIELD_USEMAXR 512
#define PFIELD_USEMINR 1024
+#define PFIELD_TEX_ROOTCO 2048
/* pd->falloff */
#define PFIELD_FALL_SPHERE 0
@@ -170,21 +238,30 @@ typedef struct SoftBody {
#define PFIELD_TEX_GRAD 1
#define PFIELD_TEX_CURL 2
+/* pointcache->flag */
+#define PTCACHE_BAKED 1
+#define PTCACHE_OUTDATED 2
+#define PTCACHE_SIMULATION_VALID 4
+#define PTCACHE_BAKING 8
+#define PTCACHE_BAKE_EDIT 16
+#define PTCACHE_BAKE_EDIT_ACTIVE 32
+
/* ob->softflag */
#define OB_SB_ENABLE 1
#define OB_SB_GOAL 2
#define OB_SB_EDGES 4
#define OB_SB_QUADS 8
#define OB_SB_POSTDEF 16
-#define OB_SB_REDO 32
-#define OB_SB_BAKESET 64
-#define OB_SB_BAKEDO 128
-#define OB_SB_RESET 256
+// #define OB_SB_REDO 32
+// #define OB_SB_BAKESET 64
+// #define OB_SB_BAKEDO 128
+// #define OB_SB_RESET 256
#define OB_SB_SELF 512
#define OB_SB_FACECOLL 1024
#define OB_SB_EDGECOLL 2048
#define OB_SB_COLLFINAL 4096
-#define OB_SB_PROTECT_CACHE 8192
+//#define OB_SB_PROTECT_CACHE 8192
+#define OB_SB_AERO_ANGLE 16384
/* sb->solverflags */
#define SBSO_MONITOR 1
diff --git a/source/blender/makesdna/DNA_object_types.h b/source/blender/makesdna/DNA_object_types.h
index 5120bee742c..b885bbf084e 100644
--- a/source/blender/makesdna/DNA_object_types.h
+++ b/source/blender/makesdna/DNA_object_types.h
@@ -59,6 +59,27 @@ typedef struct bDeformGroup {
char name[32];
} bDeformGroup;
+/**
+ * The following illustrates the orientation of the
+ * bounding box in local space
+ *
+ *
+ * Z Y
+ * | /
+ * |/
+ * .-----X
+ *
+ *
+ * 2----------6
+ * /| /|
+ * / | / |
+ * 1----------5 |
+ * | | | |
+ * | 3-------|--7
+ * | / | /
+ * |/ |/
+ * 0----------4
+ */
typedef struct BoundBox {
float vec[8][3];
int flag, pad;
@@ -81,6 +102,7 @@ typedef struct Object {
struct Path *path;
struct BoundBox *bb;
struct bAction *action;
+ struct bAction *poselib;
struct bPose *pose;
void *data;
@@ -96,7 +118,7 @@ typedef struct Object {
float loc[3], dloc[3], orig[3];
float size[3], dsize[3];
float rot[3], drot[3];
- float quat[4], dquat[4];
+ /* float quat[4], dquat[4]; (not used yet) */
float obmat[4][4];
float parentinv[4][4]; /* inverse result of parent, so that object doesn't 'stick' to parent */
float constinv[4][4]; /* inverse result of constraints. doesn't include effect of parent or object local transform */
@@ -115,7 +137,7 @@ typedef struct Object {
int dupon, dupoff, dupsta, dupend;
- float sf, ctime;
+ float sf, ctime; /* sf is time-offset, ctime is the objects current time */
/* during realtime */
@@ -134,7 +156,9 @@ typedef struct Object {
float formfactor;
float rdamping, sizefac;
-
+ float margin;
+ int pad3;
+
char dt, dtx;
char totcol; /* copy of mesh or curve or meta */
char actcol; /* currently selected material in the user interface */
@@ -147,10 +171,6 @@ typedef struct Object {
ListBase sensors;
ListBase controllers;
ListBase actuators;
-
- /* now used to store cache particles,
- * should be renamed see effect.c (Campbell) */
- void *sumohandle;
float bbsize[3];
short index; /* custom index, for renderpasses */
@@ -173,7 +193,9 @@ typedef struct Object {
* bit 15: Always ignore activity culling
*/
int gameflag2;
- short softflag; /* softboday settings */
+ struct BulletSoftBody *bsoft; /* settings for game engine bullet soft body */
+
+ short softflag; /* softbody settings */
short recalc; /* dependency flag */
float anisotropicFriction[3];
@@ -192,17 +214,22 @@ typedef struct Object {
short shapenr, shapeflag; /* current shape key for menu or pinned, flag for pinning */
float smoothresh; /* smoothresh is phong interpolation ray_shadow correction in render */
- short recalco, pad4; /* recalco for temp storage of ob->recalc, bad design warning */
+ short recalco; /* recalco for temp storage of ob->recalc, bad design warning */
+ short body_type; /* for now used to temporarily holds the type of collision object */
struct FluidsimSettings *fluidsimSettings; /* if fluidsim enabled, store additional settings */
struct DerivedMesh *derivedDeform, *derivedFinal;
int lastDataMask; /* the custom data layer mask that was last used to calculate derivedDeform and derivedFinal */
- int pad;
+ unsigned int state; /* bit masks of game controllers that are active */
+ unsigned int init_state; /* bit masks of initial state as recorded by the users */
+ int pad2;
/*#ifdef WITH_VERSE*/
void *vnode; /* pointer at object VerseNode */
/*#endif*/
+
+ ListBase gpulamp; /* runtime, for lamps only */
} Object;
/* Warning, this is not used anymore because hooks are now modifiers */
@@ -293,6 +320,9 @@ extern Object workob;
/* for stride edit */
#define OB_DISABLE_PATH 1024
+#define OB_OFFS_PARENTADD 2048
+
+
/* (short) trackflag / upflag */
#define OB_POSX 0
#define OB_POSY 1
@@ -365,6 +395,8 @@ extern Object workob;
#define BA_FROMSET 128
+#define BA_TRANSFORM_CHILD 256 /* child of a transformed object */
+
/* an initial attempt as making selection more specific! */
#define BA_DESELECT 0
#define BA_SELECT 1
@@ -383,6 +415,7 @@ extern Object workob;
#define OB_RECALC_TIME 4
#define OB_RECALC 7
+
/* ob->gameflag */
#define OB_DYNAMIC 1
#define OB_CHILD 2
@@ -402,11 +435,21 @@ extern Object workob;
#define OB_PROP 16384
#define OB_MAINACTOR 32768
+#define OB_COLLISION 65536
+#define OB_SOFT_BODY 0x20000
+
/* ob->gameflag2 */
#define OB_NEVER_DO_ACTIVITY_CULLING 1
#define OB_LIFE (OB_PROP|OB_DYNAMIC|OB_ACTOR|OB_MAINACTOR|OB_CHILD)
+/* ob->body_type */
+#define OB_BODY_TYPE_NO_COLLISION 0
+#define OB_BODY_TYPE_STATIC 1
+#define OB_BODY_TYPE_DYNAMIC 2
+#define OB_BODY_TYPE_RIGID 3
+#define OB_BODY_TYPE_SOFT 4
+
/* ob->scavisflag */
#define OB_VIS_SENS 1
#define OB_VIS_CONT 2
@@ -419,6 +462,9 @@ extern Object workob;
#define OB_ADDCONT 512
#define OB_ADDACT 1024
#define OB_SHOWCONT 2048
+#define OB_SETSTBIT 4096
+#define OB_INITSTBIT 8192
+#define OB_DEBUGSTATE 16384
/* ob->restrictflag */
#define OB_RESTRICT_VIEW 1
@@ -441,9 +487,11 @@ extern Object workob;
#define OB_LOCK_ROTX 8
#define OB_LOCK_ROTY 16
#define OB_LOCK_ROTZ 32
+#define OB_LOCK_ROT 56
#define OB_LOCK_SCALEX 64
#define OB_LOCK_SCALEY 128
#define OB_LOCK_SCALEZ 256
+#define OB_LOCK_SCALE 448
/* ob->softflag in DNA_object_force.h */
diff --git a/source/blender/makesdna/DNA_particle_types.h b/source/blender/makesdna/DNA_particle_types.h
index 115344bd899..7dd69b2151c 100644
--- a/source/blender/makesdna/DNA_particle_types.h
+++ b/source/blender/makesdna/DNA_particle_types.h
@@ -66,6 +66,8 @@ typedef struct ParticleData {
ParticleKey state; /* normally current global coordinates or */
/* in sticky object space if dead & sticky */
+ ParticleKey prev_state; /* previous state */
+
HairKey *hair; /* hair vertices */
ParticleKey *keys; /* keyed states */
@@ -125,18 +127,18 @@ typedef struct ParticleSettings {
/* general values */
float sta, end, lifetime, randlife;
- float timetweak, jitfac, keyed_time;
+ float timetweak, jitfac, keyed_time, eff_hair, rt;
int totpart, userjit, grid_res;
/* initial velocity factors */
float normfac, obfac, randfac, partfac, tanfac, tanphase, reactfac;
- float rotfac, avefac, phasefac;
+ float avefac, phasefac, randrotfac, randphasefac;
/* physical properties */
float mass, size, randsize, reactshape;
/* global physical properties */
float acc[3], dragfac, brownfac, dampfac;
/* length */
- float length, abslength, randlength, pad;
+ float length, abslength, randlength;
/* children */
int child_nbr, ren_child_nbr;
float parents, childsize, childrandsize;
@@ -166,29 +168,30 @@ typedef struct ParticleSettings {
struct Object *bb_ob;
struct Ipo *ipo;
struct PartDeflect *pd;
+ struct PartDeflect *pd2;
} ParticleSettings;
-typedef struct ParticleSystem{
+typedef struct ParticleSystem{ /* note, make sure all (runtime) are NULL's in copy_particlesystem */
struct ParticleSystem *next, *prev;
- ParticleSettings *part;
-
- ParticleData *particles;
+ ParticleSettings *part; /* particle settings */
- ChildParticle *child;
+ ParticleData *particles; /* (parent) particles */
+ ChildParticle *child; /* child particles */
- struct ParticleEdit *edit;
+ struct ParticleEdit *edit; /* particle editmode (runtime) */
- struct ParticleCacheKey **pathcache;
- struct ParticleCacheKey **childcache;
+ struct ParticleCacheKey **pathcache; /* path cache (runtime) */
+ struct ParticleCacheKey **childcache; /* child cache (runtime) */
+ ListBase pathcachebufs, childcachebufs; /* buffers for the above */
- struct SoftBody *soft;
+ struct SoftBody *soft; /* hair softbody */
struct Object *target_ob;
struct Object *keyed_ob;
struct Object *lattice;
- struct ListBase effectors, reactevents;
+ struct ListBase effectors, reactevents; /* runtime */
float imat[4][4]; /* used for duplicators */
float cfra;
@@ -196,13 +199,16 @@ typedef struct ParticleSystem{
int flag, totpart, totchild, totcached, totchildcache, rt;
short recalc, target_psys, keyed_psys, totkeyed, softflag, bakespace;
- char bb_uvname[3][32];
+ char bb_uvname[3][32]; /* billboard uv name */
/* if you change these remember to update array lengths to PSYS_TOT_VG! */
- short vgroup[11], vg_neg, rt3[2];
+ short vgroup[12], vg_neg, rt3; /* vertex groups */
/* temporary storage during render */
void *renderdata;
+
+ /* point cache */
+ struct PointCache *pointcache;
}ParticleSystem;
/* general particle maximums */
@@ -218,13 +224,14 @@ typedef struct ParticleSystem{
#define PART_EMITTER 0
#define PART_REACTOR 1
#define PART_HAIR 2
+#define PART_FLUID 3
/* part->flag */
#define PART_REACT_STA_END 1
#define PART_REACT_MULTIPLE 2
#define PART_LOOP 4
-#define PART_LOOP_INSTANT 8
+//#define PART_LOOP_INSTANT 8
#define PART_HAIR_GEOMETRY 16
@@ -255,10 +262,13 @@ typedef struct ParticleSystem{
#define PART_GRID_INVERT (1<<26)
+#define PART_CHILD_EFFECT (1<<27)
#define PART_CHILD_SEAMS (1<<28)
#define PART_CHILD_RENDER (1<<29)
#define PART_CHILD_GUIDE (1<<30)
+#define PART_SELF_EFFECT (1<<22)
+
/* part->rotfrom */
#define PART_ROT_KEYS 0 /* interpolate directly from keys */
#define PART_ROT_ZINCR 1 /* same as zdir but done incrementally from previous position */
@@ -288,8 +298,6 @@ typedef struct ParticleSystem{
#define PART_KINK_RADIAL 2
#define PART_KINK_WAVE 3
#define PART_KINK_BRAID 4
-#define PART_KINK_ROT 5
-#define PART_KINK_ROLL 6
/* part->draw */
#define PART_DRAW_VEL 1
@@ -352,12 +360,16 @@ typedef struct ParticleSystem{
/* part->rotmode */
#define PART_ROT_NOR 1
#define PART_ROT_VEL 2
-#define PART_ROT_RAND 3
+#define PART_ROT_GLOB_X 3
+#define PART_ROT_GLOB_Y 4
+#define PART_ROT_GLOB_Z 5
+#define PART_ROT_OB_X 6
+#define PART_ROT_OB_Y 7
+#define PART_ROT_OB_Z 8
/* part->avemode */
#define PART_AVE_SPIN 1
#define PART_AVE_RAND 2
-#define PART_AVE_VEL 3
/* part->reactevent */
#define PART_EVENT_DEATH 0
@@ -380,7 +392,7 @@ typedef struct ParticleSystem{
//#define PSYS_BAKING 2
//#define PSYS_BAKE_UI 4
#define PSYS_KEYED_TIME 8
-#define PSYS_ENABLED 16
+#define PSYS_ENABLED 16 /* deprecated */
#define PSYS_FIRST_KEYED 32
#define PSYS_DRAWING 64
//#define PSYS_SOFT_BAKE 128
@@ -388,7 +400,8 @@ typedef struct ParticleSystem{
#define PSYS_HAIR_DONE 512
#define PSYS_KEYED 1024
#define PSYS_EDITED 2048
-#define PSYS_PROTECT_CACHE 4096
+//#define PSYS_PROTECT_CACHE 4096
+#define PSYS_DISABLED 8192
/* pars->flag */
#define PARS_UNEXIST 1
@@ -405,9 +418,10 @@ typedef struct ParticleSystem{
#define PARS_DEAD 1
#define PARS_UNBORN 2
#define PARS_ALIVE 3
+#define PARS_DYING 4
/* psys->vg */
-#define PSYS_TOT_VG 11
+#define PSYS_TOT_VG 12
#define PSYS_VG_DENSITY 0
#define PSYS_VG_VEL 1
@@ -420,6 +434,7 @@ typedef struct ParticleSystem{
#define PSYS_VG_SIZE 8
#define PSYS_VG_TAN 9
#define PSYS_VG_ROT 10
+#define PSYS_VG_EFFECTOR 11
/* part->boidrules */
#define BOID_TOT_RULES 8
diff --git a/source/blender/makesdna/DNA_scene_types.h b/source/blender/makesdna/DNA_scene_types.h
index eef665bc290..6563f56ed4d 100644
--- a/source/blender/makesdna/DNA_scene_types.h
+++ b/source/blender/makesdna/DNA_scene_types.h
@@ -98,6 +98,7 @@ typedef struct FFMpegCodecData {
int rc_buffer_size;
int mux_packet_size;
int mux_rate;
+ IDProperty *properties;
} FFMpegCodecData;
@@ -117,7 +118,11 @@ typedef struct SceneRenderLayer {
struct Group *light_override;
unsigned int lay; /* scene->lay itself has priority over this */
+ unsigned int lay_zmask; /* has to be after lay, this is for Z-masking */
int layflag;
+
+ int pad;
+
int passflag; /* pass_xor has to be after passflag */
int pass_xor;
} SceneRenderLayer;
@@ -131,9 +136,11 @@ typedef struct SceneRenderLayer {
#define SCE_LAY_STRAND 32
/* flags between 32 and 0x8000 are set to 1 already, for future options */
-#define SCE_LAY_ALL_Z 0x8000
-#define SCE_LAY_XOR 0x10000
-#define SCE_LAY_DISABLE 0x20000
+#define SCE_LAY_ALL_Z 0x8000
+#define SCE_LAY_XOR 0x10000
+#define SCE_LAY_DISABLE 0x20000
+#define SCE_LAY_ZMASK 0x40000
+#define SCE_LAY_NEG_ZMASK 0x80000
/* srl->passflag */
#define SCE_PASS_COMBINED 1
@@ -150,6 +157,8 @@ typedef struct SceneRenderLayer {
#define SCE_PASS_INDEXOB 2048
#define SCE_PASS_UV 4096
#define SCE_PASS_RADIO 8192
+#define SCE_PASS_MIST 16384
+
/* note, srl->passflag is treestore element 'nr' in outliner, short still... */
@@ -191,14 +200,6 @@ typedef struct RenderData {
*/
short ysch;
/**
- * Adjustment factors for the aspect ratio in the x direction
- */
- short xasp;
- /**
- * Adjustment factors for the aspect ratio in the x direction
- */
- short yasp;
- /**
* The number of part to use in the x direction
*/
short xparts;
@@ -214,10 +215,12 @@ typedef struct RenderData {
short bufflag;
short quality;
+ short rpad, rpad1, rpad2;
+
/**
* Flags for render settings. Use bit-masking to access the settings.
*/
- short scemode;
+ int scemode;
/**
* Flags for render settings. Use bit-masking to access the settings.
@@ -225,7 +228,7 @@ typedef struct RenderData {
int mode;
/* render engine, octree resolution */
- short renderer, ocres, rpad[2];
+ short renderer, ocres;
/**
* What to do with the sky/background. Picks sky/premul/key
@@ -247,6 +250,15 @@ typedef struct RenderData {
/* information on different layers to be rendered */
ListBase layers;
short actlay, pad;
+
+ /**
+ * Adjustment factors for the aspect ratio in the x direction, was a short in 2.45
+ */
+ float xasp;
+ /**
+ * Adjustment factors for the aspect ratio in the x direction, was a short in 2.45
+ */
+ float yasp;
float frs_sec_base;
@@ -262,8 +274,8 @@ typedef struct RenderData {
/* Bake Render options */
short bake_osa, bake_filter, bake_mode, bake_flag;
- short bake_normal_space, bpad;
- float bake_maxdist;
+ short bake_normal_space, bake_quad_split;
+ float bake_maxdist, bake_biasdist, bake_pad;
/* yafray: global panel params. TODO: move elsewhere */
short GIquality, GIcache, GImethod, GIphotons, GIdirect;
@@ -271,12 +283,12 @@ typedef struct RenderData {
int GIdepth, GIcausdepth, GIpixelspersample;
int GIphotoncount, GImixphotons;
float GIphotonradius;
- int YF_numprocs, YF_raydepth, YF_AApasses, YF_AAsamples;
+ int YF_raydepth, YF_AApasses, YF_AAsamples, yfpad2;
float GIshadowquality, GIrefinement, GIpower, GIindirpower;
float YF_gamma, YF_exposure, YF_raybias, YF_AApixelsize, YF_AAthreshold;
/* paths to backbufffer, output, ftype */
- char backbuf[160], pic[160], ftype[160];
+ char backbuf[160], pic[160];
/* stamps flags. */
int stamp;
@@ -288,8 +300,31 @@ typedef struct RenderData {
/* foreground/background color. */
float fg_stamp[4];
float bg_stamp[4];
+
+ /* render simplify */
+ int simplify_subsurf;
+ int simplify_shadowsamples;
+ float simplify_particles;
+ float simplify_aosss;
+
+ /* cineon */
+ short cineonwhite, cineonblack;
+ float cineongamma;
} RenderData;
+/* control render convert and shading engine */
+typedef struct RenderProfile {
+ struct RenderProfile *next, *prev;
+ char name[32];
+
+ short particle_perc;
+ short subsurf_max;
+ short shadbufsample_max;
+ short pad1;
+
+ float ao_error, pad2;
+
+} RenderProfile;
typedef struct GameFraming {
float col[3];
@@ -314,7 +349,7 @@ typedef struct ImagePaintSettings {
} ImagePaintSettings;
typedef struct ParticleBrushData {
- short size, strength; /* commong settings */
+ short size, strength; /* common settings */
short step, invert; /* for specific brushes only */
} ParticleBrushData;
@@ -330,6 +365,12 @@ typedef struct ParticleEditSettings {
int draw_timed;
} ParticleEditSettings;
+typedef struct TransformOrientation {
+ struct TransformOrientation *next, *prev;
+ char name[36];
+ float mat[3][3];
+} TransformOrientation;
+
typedef struct ToolSettings {
/* Subdivide Settings */
short cornertype;
@@ -363,7 +404,7 @@ typedef struct ToolSettings {
/* Auto-IK */
short autoik_chainlen;
- /* Image Paint (8 byte aligned please!) */
+ /* Image Paint (8 byttse aligned please!) */
struct ImagePaintSettings imapaint;
/* Particle Editing */
@@ -392,12 +433,20 @@ typedef struct ToolSettings {
float skgen_angle_limit;
float skgen_correlation_limit;
float skgen_symmetry_limit;
+ float skgen_retarget_angle_weight;
+ float skgen_retarget_length_weight;
+ float skgen_retarget_distance_weight;
short skgen_options;
char skgen_postpro;
char skgen_postpro_passes;
char skgen_subdivisions[3];
+ char skgen_multi_level;
+ char skgen_optimisation_method;
- char pad3[5];
+ char tpad[6];
+
+ /* Alt+RMB option */
+ char edge_mode;
} ToolSettings;
/* Used by all brushes to store their properties, which can be directly set
@@ -407,25 +456,31 @@ typedef struct BrushData
{
short size;
char strength, dir; /* Not used for smooth brush */
- char airbrush;
char view;
+ char flag;
char pad[2];
} BrushData;
struct SculptSession;
typedef struct SculptData
{
+ /* Note! all pointers in this struct must be duplicated header_info.c's copy_scene function */
+
/* Data stored only from entering sculptmode until exiting sculptmode */
struct SculptSession *session;
/* Pointers to all of sculptmodes's textures */
- struct MTex *mtex[10];
+ struct MTex *mtex[18];
/* Editable brush shape */
struct CurveMapping *cumap;
/* Settings for each brush */
BrushData drawbrush, smoothbrush, pinchbrush, inflatebrush, grabbrush, layerbrush, flattenbrush;
+
+ /* For rotating around a pivot point */
+ float pivot[3];
+
short brush_type;
/* For the Brush Shape */
@@ -444,10 +499,11 @@ typedef struct SculptData
/* Symmetry is separate from the other BrushData because the same
settings are always used for all brush types */
char symm;
-
+
/* Added to store if the 'Rake' setting has been set */
char rake;
- char pad[7];
+ char axislock;
+ char pad[2];
} SculptData;
typedef struct Scene {
@@ -470,7 +526,9 @@ typedef struct Scene {
float editbutsize; /* size of normals */
short selectmode; /* for mesh only! */
short proportional, prop_mode;
- short automerge, pad5, pad6, pad7;
+ short automerge, pad5, pad6;
+
+ short autokey_mode; /* mode for autokeying (defines in DNA_userdef_types.h */
short use_nodes;
@@ -491,9 +549,10 @@ typedef struct Scene {
ScriptLink scriptlink;
ListBase markers;
+ ListBase transform_spaces;
- short jumpframe, pad1;
- short snap_flag, snap_target;
+ short jumpframe;
+ short snap_mode, snap_flag, snap_target;
/* none of the dependancy graph vars is mean to be saved */
struct DagForest *theDag;
@@ -502,6 +561,10 @@ typedef struct Scene {
/* Sculptmode data */
struct SculptData sculptdata;
+
+ /* frame step. */
+ int frame_step;
+ int pad;
} Scene;
@@ -535,10 +598,17 @@ typedef struct Scene {
#define R_GAUSS 0x20000
/* fbuf obsolete... */
#define R_FBUF 0x40000
- /* threads obsolete... is there for old files */
+ /* threads obsolete... is there for old files, now use for autodetect threads */
#define R_THREADS 0x80000
+ /* Use the same flag for autothreads */
+#define R_FIXED_THREADS 0x80000
+
#define R_SPEED 0x100000
#define R_SSS 0x200000
+#define R_NO_OVERWRITE 0x400000 /* skip existing files */
+#define R_TOUCH 0x800000 /* touch files before rendering */
+#define R_SIMPLIFY 0x1000000
+
/* filtertype */
#define R_FILTER_BOX 0
@@ -554,7 +624,7 @@ typedef struct Scene {
#define R_INTERN 0
#define R_YAFRAY 1
-/* scemode */
+/* scemode (int now) */
#define R_DOSEQ 0x0001
#define R_BG_RENDER 0x0002
/* passepartout is camera option now, keep this for backward compatibility */
@@ -569,8 +639,10 @@ typedef struct Scene {
#define R_EXR_TILE_FILE 0x0400
#define R_COMP_FREE 0x0800
#define R_NO_IMAGE_LOAD 0x1000
-#define R_NO_TEX 0x2000
+#define R_NO_TEX 0x2000
#define R_STAMP_INFO 0x4000
+#define R_FULL_SAMPLE 0x8000
+#define R_COMP_RERENDER 0x10000
/* r->stamp */
#define R_STAMP_TIME 0x0001
@@ -598,7 +670,7 @@ typedef struct Scene {
#define R_TARGA 0
#define R_IRIS 1
#define R_HAMX 2
-#define R_FTYPE 3
+#define R_FTYPE 3 /* ftype is nomore */
#define R_JPEG90 4
#define R_MOVIE 5
#define R_IRIZ 7
@@ -623,12 +695,15 @@ typedef struct Scene {
#define R_OPENEXR_HALF 1
#define R_OPENEXR_ZBUF 2
#define R_PREVIEW_JPG 4
+#define R_CINEON_LOG 8
+#define R_TIFF_16BIT 16
/* bake_mode: same as RE_BAKE_xxx defines */
/* bake_flag: */
#define R_BAKE_CLEAR 1
#define R_BAKE_OSA 2
#define R_BAKE_TO_ACTIVE 4
+#define R_BAKE_NORMALIZE 8
/* bake_normal_space */
#define R_BAKE_SPACE_CAMERA 0
@@ -672,10 +747,16 @@ typedef struct Scene {
/* scene->snap_flag */
#define SCE_SNAP 1
+#define SCE_SNAP_ROTATE 2
/* scene->snap_target */
#define SCE_SNAP_TARGET_CLOSEST 0
#define SCE_SNAP_TARGET_CENTER 1
#define SCE_SNAP_TARGET_MEDIAN 2
+#define SCE_SNAP_TARGET_ACTIVE 3
+/* scene->snap_mode */
+#define SCE_SNAP_MODE_VERTEX 0
+#define SCE_SNAP_MODE_EDGE 1
+#define SCE_SNAP_MODE_FACE 2
/* sce->selectmode */
#define SCE_SELECT_VERTEX 1 /* for mesh */
@@ -713,6 +794,9 @@ typedef struct Scene {
#define FFMPEG_MULTIPLEX_AUDIO 1
#define FFMPEG_AUTOSPLIT_OUTPUT 2
+/* Sculpt brush flags */
+#define SCULPT_BRUSH_AIRBRUSH 1
+#define SCULPT_BRUSH_ANCHORED 2
/* SculptData.flags */
#define SCULPT_INPUT_SMOOTH 1
#define SCULPT_DRAW_FAST 2
@@ -734,11 +818,27 @@ typedef struct Scene {
#define SYMM_Y 2
#define SYMM_Z 4
+#define AXISLOCK_X 1
+#define AXISLOCK_Y 2
+#define AXISLOCK_Z 4
+
/* toolsettings->imagepaint_flag */
#define IMAGEPAINT_DRAWING 1
#define IMAGEPAINT_DRAW_TOOL 2
#define IMAGEPAINT_DRAW_TOOL_DRAWING 4
+/* toolsettings->uvcalc_flag */
+#define UVCALC_FILLHOLES 1
+#define UVCALC_NO_ASPECT_CORRECT 2 /* would call this UVCALC_ASPECT_CORRECT, except it should be default with old file */
+#define UVCALC_TRANSFORM_CORRECT 4 /* adjust UV's while transforming to avoid distortion */
+
+/* toolsettings->edge_mode */
+#define EDGE_MODE_SELECT 0
+#define EDGE_MODE_TAG_SEAM 1
+#define EDGE_MODE_TAG_SHARP 2
+#define EDGE_MODE_TAG_CREASE 3
+#define EDGE_MODE_TAG_BEVEL 4
+
/* toolsettings->particle flag */
#define PE_KEEP_LENGTHS 1
#define PE_LOCK_FIRST 2
@@ -771,12 +871,21 @@ typedef struct Scene {
#define RETOPO_ELLIPSE 4
/* toolsettings->skgen_options */
-#define SKGEN_FILTER_INTERNAL 1
-#define SKGEN_FILTER_EXTERNAL 2
-#define SKGEN_SYMMETRY 4
-#define SKGEN_CUT_LENGTH 8
-#define SKGEN_CUT_ANGLE 16
-#define SKGEN_CUT_CORRELATION 32
+#define SKGEN_FILTER_INTERNAL (1 << 0)
+#define SKGEN_FILTER_EXTERNAL (1 << 1)
+#define SKGEN_SYMMETRY (1 << 2)
+#define SKGEN_CUT_LENGTH (1 << 3)
+#define SKGEN_CUT_ANGLE (1 << 4)
+#define SKGEN_CUT_CORRELATION (1 << 5)
+#define SKGEN_HARMONIC (1 << 6)
+#define SKGEN_STICK_TO_EMBEDDING (1 << 7)
+#define SKGEN_ADAPTIVE_DISTANCE (1 << 8)
+#define SKGEN_FILTER_SMART (1 << 9)
+#define SKGEN_DISP_LENGTH (1 << 10)
+#define SKGEN_DISP_WEIGHT (1 << 11)
+#define SKGEN_DISP_ORIG (1 << 12)
+#define SKGEN_DISP_EMBED (1 << 13)
+#define SKGEN_DISP_INDEX (1 << 14)
#define SKGEN_SUB_LENGTH 0
#define SKGEN_SUB_ANGLE 1
diff --git a/source/blender/makesdna/DNA_screen_types.h b/source/blender/makesdna/DNA_screen_types.h
index c5ec847608f..40374f56967 100644
--- a/source/blender/makesdna/DNA_screen_types.h
+++ b/source/blender/makesdna/DNA_screen_types.h
@@ -6,7 +6,7 @@
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
+ * of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -20,7 +20,6 @@
* The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
* All rights reserved.
*
- *
* Contributor(s): Blender Foundation
*
* ***** END GPL LICENSE BLOCK *****
diff --git a/source/blender/makesdna/DNA_scriptlink_types.h b/source/blender/makesdna/DNA_scriptlink_types.h
index 85e0f237d69..95e20dd004d 100644
--- a/source/blender/makesdna/DNA_scriptlink_types.h
+++ b/source/blender/makesdna/DNA_scriptlink_types.h
@@ -58,6 +58,9 @@ typedef struct ScriptLink {
* RENDER script links for clean-up actions */
#define SCRIPT_POSTRENDER 32
+#define SCRIPT_OBJECTUPDATE 64
+#define SCRIPT_OBDATAUPDATE 128
+
/* **************** SPACE HANDLERS ********************* */
/* these are special scriptlinks that can be assigned to
* a given space in a given ScrArea to:
diff --git a/source/blender/makesdna/DNA_sensor_types.h b/source/blender/makesdna/DNA_sensor_types.h
index 90e2b8f9f41..d8a1ffc6c24 100644
--- a/source/blender/makesdna/DNA_sensor_types.h
+++ b/source/blender/makesdna/DNA_sensor_types.h
@@ -82,6 +82,19 @@ typedef struct bPropertySensor {
char maxvalue[32];
} bPropertySensor;
+typedef struct bActuatorSensor {
+ int type;
+ int pad;
+ char name[32];
+} bActuatorSensor;
+
+typedef struct bDelaySensor {
+ short delay;
+ short duration;
+ short flag;
+ short pad;
+} bDelaySensor;
+
typedef struct bCollisionSensor {
char name[32]; /* property name */
char materialName[32]; /* material */
@@ -144,18 +157,18 @@ typedef struct bSensor {
/* just add here, to avoid align errors... */
short invert; /* Whether or not to invert the output. */
- short freq2; /* The negative pulsing frequency? Not used anymore... */
+ short level; /* Whether the sensor is level base (edge by default) */
int pad;
} bSensor;
typedef struct bJoystickSensor {
char name[32];
- short type;
- short pad;
+ char type;
+ char joyindex;
+ short flag;
int axis;
int axisf;
int button;
- int buttonf;
int hat;
int hatf;
int precision;
@@ -197,11 +210,15 @@ typedef struct bJoystickSensor {
#define SENS_RAY 9
#define SENS_MESSAGE 10
#define SENS_JOYSTICK 11
+#define SENS_ACTUATOR 12
+#define SENS_DELAY 13
/* sensor->flag */
#define SENS_SHOW 1
#define SENS_DEL 2
#define SENS_NEW 4
#define SENS_NOT 8
+#define SENS_VISIBLE 16
+#define SENS_PIN 32
/* sensor->pulse */
#define SENS_PULSE_CONT 0
@@ -221,6 +238,9 @@ typedef struct bJoystickSensor {
* */
/* #define SENS_COLLISION_PROPERTY 0 */
#define SENS_COLLISION_MATERIAL 1
+/* ray specific mode */
+/* X-Ray means that the ray will traverse objects that don't have the property/material */
+#define SENS_RAY_XRAY 2
/* Some stuff for the mouse sensor Type: */
#define BL_SENS_MOUSE_LEFT_BUTTON 1
@@ -232,6 +252,8 @@ typedef struct bJoystickSensor {
#define BL_SENS_MOUSE_MOUSEOVER 16
#define BL_SENS_MOUSE_MOUSEOVER_ANY 32
+#define SENS_JOY_ANY_EVENT 1
+
#define SENS_JOY_BUTTON 0
#define SENS_JOY_BUTTON_PRESSED 0
#define SENS_JOY_BUTTON_RELEASED 1
@@ -246,5 +268,9 @@ typedef struct bJoystickSensor {
#define SENS_JOY_HAT 2
#define SENS_JOY_HAT_DIR 0
+
+#define SENS_DELAY_REPEAT 1
+// should match JOYINDEX_MAX in SCA_JoystickDefines.h */
+#define SENS_JOY_MAXINDEX 8
#endif
diff --git a/source/blender/makesdna/DNA_sequence_types.h b/source/blender/makesdna/DNA_sequence_types.h
index cc1213a02a1..7bad8ec3b44 100644
--- a/source/blender/makesdna/DNA_sequence_types.h
+++ b/source/blender/makesdna/DNA_sequence_types.h
@@ -47,19 +47,55 @@ typedef struct StripElem {
typedef struct TStripElem {
struct ImBuf *ibuf;
+ struct ImBuf *ibuf_comp;
struct TStripElem *se1, *se2, *se3;
short ok;
- short pad;
+ short flag;
int nr;
} TStripElem;
+typedef struct StripCrop {
+ int top;
+ int bottom;
+ int left;
+ int right;
+} StripCrop;
+
+typedef struct StripTransform {
+ int xofs;
+ int yofs;
+} StripTransform;
+
+typedef struct StripColorBalance {
+ float lift[3];
+ float gamma[3];
+ float gain[3];
+ int flag;
+ int pad;
+ float exposure;
+ float saturation;
+} StripColorBalance;
+
+typedef struct StripProxy {
+ char dir[160];
+} StripProxy;
+
typedef struct Strip {
struct Strip *next, *prev;
int rt, len, us, done;
+ int startstill, endstill;
StripElem *stripdata;
char dir[160];
int orx, ory;
+ StripProxy *proxy;
+ StripCrop *crop;
+ StripTransform *transform;
+ StripColorBalance *color_balance;
TStripElem *tstripdata;
+ TStripElem *tstripdata_startstill;
+ TStripElem *tstripdata_endstill;
+ struct ImBuf *ibuf_startstill;
+ struct ImBuf *ibuf_endstill;
} Strip;
@@ -93,7 +129,7 @@ typedef struct Sequence {
void *lib; /* needed (to be like ipo), else it will raise libdata warnings, this should never be used */
char name[24]; /* name, not set by default and dosnt need to be unique as with ID's */
- short flag, type; /*flags bitmap (see below) and the type of sequence*/
+ int flag, type; /*flags bitmap (see below) and the type of sequence*/
int len; /* the length of the contense of this strip - before handles are applied */
int start, startofs, endofs;
int startstill, endstill;
@@ -102,6 +138,7 @@ typedef struct Sequence {
float mul, handsize;
/* is sfra needed anymore? - it looks like its only used in one place */
int sfra; /* starting frame according to the timeline of the scene. */
+ int anim_preseek;
Strip *strip;
@@ -125,7 +162,13 @@ typedef struct Sequence {
void *effectdata; /* Struct pointer for effect settings */
- int anim_preseek;
+ int anim_startofs; /* only use part of animation file */
+ int anim_endofs; /* is subtle different to startofs / endofs */
+
+ int blend_mode;
+ float blend_opacity;
+
+ int scenenr; /* for scene selection */
int pad;
} Sequence;
@@ -207,6 +250,18 @@ typedef struct SpeedControlVars {
#define SEQ_FLAG_DELETE 1024
#define SEQ_FLIPX 2048
#define SEQ_FLIPY 4096
+#define SEQ_MAKE_FLOAT 8192
+#define SEQ_LOCK 16384
+#define SEQ_USE_PROXY 32768
+#define SEQ_USE_TRANSFORM 65536
+#define SEQ_USE_CROP 131072
+#define SEQ_USE_COLOR_BALANCE 262144
+#define SEQ_USE_PROXY_CUSTOM_DIR 524288
+#define SEQ_ACTIVE 1048576
+
+#define SEQ_COLOR_BALANCE_INVERSE_GAIN 1
+#define SEQ_COLOR_BALANCE_INVERSE_GAMMA 2
+#define SEQ_COLOR_BALANCE_INVERSE_LIFT 4
/* seq->type WATCH IT: SEQ_EFFECT BIT is used to determine if this is an effect strip!!! */
#define SEQ_IMAGE 0
@@ -232,10 +287,18 @@ typedef struct SpeedControlVars {
#define SEQ_TRANSFORM 27
#define SEQ_COLOR 28
#define SEQ_SPEED 29
+#define SEQ_EFFECT_MAX 29
#define STRIPELEM_FAILED 0
#define STRIPELEM_OK 1
-#define STRIPELEM_META 2
+
+#define STRIPELEM_PREVIEW_DONE 1
+
+#define SEQ_BLEND_REPLACE 0
+/* all other BLEND_MODEs are simple SEQ_EFFECT ids and therefore identical
+ to the table above. (Only those effects that handle _exactly_ two inputs,
+ otherwise, you can't really blend, right :) !)
+*/
#endif
diff --git a/source/blender/makesdna/DNA_space_types.h b/source/blender/makesdna/DNA_space_types.h
index e1b916be814..dc713362d83 100644
--- a/source/blender/makesdna/DNA_space_types.h
+++ b/source/blender/makesdna/DNA_space_types.h
@@ -50,6 +50,7 @@ struct RenderInfo;
struct bNodeTree;
struct uiBlock;
struct FileList;
+struct bGPdata;
/**
* The base structure all the other spaces
@@ -140,11 +141,13 @@ typedef struct SpaceSeq {
View2D v2d;
float xof, yof; /* offset for drawing the image preview */
- short mainb, zoom;
+ short mainb, pad;
short chanshown;
- short pad2;
+ short zebra;
int flag;
- int pad;
+ float zoom;
+
+ struct bGPdata *gpd; /* grease-pencil data */
} SpaceSeq;
typedef struct SpaceFile {
@@ -158,7 +161,7 @@ typedef struct SpaceFile {
int totfile;
char title[24];
- char dir[160];
+ char dir[240];
char file[80];
short type, ofs, flag, sort;
@@ -224,19 +227,19 @@ typedef struct SpaceImage {
short imanr;
short curtile; /* the currently active tile of the image when tile is enabled, is kept in sync with the active faces tile */
int flag;
+ short selectmode;
short imtypenr, lock;
- short showspare, pin;
+ short pin;
float zoom;
char dt_uv; /* UV draw type */
- char sticky; /* sticky selection type */
- char pad[6];
+ char sticky; /* sticky selection type */
+ char dt_uvstretch;
+ char pad[5];
float xof, yof; /* user defined offset, image is centered */
float centx, centy; /* storage for offset while render drawing */
- char *info_str, *info_spare; /* info string for render */
- struct ImBuf *spare;
-
+ struct bGPdata *gpd; /* grease pencil data */
} SpaceImage;
typedef struct SpaceNla {
@@ -263,24 +266,43 @@ typedef struct SpaceText {
struct Text *text;
int top, viewlines;
- short flags, menunr;
-
- int font_id;
+ short flags, menunr;
+ int font_id;
+
int lheight;
int left;
int showlinenrs;
-
int tabnumber;
+
int currtab_set;
int showsyntax;
- int unused_padd;
-
+ int overwrite;
float pix_per_line;
struct rcti txtscroll, txtbar;
+ int wordwrap, doplugins;
+
} SpaceText;
+typedef struct Script {
+ ID id;
+
+ void *py_draw;
+ void *py_event;
+ void *py_button;
+ void *py_browsercallback;
+ void *py_globaldict;
+
+ int flags, lastspace;
+ char scriptname[256]; /* store the script file here so we can re-run it on loading blender, if "Enable Scripts" is on */
+ char scriptarg[256];
+} Script;
+#define SCRIPT_SET_NULL(_script) _script->py_draw = _script->py_event = _script->py_button = _script->py_browsercallback = _script->py_globaldict = NULL; _script->flags = 0;
+#define SCRIPT_RUNNING 0x01
+#define SCRIPT_GUI 0x02
+#define SCRIPT_FILESEL 0x04
+
typedef struct SpaceScript {
SpaceLink *next, *prev;
int spacetype;
@@ -309,6 +331,8 @@ typedef struct SpaceNode {
int spacetype;
float blockscale;
+ short blockhandler[8];
+
View2D v2d;
struct ID *id, *from; /* context, no need to save in file? well... pinning... */
@@ -321,11 +345,13 @@ typedef struct SpaceNode {
struct bNodeTree *nodetree, *edittree;
int treetype, pad; /* treetype: as same nodetree->type */
+ struct bGPdata *gpd; /* grease-pencil data */
} SpaceNode;
/* snode->flag */
#define SNODE_DO_PREVIEW 1
#define SNODE_BACKDRAW 2
+#define SNODE_DISPGP 4
typedef struct SpaceImaSel {
SpaceLink *next, *prev;
@@ -340,7 +366,7 @@ typedef struct SpaceImaSel {
/* specific stuff for drawing */
char title[24];
- char dir[160];
+ char dir[240];
char file[80];
short type, menu, flag, sort;
@@ -404,7 +430,7 @@ typedef struct SpaceImaSel {
/* filesel types */
#define FILE_UNIX 8
-#define FILE_BLENDER 8
+#define FILE_BLENDER 8 /* dont display relative paths */
#define FILE_SPECIAL 9
#define FILE_LOADLIB 1
@@ -450,10 +476,14 @@ typedef struct SpaceImaSel {
#define SI_SHOW 1
/* SpaceImage->dt_uv */
-#define SI_UVDT_DASH 0
-#define SI_UVDT_BLACK 1
-#define SI_UVDT_WHITE 2
-#define SI_UVDT_OUTLINE 3
+#define SI_UVDT_OUTLINE 0
+#define SI_UVDT_DASH 1
+#define SI_UVDT_BLACK 2
+#define SI_UVDT_WHITE 3
+
+/* SpaceImage->dt_uvstretch */
+#define SI_UVDT_STRETCH_ANGLE 0
+#define SI_UVDT_STRETCH_AREA 1
/* SpaceImage->sticky
* Note DISABLE should be 0, however would also need to re-arrange icon order,
@@ -462,6 +492,12 @@ typedef struct SpaceImaSel {
#define SI_STICKY_DISABLE 1
#define SI_STICKY_VERTEX 2
+/* SpaceImage->selectmode */
+#define SI_SELECT_VERTEX 0
+#define SI_SELECT_EDGE 1 /* not implemented */
+#define SI_SELECT_FACE 2
+#define SI_SELECT_ISLAND 3
+
/* SpaceImage->flag */
#define SI_BE_SQUARE 1<<0
#define SI_EDITTILE 1<<1
@@ -469,7 +505,7 @@ typedef struct SpaceImaSel {
#define SI_DRAWTOOL 1<<3
#define SI_DEPRECATED1 1<<4 /* stick UVs to others in the same location */
#define SI_DRAWSHADOW 1<<5
-#define SI_SELACTFACE 1<<6
+#define SI_SELACTFACE 1<<6 /* deprecated */
#define SI_DEPRECATED2 1<<7
#define SI_DEPRECATED3 1<<8 /* stick UV selection to mesh vertex (UVs wont always be touching) */
#define SI_COORDFLOATS 1<<9
@@ -486,7 +522,13 @@ typedef struct SpaceImaSel {
/* this means that the image is drawn until it reaches the view edge,
* in the image view, its unrelated to the 'tile' mode for texface */
#define SI_DRAW_TILE 1<<19
-#define SI_SMOOTH_UV 1<<20
+#define SI_SMOOTH_UV 1<<20
+#define SI_DRAW_STRETCH 1<<21
+#define SI_DISPGP 1<<22
+
+/* SpaceIpo->flag */
+#define SIPO_LOCK_VIEW 1<<0
+#define SIPO_NOTRANSKEYCULL 1<<1
/* SpaceText flags (moved from DNA_text_types.h) */
@@ -520,6 +562,7 @@ typedef struct SpaceImaSel {
#define OOPS_IM 4096
#define OOPS_AR 8192
#define OOPS_GR 16384
+#define OOPS_CA 32768
/* SpaceOops->outlinevis */
#define SO_ALL_SCENES 0
@@ -532,6 +575,7 @@ typedef struct SpaceImaSel {
#define SO_LIBRARIES 7
#define SO_VERSE_SESSION 8
#define SO_VERSE_MS 9
+#define SO_SEQUENCE 10
/* SpaceOops->storeflag */
#define SO_TREESTORE_CLEANUP 1
@@ -578,6 +622,7 @@ typedef struct SpaceImaSel {
#define SNLA_ALLKEYED 1
#define SNLA_ACTIVELAYERS 2
#define SNLA_DRAWTIME 4
+#define SNLA_NOTRANSKEYCULL 8
/* time->flag */
/* show timing in frames instead of in seconds */
@@ -595,16 +640,21 @@ typedef struct SpaceImaSel {
#define TIME_WITH_SEQ_AUDIO 16
#define TIME_SEQ 32
#define TIME_ALL_IMAGE_WIN 64
+#define TIME_CONTINUE_PHYSICS 128
/* sseq->mainb */
#define SEQ_DRAW_SEQUENCE 0
#define SEQ_DRAW_IMG_IMBUF 1
#define SEQ_DRAW_IMG_WAVEFORM 2
#define SEQ_DRAW_IMG_VECTORSCOPE 3
+#define SEQ_DRAW_IMG_HISTOGRAM 4
/* sseq->flag */
-#define SEQ_DRAWFRAMES 1
+#define SEQ_DRAWFRAMES 1
#define SEQ_MARKER_TRANS 2
+#define SEQ_DRAW_COLOR_SEPERATED 4
+#define SEQ_DRAW_SAFE_MARGINS 8
+#define SEQ_DRAW_GPENCIL 16
/* space types, moved from DNA_screen_types.h */
enum {
diff --git a/source/blender/makesdna/DNA_text_types.h b/source/blender/makesdna/DNA_text_types.h
index d1859d22115..48ecccd517a 100644
--- a/source/blender/makesdna/DNA_text_types.h
+++ b/source/blender/makesdna/DNA_text_types.h
@@ -38,25 +38,36 @@ typedef struct TextLine {
struct TextLine *next, *prev;
char *line;
- char *format;
- int len, blen;
+ char *format; /* may be NULL if syntax is off or not yet formatted */
+ int len, blen; /* blen unused */
} TextLine;
+typedef struct TextMarker {
+ struct TextMarker *next, *prev;
+
+ int lineno, start, end, pad1; /* line number and start/end character indices */
+
+ int group, flags; /* see BKE_text.h for flag defines */
+ char color[4], pad[4]; /* draw color of the marker */
+} TextMarker;
+
typedef struct Text {
ID id;
char *name;
-
+
int flags, nlines;
ListBase lines;
TextLine *curl, *sell;
int curc, selc;
+ ListBase markers;
char *undo_buf;
int undo_pos, undo_len;
void *compiled;
+ double mtime;
} Text;
@@ -74,4 +85,12 @@ typedef struct Text {
#define TXT_READONLY 0x0100
#define TXT_FOLLOW 0x0200 /* always follow cursor (console) */
+/* format continuation flags */
+#define TXT_NOCONT 0x00 /* no continuation */
+#define TXT_SNGQUOTSTR 0x01 /* single quotes */
+#define TXT_DBLQUOTSTR 0x02 /* double quotes */
+#define TXT_TRISTR 0x04 /* triplets of quotes: """ or ''' */
+#define TXT_SNGTRISTR 0x05 /*(TXT_TRISTR | TXT_SNGQUOTSTR)*/
+#define TXT_DBLTRISTR 0x06 /*(TXT_TRISTR | TXT_DBLQUOTSTR)*/
+
#endif
diff --git a/source/blender/makesdna/DNA_texture_types.h b/source/blender/makesdna/DNA_texture_types.h
index bee341acf2e..111dc08ee02 100644
--- a/source/blender/makesdna/DNA_texture_types.h
+++ b/source/blender/makesdna/DNA_texture_types.h
@@ -245,6 +245,7 @@ typedef struct TexMapping {
#define TEX_CALCALPHA 32
#define TEX_NORMALMAP 2048
#define TEX_GAUSS_MIP 4096
+#define TEX_FILTER_MIN 8192
/* imaflag unused, only for version check */
#define TEX_FIELDS_ 8
@@ -343,11 +344,13 @@ typedef struct TexMapping {
#define PROJ_Z 3
/* texflag */
-#define MTEX_RGBTOINT 1
-#define MTEX_STENCIL 2
-#define MTEX_NEGATIVE 4
-#define MTEX_ALPHAMIX 8
-#define MTEX_VIEWSPACE 16
+#define MTEX_RGBTOINT 1
+#define MTEX_STENCIL 2
+#define MTEX_NEGATIVE 4
+#define MTEX_ALPHAMIX 8
+#define MTEX_VIEWSPACE 16
+#define MTEX_DUPLI_MAPTO 32
+#define MTEX_OB_DUPLI_ORIG 64
/* blendtype */
#define MTEX_BLEND 0
@@ -360,6 +363,11 @@ typedef struct TexMapping {
#define MTEX_LIGHT 7
#define MTEX_SCREEN 8
#define MTEX_OVERLAY 9
+#define MTEX_BLEND_HUE 10
+#define MTEX_BLEND_SAT 11
+#define MTEX_BLEND_VAL 12
+#define MTEX_BLEND_COLOR 13
+#define MTEX_NUM_BLENDTYPES 14
/* **************** EnvMap ********************* */
diff --git a/source/blender/makesdna/DNA_userdef_types.h b/source/blender/makesdna/DNA_userdef_types.h
index 0f04528130e..fbd962f9372 100644
--- a/source/blender/makesdna/DNA_userdef_types.h
+++ b/source/blender/makesdna/DNA_userdef_types.h
@@ -61,7 +61,6 @@ typedef struct ThemeUI {
char but_drawtype;
char pad[3];
char iconfile[80]; // FILE_MAXFILE length
-
} ThemeUI;
/* try to put them all in one, if needed a special struct can be created as well
@@ -102,16 +101,28 @@ typedef struct ThemeSpace {
char movie[4], image[4], scene[4], audio[4]; // for sequence editor
char effect[4], plugin[4], transition[4], meta[4];
char editmesh_active[4];
+
+ char handle_vertex[4];
+ char handle_vertex_select[4];
+ char handle_vertex_size;
+ char hpad[7];
} ThemeSpace;
+
/* set of colors for use as a custom color set for Objects/Bones wire drawing */
typedef struct ThemeWireColor {
- char unselected[3];
- char selected[3];
- char active[3];
- char pad[7];
+ char solid[4];
+ char select[4];
+ char active[4];
+
+ short flag;
+ short pad;
} ThemeWireColor;
+/* flags for ThemeWireColor */
+#define TH_WIRECOLOR_CONSTCOLS (1<<0)
+#define TH_WIRECOLOR_TEXTCOLS (1<<1)
+
/* A theme */
typedef struct bTheme {
struct bTheme *next, *prev;
@@ -177,7 +188,9 @@ typedef struct UserDef {
char fontname[256]; // FILE_MAXDIR+FILE length
struct ListBase themes;
short undosteps;
- short curssize;
+ short undomemory;
+ short gp_manhattendist, gp_euclideandist, gp_eraser;
+ short gp_settings;
short tb_leftmouse, tb_rightmouse;
struct SolidLight light[3];
short tw_hotspot, tw_flag, tw_handlesize, tw_size;
@@ -192,9 +205,15 @@ typedef struct UserDef {
short recent_files; /* maximum number of recently used files to remember */
short smooth_viewtx; /* miliseconds to spend spinning the view */
short glreslimit;
+ short ndof_pan, ndof_rotate;
+ short curssize, pad;
+// char pad[8];
char versemaster[160];
char verseuser[160];
- float glalphaclip, pad;
+ float glalphaclip;
+
+ short autokey_mode; /* autokeying mode */
+ short autokey_flag; /* flags for autokeying */
struct ColorBand coba_weight; /* from texture.h */
} UserDef;
@@ -213,7 +232,7 @@ extern UserDef U; /* from usiblender.c !!!! */
#define USER_DUPLILINK (1 << 6)
#define USER_FSCOLLUM (1 << 7)
#define USER_MAT_ON_OB (1 << 8)
-#define USER_NO_CAPSLOCK (1 << 9)
+/*#define USER_NO_CAPSLOCK (1 << 9)*/ /* not used anywhere */
#define USER_VIEWMOVE (1 << 10)
#define USER_TOOLTIPS (1 << 11)
#define USER_TWOBUTTONMOUSE (1 << 12)
@@ -224,8 +243,9 @@ extern UserDef U; /* from usiblender.c !!!! */
#define USER_CUSTOM_RANGE (1 << 17)
#define USER_ADD_EDITMODE (1 << 18)
#define USER_ADD_VIEWALIGNED (1 << 19)
-#define USER_ADD_VIEWALIGNED (1 << 19)
-
+#define USER_RELPATHS (1 << 20)
+#define USER_DRAGIMMEDIATE (1 << 21)
+#define USER_DONT_DOSCRIPTLINKS (1 << 22)
/* viewzom */
#define USER_ZOOM_CONT 0
@@ -233,9 +253,8 @@ extern UserDef U; /* from usiblender.c !!!! */
#define USER_ZOOM_DOLLY 2
/* uiflag */
-
-#define USER_KEYINSERTACT (1 << 0)
-#define USER_KEYINSERTOBJ (1 << 1)
+// old flag for #define USER_KEYINSERTACT (1 << 0)
+// old flag for #define USER_KEYINSERTOBJ (1 << 1)
#define USER_WHEELZOOMDIR (1 << 2)
#define USER_FILTERFILEEXTS (1 << 3)
#define USER_DRAWVIEWINFO (1 << 4)
@@ -249,16 +268,30 @@ extern UserDef U; /* from usiblender.c !!!! */
#define USER_LOCKAROUND (1 << 12)
#define USER_GLOBALUNDO (1 << 13)
#define USER_ORBIT_SELECTION (1 << 14)
-#define USER_KEYINSERTAVAI (1 << 15)
+// old flag for #define USER_KEYINSERTAVAI (1 << 15)
+#define USER_ORBIT_ZBUF (1 << 15)
#define USER_HIDE_DOT (1 << 16)
#define USER_SHOW_ROTVIEWICON (1 << 17)
#define USER_SHOW_VIEWPORTNAME (1 << 18)
-#define USER_KEYINSERTNEED (1 << 19)
+// old flag for #define USER_KEYINSERTNEED (1 << 19)
#define USER_ZOOM_TO_MOUSEPOS (1 << 20)
-#define USER_SHOW_FPS (1 << 21)
+#define USER_SHOW_FPS (1 << 21)
+#define USER_MMB_PASTE (1 << 22)
-/* transopts */
+/* Auto-Keying mode */
+ /* AUTOKEY_ON is a bitflag */
+#define AUTOKEY_ON 1
+ /* AUTOKEY_ON + 2**n... (i.e. AUTOKEY_MODE_NORMAL = AUTOKEY_ON + 2) to preserve setting, even when autokey turned off */
+#define AUTOKEY_MODE_NORMAL 3
+#define AUTOKEY_MODE_EDITKEYS 5
+
+/* Auto-Keying flag */
+#define AUTOKEY_FLAG_INSERTAVAIL (1<<0)
+#define AUTOKEY_FLAG_INSERTNEEDED (1<<1)
+#define AUTOKEY_FLAG_AUTOMATKEY (1<<2)
+
+/* transopts */
#define USER_TR_TOOLTIPS (1 << 0)
#define USER_TR_BUTTONS (1 << 1)
#define USER_TR_MENUS (1 << 2)
@@ -269,7 +302,6 @@ extern UserDef U; /* from usiblender.c !!!! */
#define CONVERT_TO_UTF8 (1 << 7)
/* dupflag */
-
#define USER_DUP_MESH (1 << 0)
#define USER_DUP_CURVE (1 << 1)
#define USER_DUP_SURF (1 << 2)
@@ -283,18 +315,20 @@ extern UserDef U; /* from usiblender.c !!!! */
#define USER_DUP_ACT (1 << 10)
/* gameflags */
-
-#define USER_VERTEX_ARRAYS 1
+#define USER_DEPRECATED_FLAG 1
#define USER_DISABLE_SOUND 2
#define USER_DISABLE_MIPMAP 4
/* vrml flag */
-
#define USER_VRML_LAYERS 1
#define USER_VRML_AUTOSCALE 2
#define USER_VRML_TWOSIDED 4
/* tw_flag (transform widget) */
+/* gp_settings (Grease Pencil Settings) */
+#define GP_PAINT_DOSMOOTH (1<<0)
+#define GP_PAINT_DOSIMPLIFY (1<<1)
+
#endif
diff --git a/source/blender/makesdna/DNA_view3d_types.h b/source/blender/makesdna/DNA_view3d_types.h
index 987a12965fb..f1fa8c19199 100644
--- a/source/blender/makesdna/DNA_view3d_types.h
+++ b/source/blender/makesdna/DNA_view3d_types.h
@@ -40,6 +40,7 @@ struct Base;
struct BoundBox;
struct RenderInfo;
struct RetopoViewData;
+struct bGPdata;
/* This is needed to not let VC choke on near and far... old
* proprietary MS extensions... */
@@ -53,9 +54,12 @@ struct RetopoViewData;
#include "DNA_listBase.h"
#include "DNA_image_types.h"
+/* ******************************** */
+
/* The near/far thing is a Win EXCEPTION. Thus, leave near/far in the
* code, and patch for windows. */
-
+
+/* Background Picture in 3D-View */
typedef struct BGpic {
struct Image *ima;
struct ImageUser iuser;
@@ -63,6 +67,9 @@ typedef struct BGpic {
short xim, yim;
} BGpic;
+/* ********************************* */
+
+/* 3D ViewPort Struct */
typedef struct View3D {
struct SpaceLink *next, *prev;
int spacetype;
@@ -78,13 +85,9 @@ typedef struct View3D {
float winmat1[4][4]; // persp(1) storage, for swap matrices
float viewmat1[4][4];
- float viewquat[4], dist, zfac, pad0; /* zfac is initgrabz() result */
+ float viewquat[4], dist, zfac; /* zfac is initgrabz() result */
+ int lay_used; /* used while drawing */
- /**
- * 0 - ortho
- * 1 - do 3d perspective
- * 2 - use the camera
- */
short persp;
short view;
@@ -99,7 +102,7 @@ typedef struct View3D {
/**
* The drawing mode for the 3d display. Set to OB_WIRE, OB_SOLID,
- * OB_SHADED or OB_TEXTURED */
+ * OB_SHADED or OB_TEXTURE */
short drawtype;
short localview;
int lay, layact;
@@ -133,14 +136,22 @@ typedef struct View3D {
short gridsubdiv; /* Number of subdivisions in the grid between each highlighted grid line */
- short pad3;
+ short keyflags; /* flags for display of keyframes */
- short pad2;
+ char ndofmode; /* mode of transform for 6DOF devices -1 not found, 0 normal, 1 fly, 2 ob transform */
+ char ndoffilter; /*filter for 6DOF devices 0 normal, 1 dominant */
void *properties_storage; /* Nkey panel stores stuff here, not in file */
+ struct bGPdata *gpd; /* Grease-Pencil Data (annotation layers) */
+ /* last view */
+ float lviewquat[4];
+ short lpersp, lview;
+
+ short pad5, pad6;
} View3D;
+
/* View3D->flag (short) */
#define V3D_MODE (16+32+64+128+256+512)
#define V3D_DISPIMAGE 1
@@ -160,12 +171,13 @@ typedef struct View3D {
#define V3D_CLIPPING 16384
#define V3D_DRAW_CENTERS 32768
-
/* View3d->flag2 (short) */
+#define V3D_MODE2 (32)
#define V3D_OPP_DIRECTION_NAME 1
#define V3D_FLYMODE 2
#define V3D_DEPRECATED 4 /* V3D_TRANSFORM_SNAP, moved to a scene setting */
#define V3D_SOLID_TEX 8
+#define V3D_DISPGP 16
/* View3D->around */
#define V3D_CENTER 0
@@ -176,9 +188,9 @@ typedef struct View3D {
/* View3d->persp */
-#define V3D_PERSP_ORTHO 0
-#define V3D_PERSP_DO_3D_PERSP 1
-#define V3D_PERSP_USE_THE_CAMERA 2
+#define V3D_ORTHO 0
+#define V3D_PERSP 1
+#define V3D_CAMOB 2
/* View3d->gridflag */
#define V3D_SHOW_FLOOR 1
@@ -196,6 +208,7 @@ typedef struct View3D {
#define V3D_MANIP_LOCAL 1
#define V3D_MANIP_NORMAL 2
#define V3D_MANIP_VIEW 3
+#define V3D_MANIP_CUSTOM 4 /* anything of value 4 or higher is custom */
/* View3d->twflag */
/* USE = user setting, DRAW = based on selection */
@@ -206,3 +219,4 @@ typedef struct View3D {
#endif
+
diff --git a/source/blender/makesdna/DNA_world_types.h b/source/blender/makesdna/DNA_world_types.h
index 4e313570b2b..ab7e25190ad 100644
--- a/source/blender/makesdna/DNA_world_types.h
+++ b/source/blender/makesdna/DNA_world_types.h
@@ -38,7 +38,7 @@ struct Ipo;
struct MTex;
#ifndef MAX_MTEX
-#define MAX_MTEX 10
+#define MAX_MTEX 18
#endif
@@ -101,15 +101,14 @@ typedef struct World {
float aodist, aodistfac, aoenergy, aobias;
short aomode, aosamp, aomix, aocolor;
float ao_adapt_thresh, ao_adapt_speed_fac;
- float pad2[2];
- short ao_samp_method;
- short pad1[3];
+ float ao_approx_error, ao_approx_correction;
+ short ao_samp_method, ao_gather_method, ao_approx_passes, pad1;
float *aosphere, *aotables;
struct Ipo *ipo;
- struct MTex *mtex[10];
+ struct MTex *mtex[18]; /* MAX_MTEX */
/* previews */
struct PreviewImage *preview;
@@ -148,12 +147,17 @@ typedef struct World {
/* aomode (use distances & random sampling modes) */
#define WO_AODIST 1
#define WO_AORNDSMP 2
+#define WO_AOCACHE 4
/* aocolor */
#define WO_AOPLAIN 0
#define WO_AOSKYCOL 1
#define WO_AOSKYTEX 2
+/* ao_gather_method */
+#define WO_AOGATHER_RAYTRACE 0
+#define WO_AOGATHER_APPROX 1
+
/* texco (also in DNA_material_types.h) */
#define TEXCO_ANGMAP 64
#define TEXCO_H_SPHEREMAP 256
diff --git a/source/blender/makesdna/intern/CMakeLists.txt b/source/blender/makesdna/intern/CMakeLists.txt
index d4b222f3644..a85f561da92 100644
--- a/source/blender/makesdna/intern/CMakeLists.txt
+++ b/source/blender/makesdna/intern/CMakeLists.txt
@@ -24,7 +24,7 @@
#
# ***** END GPL LICENSE BLOCK *****
-SET(SRC makesdna.c ../../../../intern/guardedalloc/intern/mallocn.c)
+SET(SRC makesdna.c ../../../../intern/guardedalloc/intern/mallocn.c ../../../../intern/guardedalloc/intern/mmap_win.c)
INCLUDE_DIRECTORIES(../../../../intern/guardedalloc ..)
diff --git a/source/blender/makesdna/intern/SConscript b/source/blender/makesdna/intern/SConscript
index 23d6f84942f..b7d55a0ca1a 100644
--- a/source/blender/makesdna/intern/SConscript
+++ b/source/blender/makesdna/intern/SConscript
@@ -15,31 +15,36 @@ dna = env.Clone()
makesdna_tool.Append(CCFLAGS = '-DBASE_HEADER="\\"source/blender/makesdna/\\"" ')
makesdna_tool.Append (CPPPATH = ['#/intern/guardedalloc',
- '../../makesdna'])
+ '../../makesdna'])
if env['OURPLATFORM'] == 'linuxcross':
- makesdna_tool.Replace(CC='gcc')
- makesdna_tool.Replace(AR='ar')
- makesdna_tool.Replace(LINK='gcc')
+ makesdna_tool.Replace(CC='gcc')
+ makesdna_tool.Replace(AR='ar')
+ makesdna_tool.Replace(LINK='gcc')
if sys.platform != 'cygwin':
- makesdna_tool.Append (CCFLAGS = cflags)
+ makesdna_tool.Append (CCFLAGS = cflags)
makesdna_tool.Append (CPPDEFINES = defines)
-makesdna_tool.Append (LIBPATH = '#'+root_build_dir+'/lib')
+targetdir = root_build_dir+'/lib'
+if not (root_build_dir[0]==os.sep or root_build_dir[1]==':'):
+ targetdir = '#'+targetdir
+makesdna_tool.Append (LIBPATH = targetdir)
if env['BF_PROFILE']:
makesdna_tool.Append (LINKFLAGS = env['BF_PROFILE_FLAGS'])
-if env['OURPLATFORM'] == 'linux2' and root_build_dir[0]==os.sep:
- makesdna = makesdna_tool.Program (target = root_build_dir+'/makesdna', source = source_files, LIBS=['bf_guardedalloc'])
-else:
- makesdna = makesdna_tool.Program (target = '#'+root_build_dir+'/makesdna', source = source_files, LIBS=['bf_guardedalloc'])
+targetdir = root_build_dir + '/makesdna'
+
+if not (root_build_dir[0]==os.sep or root_build_dir[1]==':'):
+ targetdir = '#' + targetdir
+
+makesdna = makesdna_tool.Program (target = targetdir, source = source_files, LIBS=['bf_guardedalloc'])
dna_dict = dna.Dictionary()
dna.Depends ('dna.c', makesdna)
dna.Depends ('dna.c', header_files)
if env['OURPLATFORM'] != 'linuxcross':
- dna.Command ('dna.c', '', root_build_dir+os.sep+"makesdna $TARGET")
+ dna.Command ('dna.c', '', root_build_dir+os.sep+"makesdna $TARGET")
else:
- dna.Command ('dna.c', '', root_build_dir+os.sep+"makesdna.exe $TARGET")
+ dna.Command ('dna.c', '', root_build_dir+os.sep+"makesdna.exe $TARGET")
obj = ['intern/dna.c', 'intern/dna_genfile.c']
Return ('obj')
diff --git a/source/blender/makesdna/intern/makesdna.c b/source/blender/makesdna/intern/makesdna.c
index 87f99896654..dd5aa518e24 100644
--- a/source/blender/makesdna/intern/makesdna.c
+++ b/source/blender/makesdna/intern/makesdna.c
@@ -55,6 +55,8 @@
#include "MEM_guardedalloc.h"
#include "DNA_sdna_types.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
@@ -125,6 +127,8 @@ char *includefiles[] = {
"DNA_brush_types.h",
"DNA_customdata_types.h",
"DNA_particle_types.h",
+ "DNA_cloth_types.h",
+ "DNA_gpencil_types.h",
// if you add files here, please add them at the end
// of makesdna.c (this file) as well
"DNA_windowmanager_types.h",
@@ -688,18 +692,18 @@ static int calculate_structlens(int firststruct)
/* 4-8 aligned/ */
if(sizeof(void *) == 4) {
if (len % 4) {
- printf("Align pointer error in struct: %s %s\n", types[structtype], cp);
+ printf("Align pointer error in struct (len4): %s %s\n", types[structtype], cp);
dna_error = 1;
}
} else {
if (len % 8) {
- printf("Align pointer error in struct: %s %s\n", types[structtype], cp);
+ printf("Align pointer error in struct (len8): %s %s\n", types[structtype], cp);
dna_error = 1;
}
}
if (alphalen % 8) {
- printf("Align pointer error in struct: %s %s\n", types[structtype],cp);
+ printf("Align pointer error in struct (alphalen8): %s %s\n", types[structtype],cp);
dna_error = 1;
}
@@ -748,13 +752,13 @@ static int calculate_structlens(int firststruct)
// has_pointer is set or alphalen != len
if (has_pointer || alphalen != len) {
if (alphalen % 8) {
- printf("Sizeerror in struct: %s (add %d bytes)\n", types[structtype], alphalen%8);
+ printf("Sizeerror 8 in struct: %s (add %d bytes)\n", types[structtype], alphalen%8);
dna_error = 1;
}
}
if(len % 4) {
- printf("Sizeerror in struct: %s (add %d bytes)\n", types[structtype], len%4);
+ printf("Sizeerror 4 in struct: %s (add %d bytes)\n", types[structtype], len%4);
dna_error = 1;
}
@@ -954,7 +958,7 @@ int make_structDNA(char *baseDirectory, FILE *file)
/* calculate size of datablock with strings */
cp= names[nr_names-1];
cp+= strlen(names[nr_names-1]) + 1; /* +1: null-terminator */
- len= (long) (cp - (char*) names[0]);
+ len= (intptr_t) (cp - (char*) names[0]);
len= (len+3) & ~3;
dna_write(file, names[0], len);
@@ -967,7 +971,7 @@ int make_structDNA(char *baseDirectory, FILE *file)
/* calculate datablock size */
cp= types[nr_types-1];
cp+= strlen(types[nr_types-1]) + 1; /* +1: null-terminator */
- len= (long) (cp - (char*) types[0]);
+ len= (intptr_t) (cp - (char*) types[0]);
len= (len+3) & ~3;
dna_write(file, types[0], len);
@@ -989,7 +993,7 @@ int make_structDNA(char *baseDirectory, FILE *file)
/* calc datablock size */
sp= structs[nr_structs-1];
sp+= 2+ 2*( sp[1] );
- len= (long) ((char*) sp - (char*) structs[0]);
+ len= (intptr_t) ((char*) sp - (char*) structs[0]);
len= (len+3) & ~3;
dna_write(file, structs[0], len);
@@ -1146,6 +1150,7 @@ int main(int argc, char ** argv)
#include "DNA_brush_types.h"
#include "DNA_customdata_types.h"
#include "DNA_particle_types.h"
+#include "DNA_cloth_types.h"
+#include "DNA_gpencil_types.h"
#include "DNA_windowmanager_types.h"
-
/* end of list */
diff --git a/source/blender/makesrna/intern/makesrna.c b/source/blender/makesrna/intern/makesrna.c
index 43e03662034..de03fcddd15 100644
--- a/source/blender/makesrna/intern/makesrna.c
+++ b/source/blender/makesrna/intern/makesrna.c
@@ -798,8 +798,7 @@ static void make_bad_file(char *file)
int main(int argc, char **argv)
{
FILE *file;
- int return_status = 0;
- extern int totblock;
+ int totblock, return_status = 0;
if (argc!=2 && argc!=3) {
printf("Usage: %s outfile.c [base directory]\n", argv[0]);
@@ -833,6 +832,7 @@ int main(int argc, char **argv)
}
}
+ totblock= MEM_get_memory_blocks_in_use();
if(totblock!=0) {
printf("Error Totblock: %d\n",totblock);
MEM_printmemlist();
diff --git a/source/blender/nodes/CMP_node.h b/source/blender/nodes/CMP_node.h
index 4b7e721ca57..020bbdebfa2 100644
--- a/source/blender/nodes/CMP_node.h
+++ b/source/blender/nodes/CMP_node.h
@@ -66,6 +66,8 @@ extern bNodeType cmp_node_normalize;
extern bNodeType cmp_node_filter;
extern bNodeType cmp_node_blur;
+extern bNodeType cmp_node_dblur;
+extern bNodeType cmp_node_bilateralblur;
extern bNodeType cmp_node_vecblur;
extern bNodeType cmp_node_dilateerode;
extern bNodeType cmp_node_defocus;
@@ -83,6 +85,7 @@ extern bNodeType cmp_node_sepyuva;
extern bNodeType cmp_node_combyuva;
extern bNodeType cmp_node_sepycca;
extern bNodeType cmp_node_combycca;
+extern bNodeType cmp_node_premulkey;
extern bNodeType cmp_node_diff_matte;
extern bNodeType cmp_node_chroma;
diff --git a/source/blender/nodes/CMakeLists.txt b/source/blender/nodes/CMakeLists.txt
index 0be26622536..7f003cb2b42 100644
--- a/source/blender/nodes/CMakeLists.txt
+++ b/source/blender/nodes/CMakeLists.txt
@@ -26,13 +26,14 @@
FILE(GLOB SRC intern/*.c intern/CMP_nodes/*.c intern/SHD_nodes/*.c)
SET(INC
- . ../../../intern/guardedalloc ../include ../blenlib ../makesdna
+ . ../../../intern/guardedalloc ../editors/include ../blenlib ../makesdna
../python ../render/extern/include ../../../intern/decimation/extern
../imbuf ../avi ../../../intern/elbeem/extern
../../../intern/iksolver/extern ../blenloader ../quicktime
- ../blenkernel ../editors/include
+ ../blenkernel ../../../extern/glew/include ../gpu
${SDL_INC}
${ZLIB_INC}
+ ${PYTHON_INC}
)
IF(WITH_VERSE)
diff --git a/source/blender/nodes/Makefile b/source/blender/nodes/Makefile
index 65a0e591848..57f57ebebfe 100644
--- a/source/blender/nodes/Makefile
+++ b/source/blender/nodes/Makefile
@@ -6,7 +6,7 @@
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
+# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
diff --git a/source/blender/nodes/SConscript b/source/blender/nodes/SConscript
index 746be45eb91..5f7f29dab83 100644
--- a/source/blender/nodes/SConscript
+++ b/source/blender/nodes/SConscript
@@ -7,40 +7,44 @@ sources += env.Glob('intern/SHD_nodes/*.c')
incs = '. ./intern '
incs += '#/intern/guardedalloc ../editors/include ../blenlib ../makesdna'
-incs += ' ../python ../render/extern/include '
+incs += ' ../render/extern/include '
incs += ' ../imbuf ../avi '
-incs += ' ../blenloader ../quicktime'
+incs += ' ../blenloader'
incs += ' ../blenkernel ../renderconverter '
-
-
+incs += ' ../gpu #/extern/glew/include '
incs += ' ' + env['BF_OPENGL_INC']
incs += ' ' + env['BF_ZLIB_INC']
-incs += ' ' + env['BF_SDL_INC']
defs = ''
+if env['WITH_BF_PYTHON']:
+ incs += ' ' + env['BF_PYTHON_INC']
+ incs += ' ../python'
+else:
+ defs += 'DISABLE_PYTHON'
+
if env['WITH_BF_INTERNATIONAL']:
- defs += 'WITH_FREETYPE2'
+ defs += ' WITH_FREETYPE2'
if env['WITH_BF_VERSE']:
- defs += ' WITH_VERSE'
- incs += ' ' + env['BF_VERSE_INCLUDE']
+ defs += ' WITH_VERSE'
+ incs += ' ' + env['BF_VERSE_INCLUDE']
if env['WITH_BF_VERSE']:
- defs += ' WITH_VERSE'
+ defs += ' WITH_VERSE'
-if env['WITH_BF_OPENEXR'] == 1:
- defs += ' WITH_OPENEXR'
+if env['WITH_BF_OPENEXR']:
+ defs += ' WITH_OPENEXR'
-if env['WITH_BF_FFMPEG'] == 1:
- defs += ' WITH_FFMPEG'
- incs += ' ' + env['BF_FFMPEG_INC']
+if env['WITH_BF_FFMPEG']:
+ defs += ' WITH_FFMPEG'
+ incs += ' ' + env['BF_FFMPEG_INC']
-if env['WITH_BF_QUICKTIME'] == 1:
- defs += ' WITH_QUICKTIME'
- incs += ' ' + env['BF_QUICKTIME_INC']
+if env['WITH_BF_QUICKTIME']:
+ defs += ' WITH_QUICKTIME'
+ incs += ' ' + env['BF_QUICKTIME_INC']
-defs += ' WITH_CCGSUBSURF'
+defs += ' WITH_CCGSUBSURF '
env.BlenderLib ( libname = 'bf_nodes', sources = sources, includes = Split(incs), defines = Split(defs), libtype=['core','player'], priority = [80, 15] )
diff --git a/source/blender/nodes/SHD_node.h b/source/blender/nodes/SHD_node.h
index 8064a543ca0..d75d7c9f568 100644
--- a/source/blender/nodes/SHD_node.h
+++ b/source/blender/nodes/SHD_node.h
@@ -56,13 +56,13 @@ extern bNodeType sh_node_curve_rgb;
extern bNodeType sh_node_math;
extern bNodeType sh_node_vect_math;
extern bNodeType sh_node_squeeze;
+extern bNodeType node_dynamic_typeinfo;
extern bNodeType sh_node_material_ext;
extern bNodeType sh_node_invert;
extern bNodeType sh_node_seprgb;
extern bNodeType sh_node_combrgb;
extern bNodeType sh_node_hue_sat;
-
#endif
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_alphaOver.c b/source/blender/nodes/intern/CMP_nodes/CMP_alphaOver.c
index f108098750c..4972ff4ae5a 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_alphaOver.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_alphaOver.c
@@ -47,16 +47,16 @@ static void do_alphaover_premul(bNode *node, float *out, float *src, float *over
if(over[3]<=0.0f) {
QUATCOPY(out, src);
}
- else if(*fac==1.0f && over[3]>=1.0f) {
+ else if(fac[0]==1.0f && over[3]>=1.0f) {
QUATCOPY(out, over);
}
else {
- float mul= 1.0f - *fac*over[3];
+ float mul= 1.0f - fac[0]*over[3];
- out[0]= (mul*src[0]) + *fac*over[0];
- out[1]= (mul*src[1]) + *fac*over[1];
- out[2]= (mul*src[2]) + *fac*over[2];
- out[3]= (mul*src[3]) + *fac*over[3];
+ out[0]= (mul*src[0]) + fac[0]*over[0];
+ out[1]= (mul*src[1]) + fac[0]*over[1];
+ out[2]= (mul*src[2]) + fac[0]*over[2];
+ out[3]= (mul*src[3]) + fac[0]*over[3];
}
}
@@ -67,7 +67,7 @@ static void do_alphaover_key(bNode *node, float *out, float *src, float *over, f
if(over[3]<=0.0f) {
QUATCOPY(out, src);
}
- else if(*fac==1.0f && over[3]>=1.0f) {
+ else if(fac[0]==1.0f && over[3]>=1.0f) {
QUATCOPY(out, over);
}
else {
@@ -81,6 +81,31 @@ static void do_alphaover_key(bNode *node, float *out, float *src, float *over, f
}
}
+/* result will be still premul, but the over part is premulled */
+static void do_alphaover_mixed(bNode *node, float *out, float *src, float *over, float *fac)
+{
+
+ if(over[3]<=0.0f) {
+ QUATCOPY(out, src);
+ }
+ else if(fac[0]==1.0f && over[3]>=1.0f) {
+ QUATCOPY(out, over);
+ }
+ else {
+ NodeTwoFloats *ntf= node->storage;
+ float addfac= 1.0f - ntf->x + over[3]*ntf->x;
+ float premul= fac[0]*addfac;
+ float mul= 1.0f - fac[0]*over[3];
+
+ out[0]= (mul*src[0]) + premul*over[0];
+ out[1]= (mul*src[1]) + premul*over[1];
+ out[2]= (mul*src[2]) + premul*over[2];
+ out[3]= (mul*src[3]) + fac[0]*over[3];
+ }
+}
+
+
+
static void node_composit_exec_alphaover(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
{
@@ -97,8 +122,11 @@ static void node_composit_exec_alphaover(void *data, bNode *node, bNodeStack **i
/* make output size of input image */
CompBuf *cbuf= in[1]->data?in[1]->data:in[2]->data;
CompBuf *stackbuf= alloc_compbuf(cbuf->x, cbuf->y, CB_RGBA, 1); /* allocs */
+ NodeTwoFloats *ntf= node->storage;
- if(node->custom1)
+ if(ntf->x != 0.0f)
+ composit3_pixel_processor(node, stackbuf, in[1]->data, in[1]->vec, in[2]->data, in[2]->vec, in[0]->data, in[0]->vec, do_alphaover_mixed, CB_RGBA, CB_RGBA, CB_VAL);
+ else if(node->custom1)
composit3_pixel_processor(node, stackbuf, in[1]->data, in[1]->vec, in[2]->data, in[2]->vec, in[0]->data, in[0]->vec, do_alphaover_key, CB_RGBA, CB_RGBA, CB_VAL);
else
composit3_pixel_processor(node, stackbuf, in[1]->data, in[1]->vec, in[2]->data, in[2]->vec, in[0]->data, in[0]->vec, do_alphaover_premul, CB_RGBA, CB_RGBA, CB_VAL);
@@ -107,6 +135,11 @@ static void node_composit_exec_alphaover(void *data, bNode *node, bNodeStack **i
}
}
+static void node_alphaover_init(bNode* node)
+{
+ node->storage= MEM_callocN(sizeof(NodeTwoFloats), "NodeTwoFloats");
+}
+
bNodeType cmp_node_alphaover= {
/* *next,*prev */ NULL, NULL,
/* type code */ CMP_NODE_ALPHAOVER,
@@ -115,12 +148,12 @@ bNodeType cmp_node_alphaover= {
/* class+opts */ NODE_CLASS_OP_COLOR, NODE_OPTIONS,
/* input sock */ cmp_node_alphaover_in,
/* output sock */ cmp_node_alphaover_out,
- /* storage */ "",
+ /* storage */ "NodeTwoFloats",
/* execfunc */ node_composit_exec_alphaover,
/* butfunc */ NULL,
- /* initfunc */ NULL,
- /* freestoragefunc */ NULL,
- /* copystoragefunc */ NULL,
+ /* initfunc */ node_alphaover_init,
+ /* freestoragefunc */ node_free_standard_storage,
+ /* copystoragefunc */ node_copy_standard_storage,
/* id */ NULL
};
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_bilateralblur.c b/source/blender/nodes/intern/CMP_nodes/CMP_bilateralblur.c
new file mode 100644
index 00000000000..b954e876ea1
--- /dev/null
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_bilateralblur.c
@@ -0,0 +1,272 @@
+/**
+ *
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2006 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Vilem Novak
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#include "../CMP_util.h"
+
+/* **************** BILATERALBLUR ******************** */
+static bNodeSocketType cmp_node_bilateralblur_in[]= {
+ { SOCK_RGBA, 1, "Image", 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 1, "Determinator", 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
+ { -1, 0, "" }
+};
+
+static bNodeSocketType cmp_node_bilateralblur_out[]= {
+ { SOCK_RGBA, 0, "Image", 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
+ { -1, 0, "" }
+};
+
+#define INIT_C3\
+ mean0 = 1; mean1[0] = src[0];mean1[1] = src[1];mean1[2] = src[2];mean1[3] = src[3];
+
+/* finds color distances */
+#define COLOR_DISTANCE_C3(c1, c2)\
+ ((c1[0] - c2[0])*(c1[0] - c2[0]) + \
+ (c1[1] - c2[1])*(c1[1] - c2[1]) + \
+ (c1[2] - c2[2])*(c1[2] - c2[2]) + \
+ (c1[3] - c2[3])*(c1[3] - c2[3]))
+
+/* this is the main kernel function for comparing color distances
+ and adding them weighted to the final color */
+#define KERNEL_ELEMENT_C3(k)\
+ temp_color = src + deltas[k];\
+ ref_color = ref + deltas[k];\
+ w = weight_tab[k] + COLOR_DISTANCE_C3(ref, ref_color )*i2sigma_color;\
+ w = 1./(w*w + 1); \
+ mean0 += w;\
+ mean1[0] += temp_color[0]*w; \
+ mean1[1] += temp_color[1]*w; \
+ mean1[2] += temp_color[2]*w; \
+ mean1[3] += temp_color[3]*w;
+
+/* write blurred values to image */
+#define UPDATE_OUTPUT_C3\
+ mean0 = 1./mean0;\
+ dest[x*pix + 0] = mean1[0]*mean0; \
+ dest[x*pix + 1] = mean1[1]*mean0; \
+ dest[x*pix + 2] = mean1[2]*mean0; \
+ dest[x*pix + 3] = mean1[3]*mean0;
+
+/* initializes deltas for fast access to neighbour pixels */
+#define INIT_3X3_DELTAS( deltas, step, nch ) \
+ ((deltas)[0] = (nch), (deltas)[1] = -(step) + (nch), \
+ (deltas)[2] = -(step), (deltas)[3] = -(step) - (nch), \
+ (deltas)[4] = -(nch), (deltas)[5] = (step) - (nch), \
+ (deltas)[6] = (step), (deltas)[7] = (step) + (nch));
+
+
+/* code of this node was heavily inspired by the smooth function of opencv library.
+The main change is an optional image input */
+static void node_composit_exec_bilateralblur(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
+{
+ NodeBilateralBlurData *nbbd= node->storage;
+ CompBuf *new, *source, *img= in[0]->data , *refimg= in[1]->data;
+ double mean0, w, i2sigma_color, i2sigma_space;
+ double mean1[4];
+ double weight_tab[8];
+ float *src, *dest, *ref, *temp_color, *ref_color;
+ float sigma_color, sigma_space;
+ int imgx, imgy, x, y, pix, i, step;
+ int deltas[8];
+ short found_determinator= 0;
+
+ if(img == NULL || out[0]->hasoutput == 0)
+ return;
+
+ if(img->type != CB_RGBA) {
+ img= typecheck_compbuf(in[0]->data, CB_RGBA);
+ }
+
+ imgx= img->x;
+ imgy= img->y;
+ pix= img->type;
+ step= pix * imgx;
+
+ if(refimg) {
+ if(refimg->x == imgx && refimg->y == imgy) {
+ if(ELEM3(refimg->type, CB_VAL, CB_VEC2, CB_VEC3)) {
+ refimg= typecheck_compbuf(in[1]->data, CB_RGBA);
+ found_determinator= 1;
+ }
+ }
+ }
+ else {
+ refimg= img;
+ }
+
+ /* allocs */
+ source= dupalloc_compbuf(img);
+ new= alloc_compbuf(imgx, imgy, pix, 1);
+
+ /* accept image offsets from other nodes */
+ new->xof= img->xof;
+ new->yof= img->yof;
+
+ /* bilateral code properties */
+ sigma_color= nbbd->sigma_color;
+ sigma_space= nbbd->sigma_space;
+
+ i2sigma_color= 1. / (sigma_color * sigma_color);
+ i2sigma_space= 1. / (sigma_space * sigma_space);
+
+ INIT_3X3_DELTAS(deltas, step, pix);
+
+ weight_tab[0] = weight_tab[2] = weight_tab[4] = weight_tab[6] = i2sigma_space;
+ weight_tab[1] = weight_tab[3] = weight_tab[5] = weight_tab[7] = i2sigma_space * 2;
+
+ /* iterations */
+ for(i= 0; i < nbbd->iter; i++) {
+ src= source->rect;
+ ref= refimg->rect;
+ dest= new->rect;
+ /*goes through image, there are more loops for 1st/last line and all other lines*/
+ /*kernel element accumulates surrounding colors, which are then written with the update_output function*/
+ for(x= 0; x < imgx; x++, src+= pix, ref+= pix) {
+ INIT_C3;
+
+ KERNEL_ELEMENT_C3(6);
+
+ if(x > 0) {
+ KERNEL_ELEMENT_C3(5);
+ KERNEL_ELEMENT_C3(4);
+ }
+
+ if(x < imgx - 1) {
+ KERNEL_ELEMENT_C3(7);
+ KERNEL_ELEMENT_C3(0);
+ }
+
+ UPDATE_OUTPUT_C3;
+ }
+
+ dest+= step;
+
+ for(y= 1; y < imgy - 1; y++, dest+= step, src+= pix, ref+= pix) {
+ x= 0;
+
+ INIT_C3;
+
+ KERNEL_ELEMENT_C3(0);
+ KERNEL_ELEMENT_C3(1);
+ KERNEL_ELEMENT_C3(2);
+ KERNEL_ELEMENT_C3(6);
+ KERNEL_ELEMENT_C3(7);
+
+ UPDATE_OUTPUT_C3;
+
+ src+= pix;
+ ref+= pix;
+
+ for(x= 1; x < imgx - 1; x++, src+= pix, ref+= pix) {
+ INIT_C3;
+
+ KERNEL_ELEMENT_C3(0);
+ KERNEL_ELEMENT_C3(1);
+ KERNEL_ELEMENT_C3(2);
+ KERNEL_ELEMENT_C3(3);
+ KERNEL_ELEMENT_C3(4);
+ KERNEL_ELEMENT_C3(5);
+ KERNEL_ELEMENT_C3(6);
+ KERNEL_ELEMENT_C3(7);
+
+ UPDATE_OUTPUT_C3;
+ }
+
+ INIT_C3;
+
+ KERNEL_ELEMENT_C3(2);
+ KERNEL_ELEMENT_C3(3);
+ KERNEL_ELEMENT_C3(4);
+ KERNEL_ELEMENT_C3(5);
+ KERNEL_ELEMENT_C3(6);
+
+ UPDATE_OUTPUT_C3;
+ }
+
+ for(x= 0; x < imgx; x++, src+= pix, ref+= pix) {
+ INIT_C3;
+
+ KERNEL_ELEMENT_C3(2);
+
+ if(x > 0) {
+ KERNEL_ELEMENT_C3(3);
+ KERNEL_ELEMENT_C3(4);
+ }
+ if(x < imgx - 1) {
+ KERNEL_ELEMENT_C3(1);
+ KERNEL_ELEMENT_C3(0);
+ }
+
+ UPDATE_OUTPUT_C3;
+ }
+
+ if(node->exec & NODE_BREAK) break;
+
+ SWAP(CompBuf, *source, *new);
+ }
+
+ if(node->exec & NODE_BREAK)
+ free_compbuf(source);
+
+ if(img != in[0]->data)
+ free_compbuf(img);
+
+ if(found_determinator == 1) {
+ if(refimg != in[1]->data)
+ free_compbuf(refimg);
+ }
+
+ out[0]->data= source;
+
+ free_compbuf(new);
+}
+
+static void node_composit_init_bilateralblur(bNode* node)
+{
+ NodeBilateralBlurData *nbbd= MEM_callocN(sizeof(NodeBilateralBlurData), "node bilateral blur data");
+ node->storage= nbbd;
+ nbbd->sigma_color= 0.3;
+ nbbd->sigma_space= 5.0;
+}
+
+bNodeType cmp_node_bilateralblur= {
+ /* *next,*prev */ NULL, NULL,
+ /* type code */ CMP_NODE_BILATERALBLUR,
+ /* name */ "Bilateral Blur",
+ /* width+range */ 150, 120, 200,
+ /* class+opts */ NODE_CLASS_OP_FILTER, NODE_OPTIONS,
+ /* input sock */ cmp_node_bilateralblur_in,
+ /* output sock */ cmp_node_bilateralblur_out,
+ /* storage */ "NodeBilateralBlurData",
+ /* execfunc */ node_composit_exec_bilateralblur,
+ /* butfunc */ NULL,
+ /* initfunc */ node_composit_init_bilateralblur,
+ /* freestoragefunc */ node_free_standard_storage,
+ /* copystoragefunc */ node_copy_standard_storage,
+ /* id */ NULL
+
+};
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_blur.c b/source/blender/nodes/intern/CMP_nodes/CMP_blur.c
index 8ef4af4d219..e7e799b6e76 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_blur.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_blur.c
@@ -22,7 +22,8 @@
*
* The Original Code is: all of this file.
*
- * Contributor(s): none yet.
+ * Contributor(s): Campbell Barton, Alfredo de Greef, David Millan Escriva,
+ * Juho Vepsäläinen
*
* ***** END GPL LICENSE BLOCK *****
*/
@@ -397,7 +398,7 @@ static void bokeh_single_image(bNode *node, CompBuf *new, CompBuf *img, float fa
int maxyr= y+rady>imgy-1?imgy-y-1:rady;
float *destd= new->rect + pix*( (y + minyr)*imgx + x + minxr);
- float *dgausd= gausstab + (minyr+rady)*2*radx + minxr+radx;
+ float *dgausd= gausstab + (minyr+rady)*(2*radx+1) + minxr+radx;
if(x<=0) src= srcd;
else if(x<imgx) src+= pix;
@@ -556,16 +557,20 @@ static void blur_with_reference(bNode *node, CompBuf *new, CompBuf *img, CompBuf
static void node_composit_exec_blur(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
{
CompBuf *new, *img= in[0]->data;
+ NodeBlurData *nbd= node->storage;
- if(img==NULL || out[0]->hasoutput==0)
- return;
+ if(img==NULL) return;
+
+ /* store image in size that is needed for absolute/relative conversions on ui level */
+ nbd->image_in_width= img->x;
+ nbd->image_in_height= img->y;
+
+ if(out[0]->hasoutput==0) return;
if (((NodeBlurData *)node->storage)->filtertype == R_FILTER_FAST_GAUSS) {
CompBuf *new, *img = in[0]->data;
/*from eeshlo's original patch, removed to fit in with the existing blur node */
/*const float sx = in[1]->vec[0], sy = in[2]->vec[0];*/
-
- NodeBlurData *nbd= node->storage;
const float sx = ((float)nbd->sizex)/2.0f, sy = ((float)nbd->sizey)/2.0f;
int c;
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_brightness.c b/source/blender/nodes/intern/CMP_nodes/CMP_brightness.c
index c87307434b5..f6363cc7ffa 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_brightness.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_brightness.c
@@ -35,8 +35,8 @@
static bNodeSocketType cmp_node_brightcontrast_in[]= {
{ SOCK_RGBA, 1, "Image", 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
- { SOCK_VALUE, 1, "bright", 0.0f, 0.0f, 0.0f, 0.0f, -100.0f, 100.0f},
- { SOCK_VALUE, 1, "contrast", 0.0f, 0.0f, 0.0f, 0.0f, -100.0f, 100.0f},
+ { SOCK_VALUE, 1, "Bright", 0.0f, 0.0f, 0.0f, 0.0f, -100.0f, 100.0f},
+ { SOCK_VALUE, 1, "Contrast", 0.0f, 0.0f, 0.0f, 0.0f, -100.0f, 100.0f},
{ -1, 0, "" }
};
static bNodeSocketType cmp_node_brightcontrast_out[]= {
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_curves.c b/source/blender/nodes/intern/CMP_nodes/CMP_curves.c
index 17d9821a5ef..01af0e1db1d 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_curves.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_curves.c
@@ -22,7 +22,7 @@
*
* The Original Code is: all of this file.
*
- * Contributor(s): none yet.
+ * Contributor(s): Björn C. Schaefer
*
* ***** END GPL LICENSE BLOCK *****
*/
@@ -123,6 +123,8 @@ bNodeType cmp_node_curve_vec= {
static bNodeSocketType cmp_node_curve_rgb_in[]= {
{ SOCK_VALUE, 1, "Fac", 1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f},
{ SOCK_RGBA, 1, "Image", 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f},
+ { SOCK_RGBA, 1, "Black Level", 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f},
+ { SOCK_RGBA, 1, "White Level", 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f},
{ -1, 0, "" }
};
@@ -157,7 +159,7 @@ static void do_curves_fac(bNode *node, float *out, float *in, float *fac)
static void node_composit_exec_curve_rgb(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
{
- /* stack order input: fac, image */
+ /* stack order input: fac, image, black level, white level */
/* stack order output: image */
if(out[0]->hasoutput==0)
@@ -172,6 +174,8 @@ static void node_composit_exec_curve_rgb(void *data, bNode *node, bNodeStack **i
CompBuf *cbuf= in[1]->data;
CompBuf *stackbuf= alloc_compbuf(cbuf->x, cbuf->y, CB_RGBA, 1); /* allocs */
+ curvemapping_set_black_white(node->storage, in[2]->vec, in[3]->vec);
+
if(in[0]->vec[0] == 1.0)
composit1_pixel_processor(node, stackbuf, in[1]->data, in[1]->vec, do_curves, CB_RGBA);
else
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_defocus.c b/source/blender/nodes/intern/CMP_nodes/CMP_defocus.c
index 53d01ab1d12..6f175671296 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_defocus.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_defocus.c
@@ -235,7 +235,7 @@ static void IIR_gauss_single(CompBuf* buf, float sigma)
#undef YVV
}
-static void defocus_blur(bNode *node, CompBuf *new, CompBuf *img, CompBuf *zbuf, float inpval)
+static void defocus_blur(bNode *node, CompBuf *new, CompBuf *img, CompBuf *zbuf, float inpval, int no_zbuf)
{
NodeDefocus *nqd = node->storage;
CompBuf *wts; // weights buffer
@@ -283,7 +283,7 @@ static void defocus_blur(bNode *node, CompBuf *new, CompBuf *img, CompBuf *zbuf,
// if 'no_zbuf' flag set (which is always set if input is not an image),
// values are instead interpreted directly as blur radius values
- if (nqd->no_zbuf) {
+ if (no_zbuf) {
// to prevent *reaaallly* big radius values and impossible calculation times,
// limit the maximum to half the image width or height, whichever is smaller
float maxr = 0.5f*(float)MIN2(img->x, img->y);
@@ -376,8 +376,10 @@ static void defocus_blur(bNode *node, CompBuf *new, CompBuf *img, CompBuf *zbuf,
// some sort of visual feedback would be nice, or at least this text in the renderwin header
// but for now just print some info in the console every 8 scanlines.
if (((y & 7)==0) || (y==(img->y-1))) {
- printf("\rdefocus: Processing Line %d of %d ... ", y+1, img->y);
- fflush(stdout);
+ if(G.background==0) {
+ printf("\rdefocus: Processing Line %d of %d ... ", y+1, img->y);
+ fflush(stdout);
+ }
}
// esc set by main calling process
if(node->exec & NODE_BREAK)
@@ -698,7 +700,7 @@ static void defocus_blur(bNode *node, CompBuf *new, CompBuf *img, CompBuf *zbuf,
// sampled, simple rejection sampling here, good enough
unsigned int maxsam, s, ui = BLI_rand()*BLI_rand();
float wcor, cpr = BLI_frand();
- if (nqd->no_zbuf)
+ if (no_zbuf)
maxsam = nqd->samples; // no zbuffer input, use sample value directly
else {
// depth adaptive sampling hack, the more out of focus, the more samples taken, 16 minimum.
@@ -772,14 +774,13 @@ static void node_composit_exec_defocus(void *data, bNode *node, bNodeStack **in,
{
CompBuf *new, *old, *zbuf_use = NULL, *img = in[0]->data, *zbuf = in[1]->data;
NodeDefocus *nqd = node->storage;
+ int no_zbuf = nqd->no_zbuf;
if ((img==NULL) || (out[0]->hasoutput==0)) return;
// if image not valid type or fstop==infinite (128), nothing to do, pass in to out
- if (((img->type!=CB_RGBA) && (img->type!=CB_VAL)) || ((nqd->no_zbuf==0) && (nqd->fstop==128.f))) {
- new = alloc_compbuf(img->x, img->y, img->type, 0);
- new->rect = img->rect;
- out[0]->data = new;
+ if (((img->type!=CB_RGBA) && (img->type!=CB_VAL)) || ((no_zbuf==0) && (nqd->fstop==128.f))) {
+ out[0]->data = pass_on_compbuf(img);
return;
}
@@ -793,21 +794,27 @@ static void node_composit_exec_defocus(void *data, bNode *node, bNodeStack **in,
}
zbuf_use = typecheck_compbuf(zbuf, CB_VAL);
}
- else nqd->no_zbuf = 1; // no zbuffer input
+ else no_zbuf = 1; // no zbuffer input
// ok, process
old = img;
if (nqd->gamco) {
- // gamma correct, blender func is simplified, fixed value & RGBA only, should make user param
+ // gamma correct, blender func is simplified, fixed value & RGBA only,
+ // should make user param. also depremul and premul afterwards, gamma
+ // correction can't work with premul alpha
old = dupalloc_compbuf(img);
+ premul_compbuf(old, 1);
gamma_correct_compbuf(old, 0);
+ premul_compbuf(old, 0);
}
new = alloc_compbuf(old->x, old->y, old->type, 1);
- defocus_blur(node, new, old, zbuf_use, in[1]->vec[0]*nqd->scale);
+ defocus_blur(node, new, old, zbuf_use, in[1]->vec[0]*nqd->scale, no_zbuf);
if (nqd->gamco) {
+ premul_compbuf(new, 1);
gamma_correct_compbuf(new, 1);
+ premul_compbuf(new, 0);
free_compbuf(old);
}
if(node->exec & NODE_BREAK) {
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_directionalblur.c b/source/blender/nodes/intern/CMP_nodes/CMP_directionalblur.c
new file mode 100644
index 00000000000..27f535186db
--- /dev/null
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_directionalblur.c
@@ -0,0 +1,143 @@
+/**
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2006 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Alfredo de Greef (eeshlo)
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "../CMP_util.h"
+
+static bNodeSocketType cmp_node_dblur_in[]= {
+ { SOCK_RGBA, 1, "Image", 0.8f, 0.8f, 0.8f, 1.f, 0.f, 1.f},
+ { -1, 0, "" }
+};
+
+static bNodeSocketType cmp_node_dblur_out[]= {
+ { SOCK_RGBA, 0, "Image", 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
+ { -1, 0, "" }
+};
+
+static CompBuf *dblur(bNode *node, CompBuf *img, int iterations, int wrap,
+ float center_x, float center_y, float dist, float angle, float spin, float zoom)
+{
+ if ((dist != 0.f) || (spin != 0.f) || (zoom != 0.f)) {
+ void (*getpix)(CompBuf*, float, float, float*) = wrap ? qd_getPixelLerpWrap : qd_getPixelLerp;
+ const float a= angle * (float)M_PI / 180.f;
+ const float itsc= 1.f / pow(2.f, (float)iterations);
+ float D;
+ float center_x_pix, center_y_pix;
+ float tx, ty;
+ float sc, rot;
+ CompBuf *tmp;
+ int i, j;
+
+ tmp= dupalloc_compbuf(img);
+
+ D= dist * sqrtf(img->x * img->x + img->y * img->y);
+ center_x_pix= center_x * img->x;
+ center_y_pix= center_y * img->y;
+
+ tx= itsc * D * cos(a);
+ ty= -itsc * D * sin(a);
+ sc= itsc * zoom;
+ rot= itsc * spin * (float)M_PI / 180.f;
+
+ /* blur the image */
+ for(i= 0; i < iterations; ++i) {
+ const float cs= cos(rot), ss= sin(rot);
+ const float isc= 1.f / (1.f + sc);
+ unsigned int x, y;
+ float col[4]= {0,0,0,0};
+
+ for(y= 0; y < img->y; ++y) {
+ const float v= isc * (y - center_y_pix) + ty;
+
+ for(x= 0; x < img->x; ++x) {
+ const float u= isc * (x - center_x_pix) + tx;
+ unsigned int p= (x + y * img->x) * img->type;
+
+ getpix(tmp, cs * u + ss * v + center_x_pix, cs * v - ss * u + center_y_pix, col);
+
+ /* mix img and transformed tmp */
+ for(j= 0; j < 4; ++j)
+ img->rect[p + j]= AVG2(img->rect[p + j], col[j]);
+ }
+ }
+
+ /* copy img to tmp */
+ if(i != (iterations - 1))
+ memcpy(tmp->rect, img->rect, sizeof(float) * img->x * img->y * img->type);
+
+ /* double transformations */
+ tx *= 2.f, ty *= 2.f;
+ sc *= 2.f, rot *= 2.f;
+
+ if(node->exec & NODE_BREAK) break;
+ }
+
+ free_compbuf(tmp);
+ }
+
+ return img;
+}
+
+static void node_composit_exec_dblur(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
+{
+ NodeDBlurData *ndbd= node->storage;
+ CompBuf *new, *img= in[0]->data;
+
+ if((img == NULL) || (out[0]->hasoutput == 0)) return;
+
+ if (img->type != CB_RGBA)
+ new = typecheck_compbuf(img, CB_RGBA);
+ else
+ new = dupalloc_compbuf(img);
+
+ out[0]->data= dblur(node, new, ndbd->iter, ndbd->wrap, ndbd->center_x, ndbd->center_y, ndbd->distance, ndbd->angle, ndbd->spin, ndbd->zoom);
+}
+
+static void node_composit_init_dblur(bNode* node)
+{
+ NodeDBlurData *ndbd= MEM_callocN(sizeof(NodeDBlurData), "node dblur data");
+ node->storage= ndbd;
+ ndbd->center_x= 0.5;
+ ndbd->center_y= 0.5;
+}
+
+bNodeType cmp_node_dblur = {
+ /* *next,*prev */ NULL, NULL,
+ /* type code */ CMP_NODE_DBLUR,
+ /* name */ "Directional Blur",
+ /* width+range */ 150, 120, 200,
+ /* class+opts */ NODE_CLASS_OP_FILTER, NODE_OPTIONS,
+ /* input sock */ cmp_node_dblur_in,
+ /* output sock */ cmp_node_dblur_out,
+ /* storage */ "NodeDBlurData",
+ /* execfunc */ node_composit_exec_dblur,
+ /* butfunc */ NULL,
+ /* initfunc */ node_composit_init_dblur,
+ /* freestoragefunc */ node_free_standard_storage,
+ /* copystoragefunc */ node_copy_standard_storage,
+ /* id */ NULL
+};
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_displace.c b/source/blender/nodes/intern/CMP_nodes/CMP_displace.c
index 0ec15d9eb77..f5b6edcea80 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_displace.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_displace.c
@@ -44,18 +44,22 @@ static bNodeSocketType cmp_node_displace_out[]= {
{ -1, 0, "" }
};
+static float *vecbuf_get_pixel(CompBuf *vecbuf, float *veccol, int x, int y)
+{
+ /* the x-xrad stuff is a bit weird, but i seem to need it otherwise
+ * my returned pixels are offset weirdly */
+ return compbuf_get_pixel(vecbuf, veccol, x-vecbuf->xrad, y-vecbuf->yrad, vecbuf->xrad, vecbuf->yrad);
+}
+
static void do_displace(CompBuf *stackbuf, CompBuf *cbuf, CompBuf *vecbuf, float *veccol, float *xscale, float *yscale)
{
ImBuf *ibuf;
- int x, y, sx, sy;
float dx=0.0, dy=0.0;
float dspx, dspy;
- float uv[2];
-
- float *out= stackbuf->rect, *vec=vecbuf->rect, *in= cbuf->rect;
+ float uv[2], col[4], colnext[4], colprev[4];
float *vp, *vpnext, *vpprev;
-
- int row = 3*vecbuf->x;
+ float *out= stackbuf->rect, *vec=vecbuf->rect, *in= cbuf->rect;
+ int x, y, vx, vy, sx, sy;
/* ibuf needed for sampling */
ibuf= IMB_allocImBuf(cbuf->x, cbuf->y, 32, 0, 0);
@@ -65,37 +69,50 @@ static void do_displace(CompBuf *stackbuf, CompBuf *cbuf, CompBuf *vecbuf, float
sx= stackbuf->x;
sy= stackbuf->y;
+
+ QUATCOPY(col, veccol);
+ QUATCOPY(colnext, veccol);
+ QUATCOPY(colprev, veccol);
for(y=0; y<sy; y++) {
for(x= 0; x< sx; x++, out+=4, in+=4, vec+=3) {
- /* the x-xrad stuff is a bit weird, but i seem to need it otherwise
- * my returned pixels are offset weirdly */
- vp = compbuf_get_pixel(vecbuf, veccol, x-vecbuf->xrad, y-vecbuf->yrad, vecbuf->xrad, vecbuf->yrad);
+ vp = vecbuf_get_pixel(vecbuf, col, x, y);
+
+ /* this happens in compbuf_get_pixel, need to make sure the following
+ * check takes them into account */
+ vx= x-vecbuf->xof;
+ vy= y-vecbuf->yof;
/* find the new displaced co-ords, also correcting for translate offset */
- dspx = x - (*xscale * vp[0]);
- dspy = y - (*yscale * vp[1]);
+ dspx = vx - (*xscale * vp[0]);
+ dspy = vy - (*yscale * vp[1]);
/* convert image space to 0.0-1.0 UV space for sampling, correcting for translate offset */
uv[0] = dspx / (float)sx;
uv[1] = dspy / (float)sy;
-
- if(x>0 && x< vecbuf->x-1 && y>0 && y< vecbuf->y-1) {
- vpnext = vp+row;
- vpprev = vp-row;
-
- /* adaptive sampling, X channel */
- dx= 0.5f*(fabs(vp[0]-vp[-3]) + fabs(vp[0]-vp[3]));
-
- dx+= 0.25f*(fabs(vp[0]-vpprev[-3]) + fabs(vp[0]-vpnext[-3]));
- dx+= 0.25f*(fabs(vp[0]-vpprev[+3]) + fabs(vp[0]-vpnext[+3]));
-
- /* adaptive sampling, Y channel */
- dy= 0.5f*(fabs(vp[1]-vp[-row+1]) + fabs(vp[1]-vp[row+1]));
-
- dy+= 0.25f*(fabs(vp[1]-vpprev[+1-3]) + fabs(vp[1]-vpnext[+1-3]));
- dy+= 0.25f*(fabs(vp[1]-vpprev[+1+3]) + fabs(vp[1]-vpnext[+1+3]));
+
+ if(vx>0 && vx< vecbuf->x-1 && vy>0 && vy< vecbuf->y-1) {
+ /* adaptive sampling, X and Y channel.
+ * we call vecbuf_get_pixel for every pixel since the input
+ * might be a procedural, and then we can't use offsets */
+ vpprev = vecbuf_get_pixel(vecbuf, colprev, x-1, y);
+ vpnext = vecbuf_get_pixel(vecbuf, colnext, x+1, y);
+ dx= 0.5f*(fabs(vp[0]-vpprev[0]) + fabs(vp[0]-vpnext[0]));
+
+ vpprev = vecbuf_get_pixel(vecbuf, colprev, x, y-1);
+ vpnext = vecbuf_get_pixel(vecbuf, colnext, x, y+1);
+ dy= 0.5f*(fabs(vp[1]-vpnext[1]) + fabs(vp[1]-vpprev[1]));
+
+ vpprev = vecbuf_get_pixel(vecbuf, colprev, x-1, y-1);
+ vpnext = vecbuf_get_pixel(vecbuf, colnext, x-1, y+1);
+ dx+= 0.25f*(fabs(vp[0]-vpprev[0]) + fabs(vp[0]-vpnext[0]));
+ dy+= 0.25f*(fabs(vp[1]-vpprev[1]) + fabs(vp[1]-vpnext[1]));
+
+ vpprev = vecbuf_get_pixel(vecbuf, colprev, x+1, y-1);
+ vpnext = vecbuf_get_pixel(vecbuf, colnext, x+1, y+1);
+ dx+= 0.25f*(fabs(vp[0]-vpprev[0]) + fabs(vp[0]-vpnext[0]));
+ dy+= 0.25f*(fabs(vp[1]-vpprev[1]) + fabs(vp[1]-vpnext[1]));
/* scaled down to prevent blurriness */
/* 8: magic number, provides a good level of sharpness without getting too aliased */
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_gamma.c b/source/blender/nodes/intern/CMP_nodes/CMP_gamma.c
index 5d0ab729e08..e77de3726cb 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_gamma.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_gamma.c
@@ -34,7 +34,7 @@
static bNodeSocketType cmp_node_gamma_in[]= {
{ SOCK_RGBA, 1, "Image", 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
- { SOCK_VALUE, 1, "Gamma", 1.0f, 0.0f, 0.0f, 0.0f, 0.001f, 2.0f},
+ { SOCK_VALUE, 1, "Gamma", 1.0f, 0.0f, 0.0f, 0.0f, 0.001f, 10.0f},
{ -1, 0, "" }
};
static bNodeSocketType cmp_node_gamma_out[]= {
@@ -46,7 +46,8 @@ static void do_gamma(bNode *node, float *out, float *in, float *fac)
{
int i=0;
for(i=0; i<3; i++) {
- out[i] = pow(in[i],fac[0]);
+ /* check for negative to avoid nan's */
+ out[i] = (in[i] > 0.0f)? pow(in[i],fac[0]): in[i];
}
out[3] = in[3];
}
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_glare.c b/source/blender/nodes/intern/CMP_nodes/CMP_glare.c
index e7b8fd00c93..9ab4038607f 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_glare.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_glare.c
@@ -424,15 +424,18 @@ static void fglow(NodeGlare* ndg, CompBuf* dst, CompBuf* src)
static void node_composit_exec_glare(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
{
- CompBuf *new, *img = in[0]->data;
+ CompBuf *new, *src, *img = in[0]->data;
NodeGlare* ndg = node->storage;
if ((img == NULL) || (out[0]->hasoutput == 0)) return;
- if (img->type != CB_RGBA)
+ if (img->type != CB_RGBA) {
new = typecheck_compbuf(img, CB_RGBA);
- else
+ src = typecheck_compbuf(img, CB_RGBA);
+ } else {
new = dupalloc_compbuf(img);
+ src = dupalloc_compbuf(img);
+ }
{
int x, y;
@@ -448,19 +451,20 @@ static void node_composit_exec_glare(void *data, bNode *node, bNodeStack **in, b
switch (ndg->type) {
case 0:
- star4(ndg, new, img);
+ star4(ndg, new, src);
break;
case 1:
- fglow(ndg, new, img);
+ fglow(ndg, new, src);
break;
case 3:
- ghosts(ndg, new, img);
+ ghosts(ndg, new, src);
break;
case 2:
default:
- streaks(ndg, new, img);
+ streaks(ndg, new, src);
}
+ free_compbuf(src);
out[0]->data = new;
}
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_hueSatVal.c b/source/blender/nodes/intern/CMP_nodes/CMP_hueSatVal.c
index eeddb4ce756..92614d1cc6a 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_hueSatVal.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_hueSatVal.c
@@ -52,9 +52,7 @@ static void do_hue_sat_fac(bNode *node, float *out, float *in, float *fac)
hsv[0]+= (nhs->hue - 0.5f);
if(hsv[0]>1.0) hsv[0]-=1.0; else if(hsv[0]<0.0) hsv[0]+= 1.0;
hsv[1]*= nhs->sat;
- if(hsv[1]>1.0) hsv[1]= 1.0; else if(hsv[1]<0.0) hsv[1]= 0.0;
hsv[2]*= nhs->val;
- if(hsv[2]>1.0) hsv[2]= 1.0; else if(hsv[2]<0.0) hsv[2]= 0.0;
hsv_to_rgb(hsv[0], hsv[1], hsv[2], col, col+1, col+2);
out[0]= mfac*in[0] + *fac*col[0];
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_idMask.c b/source/blender/nodes/intern/CMP_nodes/CMP_idMask.c
index abb9fa98d97..a40579ac3b2 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_idMask.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_idMask.c
@@ -63,8 +63,25 @@ static void do_idmask(CompBuf *stackbuf, CompBuf *cbuf, float idnr)
MEM_freeN(abuf);
}
+/* full sample version */
+static void do_idmask_fsa(CompBuf *stackbuf, CompBuf *cbuf, float idnr)
+{
+ float *rect, *rs;
+ int x;
+
+ rect= cbuf->rect;
+ rs= stackbuf->rect;
+ for(x= cbuf->x*cbuf->y - 1; x>=0; x--)
+ if(rect[x]==idnr)
+ rs[x]= 1.0f;
+
+}
+
+
static void node_composit_exec_idmask(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
{
+ RenderData *rd= data;
+
if(out[0]->hasoutput==0)
return;
@@ -77,7 +94,10 @@ static void node_composit_exec_idmask(void *data, bNode *node, bNodeStack **in,
stackbuf= alloc_compbuf(cbuf->x, cbuf->y, CB_VAL, 1); /* allocs */;
- do_idmask(stackbuf, cbuf, (float)node->custom1);
+ if(rd->scemode & R_FULL_SAMPLE)
+ do_idmask_fsa(stackbuf, cbuf, (float)node->custom1);
+ else
+ do_idmask(stackbuf, cbuf, (float)node->custom1);
out[0]->data= stackbuf;
}
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_image.c b/source/blender/nodes/intern/CMP_nodes/CMP_image.c
index 20308e968d3..be5a1d7241b 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_image.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_image.c
@@ -48,6 +48,7 @@ static bNodeSocketType cmp_node_rlayers_out[]= {
{ SOCK_RGBA, 0, "Refract", 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_RGBA, 0, "Radio", 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_VALUE, 0, "IndexOB", 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_VALUE, 0, "Mist", 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
@@ -78,6 +79,21 @@ static CompBuf *node_composit_get_image(RenderData *rd, Image *ima, ImageUser *i
stackbuf->rect= ibuf->rect_float;
}
+ /*code to respect the premul flag of images; I'm
+ not sure if this is a good idea for multilayer images,
+ since it never worked before for them.
+ if (type==CB_RGBA && ima->flag & IMA_DO_PREMUL) {
+ //premul the image
+ int i;
+ float *pixel = stackbuf->rect;
+
+ for (i=0; i<stackbuf->x*stackbuf->y; i++, pixel += 4) {
+ pixel[0] *= pixel[3];
+ pixel[1] *= pixel[3];
+ pixel[2] *= pixel[3];
+ }
+ }
+ */
return stackbuf;
};
@@ -149,6 +165,8 @@ void outputs_multilayer_get(RenderData *rd, RenderLayer *rl, bNodeStack **out, I
out[RRES_OUT_RADIO]->data= compbuf_multilayer_get(rd, rl, ima, iuser, SCE_PASS_RADIO);
if(out[RRES_OUT_INDEXOB]->hasoutput)
out[RRES_OUT_INDEXOB]->data= compbuf_multilayer_get(rd, rl, ima, iuser, SCE_PASS_INDEXOB);
+ if(out[RRES_OUT_MIST]->hasoutput)
+ out[RRES_OUT_MIST]->data= compbuf_multilayer_get(rd, rl, ima, iuser, SCE_PASS_MIST);
};
@@ -184,11 +202,32 @@ static void node_composit_exec_image(void *data, bNode *node, bNodeStack **in, b
else {
stackbuf= node_composit_get_image(rd, ima, iuser);
- /* put image on stack */
- out[0]->data= stackbuf;
+ if (stackbuf) {
+ /*respect image premul option*/
+ if (stackbuf->type==CB_RGBA && ima->flag & IMA_DO_PREMUL) {
+ int i;
+ float *pixel;
+
+ /*first duplicate stackbuf->rect, since it's just a pointer
+ to the source imbuf, and we don't want to change that.*/
+ stackbuf->rect = MEM_dupallocN(stackbuf->rect);
+
+ /*premul the image*/
+
+ pixel = stackbuf->rect;
+ for (i=0; i<stackbuf->x*stackbuf->y; i++, pixel += 4) {
+ pixel[0] *= pixel[3];
+ pixel[1] *= pixel[3];
+ pixel[2] *= pixel[3];
+ }
+ }
- if(out[2]->hasoutput)
- out[2]->data= node_composit_get_zimage(node, rd);
+ /* put image on stack */
+ out[0]->data= stackbuf;
+
+ if(out[2]->hasoutput)
+ out[2]->data= node_composit_get_zimage(node, rd);
+ }
}
/* alpha and preview for both types */
@@ -205,6 +244,7 @@ static void node_composit_init_image(bNode* node)
{
ImageUser *iuser= MEM_callocN(sizeof(ImageUser), "node image user");
node->storage= iuser;
+ iuser->frames= 1;
iuser->sfra= 1;
iuser->fie_ima= 2;
iuser->ok= 1;
@@ -236,7 +276,7 @@ static CompBuf *compbuf_from_pass(RenderData *rd, RenderLayer *rl, int rectx, in
CompBuf *buf;
int buftype= CB_VEC3;
- if(ELEM(passcode, SCE_PASS_Z, SCE_PASS_INDEXOB))
+ if(ELEM3(passcode, SCE_PASS_Z, SCE_PASS_INDEXOB, SCE_PASS_MIST))
buftype= CB_VAL;
else if(passcode==SCE_PASS_VECTOR)
buftype= CB_VEC4;
@@ -282,7 +322,9 @@ void node_composit_rlayers_out(RenderData *rd, RenderLayer *rl, bNodeStack **out
if(out[RRES_OUT_RADIO]->hasoutput)
out[RRES_OUT_RADIO]->data= compbuf_from_pass(rd, rl, rectx, recty, SCE_PASS_RADIO);
if(out[RRES_OUT_INDEXOB]->hasoutput)
- out[RRES_OUT_INDEXOB]->data= compbuf_from_pass(rd, rl, rectx, recty, SCE_PASS_INDEXOB);
+ out[RRES_OUT_INDEXOB]->data= compbuf_from_pass(rd, rl, rectx, recty, SCE_PASS_INDEXOB);
+ if(out[RRES_OUT_MIST]->hasoutput)
+ out[RRES_OUT_MIST]->data= compbuf_from_pass(rd, rl, rectx, recty, SCE_PASS_MIST);
};
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_math.c b/source/blender/nodes/intern/CMP_nodes/CMP_math.c
index cf2af9bbc11..421c1343df7 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_math.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_math.c
@@ -57,7 +57,7 @@ static void do_math(bNode *node, float *out, float *in, float *in2)
break;
case 3: /* Divide */
{
- if(in[1]==0) /* We don't want to divide by zero. */
+ if(in2[0]==0) /* We don't want to divide by zero. */
out[0]= 0.0;
else
out[0]= in[0] / in2[0];
@@ -131,7 +131,23 @@ static void do_math(bNode *node, float *out, float *in, float *in2)
{
out[0]= (int)(in[0] + 0.5f);
}
- break;
+ break;
+ case 15: /* Less Than */
+ {
+ if( in[0] < in2[0] )
+ out[0]= 1.0f;
+ else
+ out[0]= 0.0f;
+ }
+ break;
+ case 16: /* Greater Than */
+ {
+ if( in[0] > in2[0] )
+ out[0]= 1.0f;
+ else
+ out[0]= 0.0f;
+ }
+ break;
}
}
@@ -142,7 +158,6 @@ static void node_composit_exec_math(void *data, bNode *node, bNodeStack **in, bN
CompBuf *stackbuf;
/* check for inputs and outputs for early out*/
- if(in[0]->hasinput==0 && in[1]->hasinput==0) return;
if(out[0]->hasoutput==0) return;
/* no image-color operation */
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_premulkey.c b/source/blender/nodes/intern/CMP_nodes/CMP_premulkey.c
new file mode 100644
index 00000000000..4fde652c59d
--- /dev/null
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_premulkey.c
@@ -0,0 +1,77 @@
+/**
+* $Id$
+*
+* ***** BEGIN GPL LICENSE BLOCK *****
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 2
+* of the License, or (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software Foundation,
+* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*
+* The Original Code is Copyright (C) 2006 Blender Foundation.
+* All rights reserved.
+*
+* The Original Code is: all of this file.
+*
+* Contributor(s): none yet.
+*
+* ***** END GPL LICENSE BLOCK *****
+
+*/
+
+#include "../CMP_util.h"
+
+/* **************** Premul and Key Alpha Convert ******************** */
+
+static bNodeSocketType cmp_node_premulkey_in[]= {
+ { SOCK_RGBA, 1, "Image", 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
+ { -1, 0, "" }
+};
+static bNodeSocketType cmp_node_premulkey_out[]= {
+ { SOCK_RGBA, 0, "Image", 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
+ { -1, 0, "" }
+};
+
+static void node_composit_exec_premulkey(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
+{
+ if(out[0]->hasoutput==0)
+ return;
+
+ if(in[0]->data) {
+ CompBuf *stackbuf, *cbuf= typecheck_compbuf(in[0]->data, CB_RGBA);
+
+ stackbuf= dupalloc_compbuf(cbuf);
+ premul_compbuf(stackbuf, node->custom1 == 1);
+
+ out[0]->data = stackbuf;
+ if(cbuf != in[0]->data)
+ free_compbuf(cbuf);
+ }
+}
+
+bNodeType cmp_node_premulkey= {
+ /* *next,*prev */ NULL, NULL,
+ /* type code */ CMP_NODE_PREMULKEY,
+ /* name */ "Alpha Convert",
+ /* width+range */ 140, 100, 320,
+ /* class+opts */ NODE_CLASS_CONVERTOR, NODE_OPTIONS,
+ /* input sock */ cmp_node_premulkey_in,
+ /* output sock */ cmp_node_premulkey_out,
+ /* storage */ "",
+ /* execfunc */ node_composit_exec_premulkey,
+ /* butfunc */ NULL,
+ /* initfunc */ NULL,
+ /* freestoragefunc */ NULL,
+ /* copysotragefunc */ NULL,
+ /* id */ NULL
+};
+
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_texture.c b/source/blender/nodes/intern/CMP_nodes/CMP_texture.c
index 31afe74bd11..c1f1948dba1 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_texture.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_texture.c
@@ -42,19 +42,18 @@ static bNodeSocketType cmp_node_texture_out[]= {
};
/* called without rect allocated */
-static void texture_procedural(CompBuf *cbuf, float *col, float xco, float yco)
+static void texture_procedural(CompBuf *cbuf, float *out, float xco, float yco)
{
bNode *node= cbuf->node;
- bNodeSocket *sock= node->inputs.first;
TexResult texres= {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0, NULL};
- float vec[3], *size, nor[3]={0.0f, 0.0f, 0.0f};
- int retval, type= cbuf->type;
+ float vec[3], *size, nor[3]={0.0f, 0.0f, 0.0f}, col[4];
+ int retval, type= cbuf->procedural_type;
- size= sock->next->ns.vec;
+ size= cbuf->procedural_size;
- vec[0]= size[0]*(xco + sock->ns.vec[0]);
- vec[1]= size[1]*(yco + sock->ns.vec[1]);
- vec[2]= size[2]*sock->ns.vec[2];
+ vec[0]= size[0]*(xco + cbuf->procedural_offset[0]);
+ vec[1]= size[1]*(yco + cbuf->procedural_offset[1]);
+ vec[2]= size[2]*cbuf->procedural_offset[2];
retval= multitex_ext((Tex *)node->id, vec, NULL, NULL, 0, &texres);
@@ -80,6 +79,8 @@ static void texture_procedural(CompBuf *cbuf, float *col, float xco, float yco)
else {
VECCOPY(col, nor);
}
+
+ typecheck_compbuf_color(out, col, cbuf->type, cbuf->procedural_type);
}
/* texture node outputs get a small rect, to make sure all other nodes accept it */
@@ -106,6 +107,9 @@ static void node_composit_exec_texture(void *data, bNode *node, bNodeStack **in,
prevbuf->rect_procedural= texture_procedural;
prevbuf->node= node;
+ VECCOPY(prevbuf->procedural_offset, in[0]->vec);
+ VECCOPY(prevbuf->procedural_size, in[1]->vec);
+ prevbuf->procedural_type= CB_RGBA;
composit1_pixel_processor(node, prevbuf, prevbuf, out[0]->vec, do_copy_rgba, CB_RGBA);
generate_preview(node, prevbuf);
free_compbuf(prevbuf);
@@ -115,6 +119,9 @@ static void node_composit_exec_texture(void *data, bNode *node, bNodeStack **in,
stackbuf->rect_procedural= texture_procedural;
stackbuf->node= node;
+ VECCOPY(stackbuf->procedural_offset, in[0]->vec);
+ VECCOPY(stackbuf->procedural_size, in[1]->vec);
+ stackbuf->procedural_type= CB_VAL;
out[0]->data= stackbuf;
}
@@ -123,6 +130,9 @@ static void node_composit_exec_texture(void *data, bNode *node, bNodeStack **in,
stackbuf->rect_procedural= texture_procedural;
stackbuf->node= node;
+ VECCOPY(stackbuf->procedural_offset, in[0]->vec);
+ VECCOPY(stackbuf->procedural_size, in[1]->vec);
+ stackbuf->procedural_type= CB_RGBA;
out[1]->data= stackbuf;
}
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_tonemap.c b/source/blender/nodes/intern/CMP_nodes/CMP_tonemap.c
index 662d8e8dde9..950ad97a397 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_tonemap.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_tonemap.c
@@ -63,7 +63,7 @@ static float avgLogLum(CompBuf *src, float* auto_key, float* Lav, float* Cav)
}
-void static tonemap(NodeTonemap* ntm, CompBuf* dst, CompBuf* src)
+static void tonemap(NodeTonemap* ntm, CompBuf* dst, CompBuf* src)
{
int x, y;
float dr, dg, db, al, igm = (ntm->gamma==0.f) ? 1 : (1.f / ntm->gamma);
@@ -130,13 +130,16 @@ static void node_composit_exec_tonemap(void *data, bNode *node, bNodeStack **in,
if ((img==NULL) || (out[0]->hasoutput==0)) return;
if (img->type != CB_RGBA)
- new = typecheck_compbuf(img, CB_RGBA);
- else
- new = dupalloc_compbuf(img);
+ img = typecheck_compbuf(img, CB_RGBA);
+
+ new = dupalloc_compbuf(img);
tonemap(node->storage, new, img);
out[0]->data = new;
+
+ if(img!=in[0]->data)
+ free_compbuf(img);
}
static void node_composit_init_tonemap(bNode* node)
diff --git a/source/blender/nodes/intern/CMP_nodes/CMP_zcombine.c b/source/blender/nodes/intern/CMP_nodes/CMP_zcombine.c
index 29cf8f34d54..daf61609692 100644
--- a/source/blender/nodes/intern/CMP_nodes/CMP_zcombine.c
+++ b/source/blender/nodes/intern/CMP_nodes/CMP_zcombine.c
@@ -45,6 +45,19 @@ static bNodeSocketType cmp_node_zcombine_out[]= {
{ -1, 0, "" }
};
+static void do_zcombine(bNode *node, float *out, float *src1, float *z1, float *src2, float *z2)
+{
+ if(*z1 <= *z2) {
+ QUATCOPY(out, src1);
+ }
+ else {
+ QUATCOPY(out, src2);
+
+ if(node->custom1)
+ *z1= *z2;
+ }
+}
+
static void do_zcombine_mask(bNode *node, float *out, float *z1, float *z2)
{
if(*z1 > *z2) {
@@ -67,43 +80,58 @@ static void do_zcombine_add(bNode *node, float *out, float *col1, float *col2, f
static void node_composit_exec_zcombine(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
{
+ RenderData *rd= data;
+ CompBuf *cbuf= in[0]->data;
+ CompBuf *zbuf;
+
/* stack order in: col z col z */
/* stack order out: col z */
- if(out[0]->hasoutput==0)
+ if(out[0]->hasoutput==0 && out[1]->hasoutput==0)
return;
/* no input image; do nothing now */
if(in[0]->data==NULL) {
return;
}
+
+ if(out[1]->hasoutput) {
+ /* copy or make a buffer for for the first z value, here we write result in */
+ if(in[1]->data)
+ zbuf= dupalloc_compbuf(in[1]->data);
+ else {
+ float *zval;
+ int tot= cbuf->x*cbuf->y;
+
+ zbuf= alloc_compbuf(cbuf->x, cbuf->y, CB_VAL, 1);
+ for(zval= zbuf->rect; tot; tot--, zval++)
+ *zval= in[1]->vec[0];
+ }
+ /* lazy coder hack */
+ node->custom1= 1;
+ out[1]->data= zbuf;
+ }
+ else {
+ node->custom1= 0;
+ zbuf= in[1]->data;
+ }
+
+ if(rd->scemode & R_FULL_SAMPLE) {
+ /* make output size of first input image */
+ CompBuf *stackbuf= alloc_compbuf(cbuf->x, cbuf->y, CB_RGBA, 1); // allocs
+
+ composit4_pixel_processor(node, stackbuf, in[0]->data, in[0]->vec, zbuf, in[1]->vec, in[2]->data, in[2]->vec,
+ in[3]->data, in[3]->vec, do_zcombine, CB_RGBA, CB_VAL, CB_RGBA, CB_VAL);
+
+ out[0]->data= stackbuf;
+ }
else {
/* make output size of first input image */
- CompBuf *cbuf= in[0]->data;
CompBuf *stackbuf= alloc_compbuf(cbuf->x, cbuf->y, CB_RGBA, 1); /* allocs */
- CompBuf *zbuf, *mbuf;
+ CompBuf *mbuf;
float *fp;
int x;
char *aabuf;
- if(out[1]->hasoutput) {
- /* copy or make a buffer for for the first z value, here we write result in */
- if(in[1]->data)
- zbuf= dupalloc_compbuf(in[1]->data);
- else {
- float *zval;
- int tot= cbuf->x*cbuf->y;
-
- zbuf= alloc_compbuf(cbuf->x, cbuf->y, CB_VAL, 1);
- for(zval= zbuf->rect; tot; tot--, zval++)
- *zval= in[1]->vec[0];
- }
- /* lazy coder hack */
- node->custom1= 1;
- }
- else {
- node->custom1= 0;
- zbuf= in[1]->data;
- }
/* make a mask based on comparison, optionally write zvalue */
mbuf= alloc_compbuf(cbuf->x, cbuf->y, CB_VAL, 1);
@@ -131,9 +159,8 @@ static void node_composit_exec_zcombine(void *data, bNode *node, bNodeStack **in
MEM_freeN(aabuf);
out[0]->data= stackbuf;
- if(node->custom1)
- out[1]->data= zbuf;
}
+
}
bNodeType cmp_node_zcombine= {
diff --git a/source/blender/nodes/intern/CMP_nodes/Makefile b/source/blender/nodes/intern/CMP_nodes/Makefile
index bf79d14c020..b70b591a588 100644
--- a/source/blender/nodes/intern/CMP_nodes/Makefile
+++ b/source/blender/nodes/intern/CMP_nodes/Makefile
@@ -42,3 +42,5 @@ CPPFLAGS += -I../../../blenlib
CPPFLAGS += -I../../../editors/include
CPPFLAGS += -I../../../imbuf
CPPFLAGS += -I../../../render/extern/include
+CPPFLAGS += -I$(NAN_GLEW)/include
+CPPFLAGS += -I$(OPENGL_HEADERS)
diff --git a/source/blender/nodes/intern/CMP_util.c b/source/blender/nodes/intern/CMP_util.c
index eee33e33ff5..f9805645115 100644
--- a/source/blender/nodes/intern/CMP_util.c
+++ b/source/blender/nodes/intern/CMP_util.c
@@ -122,6 +122,48 @@ void print_compbuf(char *str, CompBuf *cbuf)
}
+/* used for disabling node (similar code in drawnode.c for disable line) */
+void node_compo_pass_on(bNode *node, bNodeStack **nsin, bNodeStack **nsout)
+{
+ CompBuf *valbuf= NULL, *colbuf= NULL, *vecbuf= NULL;
+ bNodeSocket *sock;
+ int a;
+
+ /* connect the first value buffer in with first value out */
+ /* connect the first RGBA buffer in with first RGBA out */
+
+ /* test the inputs */
+ for(a=0, sock= node->inputs.first; sock; sock= sock->next, a++) {
+ if(nsin[a]->data) {
+ CompBuf *cbuf= nsin[a]->data;
+ if(cbuf->type==1 && valbuf==NULL) valbuf= cbuf;
+ if(cbuf->type==3 && vecbuf==NULL) vecbuf= cbuf;
+ if(cbuf->type==4 && colbuf==NULL) colbuf= cbuf;
+ }
+ }
+
+ /* outputs */
+ if(valbuf || colbuf || vecbuf) {
+ for(a=0, sock= node->outputs.first; sock; sock= sock->next, a++) {
+ if(nsout[a]->hasoutput) {
+ if(sock->type==SOCK_VALUE && valbuf) {
+ nsout[a]->data= pass_on_compbuf(valbuf);
+ valbuf= NULL;
+ }
+ if(sock->type==SOCK_VECTOR && vecbuf) {
+ nsout[a]->data= pass_on_compbuf(vecbuf);
+ vecbuf= NULL;
+ }
+ if(sock->type==SOCK_RGBA && colbuf) {
+ nsout[a]->data= pass_on_compbuf(colbuf);
+ colbuf= NULL;
+ }
+ }
+ }
+ }
+}
+
+
CompBuf *get_cropped_compbuf(rcti *drect, float *rectf, int rectx, int recty, int type)
{
CompBuf *cbuf;
@@ -183,17 +225,100 @@ CompBuf *scalefast_compbuf(CompBuf *inbuf, int newx, int newy)
return outbuf;
}
+void typecheck_compbuf_color(float *out, float *in, int outtype, int intype)
+{
+ if(intype == outtype) {
+ memcpy(out, in, sizeof(float)*outtype);
+ }
+ else if(outtype==CB_VAL) {
+ if(intype==CB_VEC2) {
+ *out= 0.5f*(in[0]+in[1]);
+ }
+ else if(intype==CB_VEC3) {
+ *out= 0.333333f*(in[0]+in[1]+in[2]);
+ }
+ else if(intype==CB_RGBA) {
+ *out= in[0]*0.35f + in[1]*0.45f + in[2]*0.2f;
+ }
+ }
+ else if(outtype==CB_VEC2) {
+ if(intype==CB_VAL) {
+ out[0]= in[0];
+ out[1]= in[0];
+ }
+ else if(intype==CB_VEC3) {
+ out[0]= in[0];
+ out[1]= in[1];
+ }
+ else if(intype==CB_RGBA) {
+ out[0]= in[0];
+ out[1]= in[1];
+ }
+ }
+ else if(outtype==CB_VEC3) {
+ if(intype==CB_VAL) {
+ out[0]= in[0];
+ out[1]= in[0];
+ out[2]= in[0];
+ }
+ else if(intype==CB_VEC2) {
+ out[0]= in[0];
+ out[1]= in[1];
+ out[2]= 0.0f;
+ }
+ else if(intype==CB_RGBA) {
+ out[0]= in[0];
+ out[1]= in[1];
+ out[2]= in[2];
+ }
+ }
+ else if(outtype==CB_RGBA) {
+ if(intype==CB_VAL) {
+ out[0]= in[0];
+ out[1]= in[0];
+ out[2]= in[0];
+ out[3]= 1.0f;
+ }
+ else if(intype==CB_VEC2) {
+ out[0]= in[0];
+ out[1]= in[1];
+ out[2]= 0.0f;
+ out[3]= 1.0f;
+ }
+ else if(intype==CB_VEC3) {
+ out[0]= in[0];
+ out[1]= in[1];
+ out[2]= in[2];
+ out[3]= 1.0f;
+ }
+ }
+}
+
CompBuf *typecheck_compbuf(CompBuf *inbuf, int type)
{
- if(inbuf && inbuf->type!=type && inbuf->rect_procedural==NULL) {
- CompBuf *outbuf= alloc_compbuf(inbuf->x, inbuf->y, type, 1);
- float *inrf= inbuf->rect;
- float *outrf= outbuf->rect;
- int x= inbuf->x*inbuf->y;
-
+ if(inbuf && inbuf->type!=type) {
+ CompBuf *outbuf;
+ float *inrf, *outrf;
+ int x;
+
+ outbuf= alloc_compbuf(inbuf->x, inbuf->y, type, 1);
+
/* warning note: xof and yof are applied in pixelprocessor, but should be copied otherwise? */
outbuf->xof= inbuf->xof;
outbuf->yof= inbuf->yof;
+
+ if(inbuf->rect_procedural) {
+ outbuf->rect_procedural= inbuf->rect_procedural;
+ VECCOPY(outbuf->procedural_size, inbuf->procedural_size);
+ VECCOPY(outbuf->procedural_offset, inbuf->procedural_offset);
+ outbuf->procedural_type= inbuf->procedural_type;
+ outbuf->node= inbuf->node;
+ return outbuf;
+ }
+
+ inrf= inbuf->rect;
+ outrf= outbuf->rect;
+ x= inbuf->x*inbuf->y;
if(type==CB_VAL) {
if(inbuf->type==CB_VEC2) {
@@ -460,6 +585,25 @@ CompBuf *valbuf_from_rgbabuf(CompBuf *cbuf, int channel)
return valbuf;
}
+static CompBuf *generate_procedural_preview(CompBuf *cbuf, int newx, int newy)
+{
+ CompBuf *outbuf;
+ float *outfp;
+ int xrad, yrad, x, y;
+
+ outbuf= alloc_compbuf(newx, newy, CB_RGBA, 1);
+
+ outfp= outbuf->rect;
+ xrad= outbuf->xrad;
+ yrad= outbuf->yrad;
+
+ for(y= -yrad; y<-yrad+outbuf->y; y++)
+ for(x= -xrad; x<-xrad+outbuf->x; x++, outfp+=outbuf->type)
+ cbuf->rect_procedural(cbuf, outfp, (float)x/(float)xrad, (float)y/(float)yrad);
+
+ return outbuf;
+}
+
void generate_preview(bNode *node, CompBuf *stackbuf)
{
bNodePreview *preview= node->preview;
@@ -467,7 +611,7 @@ void generate_preview(bNode *node, CompBuf *stackbuf)
if(preview && stackbuf) {
CompBuf *cbuf, *stackbuf_use;
- if(stackbuf->rect==NULL) return;
+ if(stackbuf->rect==NULL && stackbuf->rect_procedural==NULL) return;
stackbuf_use= typecheck_compbuf(stackbuf, CB_RGBA);
@@ -480,7 +624,10 @@ void generate_preview(bNode *node, CompBuf *stackbuf)
preview->xsize= (140*stackbuf->x)/stackbuf->y;
}
- cbuf= scalefast_compbuf(stackbuf_use, preview->xsize, preview->ysize);
+ if(stackbuf_use->rect_procedural)
+ cbuf= generate_procedural_preview(stackbuf_use, preview->xsize, preview->ysize);
+ else
+ cbuf= scalefast_compbuf(stackbuf_use, preview->xsize, preview->ysize);
/* this ensures free-compbuf does the right stuff */
SWAP(float *, cbuf->rect, node->preview->rect);
@@ -575,6 +722,36 @@ void gamma_correct_compbuf(CompBuf *img, int inversed)
}
}
+void premul_compbuf(CompBuf *img, int inversed)
+{
+ float *drect;
+ int x;
+
+ if(img->type!=CB_RGBA) return;
+
+ drect= img->rect;
+ if(inversed) {
+ for(x=img->x*img->y; x>0; x--, drect+=4) {
+ if(fabs(drect[3]) < 1e-5f) {
+ drect[0]= 0.0f;
+ drect[1]= 0.0f;
+ drect[2]= 0.0f;
+ }
+ else {
+ drect[0] /= drect[3];
+ drect[1] /= drect[3];
+ drect[2] /= drect[3];
+ }
+ }
+ }
+ else {
+ for(x=img->x*img->y; x>0; x--, drect+=4) {
+ drect[0] *= drect[3];
+ drect[1] *= drect[3];
+ drect[2] *= drect[3];
+ }
+ }
+}
diff --git a/source/blender/nodes/intern/CMP_util.h b/source/blender/nodes/intern/CMP_util.h
index 44f76b0822e..8443c022d17 100644
--- a/source/blender/nodes/intern/CMP_util.h
+++ b/source/blender/nodes/intern/CMP_util.h
@@ -92,6 +92,8 @@ typedef struct CompBuf {
int xof, yof; /* relative to center of target image */
void (*rect_procedural)(struct CompBuf *, float *, float, float);
+ float procedural_size[3], procedural_offset[3];
+ int procedural_type;
bNode *node; /* only in use for procedural bufs */
struct CompBuf *next, *prev; /* for pass-on, works nicer than reference counting */
@@ -117,10 +119,12 @@ CompBuf *dupalloc_compbuf(CompBuf *cbuf);
CompBuf *pass_on_compbuf(CompBuf *cbuf);
void free_compbuf(CompBuf *cbuf);
void print_compbuf(char *str, CompBuf *cbuf);
+void node_compo_pass_on(struct bNode *node, struct bNodeStack **nsin, struct bNodeStack **nsout);
CompBuf *get_cropped_compbuf(rcti *drect, float *rectf, int rectx, int recty, int type);
CompBuf *scalefast_compbuf(CompBuf *inbuf, int newx, int newy);
CompBuf *typecheck_compbuf(CompBuf *inbuf, int type);
+void typecheck_compbuf_color(float *out, float *in, int outtype, int intype);
float *compbuf_get_pixel(CompBuf *cbuf, float *rectf, int x, int y, int xrad, int yrad);
/* **************************************************** */
@@ -161,6 +165,7 @@ void do_hsva_to_rgba(bNode *node, float *out, float *in);
void do_ycca_to_rgba(bNode *node, float *out, float *in);
void gamma_correct_compbuf(CompBuf *img, int inversed);
+void premul_compbuf(CompBuf *img, int inversed);
void convolve(CompBuf* dst, CompBuf* in1, CompBuf* in2);
extern void node_ID_title_cb(void *node_v, void *unused_v);
diff --git a/source/blender/nodes/intern/Makefile b/source/blender/nodes/intern/Makefile
index 59c57e42bc1..7c9a67b6cc5 100644
--- a/source/blender/nodes/intern/Makefile
+++ b/source/blender/nodes/intern/Makefile
@@ -42,6 +42,8 @@ CPPFLAGS += -I../../blenlib
CPPFLAGS += -I../../editors/include
CPPFLAGS += -I../../imbuf
CPPFLAGS += -I../../render/extern/include
+CPPFLAGS += -I../../gpu
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
DIRS = SHD_nodes CMP_nodes
diff --git a/source/blender/nodes/intern/SHD_nodes/Makefile b/source/blender/nodes/intern/SHD_nodes/Makefile
index ca83c25d277..1369d346fc6 100644
--- a/source/blender/nodes/intern/SHD_nodes/Makefile
+++ b/source/blender/nodes/intern/SHD_nodes/Makefile
@@ -35,6 +35,8 @@ include nan_compile.mk
CFLAGS += $(LEVEL_1_C_WARNINGS)
+CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION)
+CPPFLAGS += -I../../../python
CPPFLAGS += -I../../../blenkernel
CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include
CPPFLAGS += -I../../../makesdna
@@ -42,3 +44,6 @@ CPPFLAGS += -I../../../blenlib
CPPFLAGS += -I../../../editors/include
CPPFLAGS += -I../../../imbuf
CPPFLAGS += -I../../../render/extern/include
+CPPFLAGS += -I../../../gpu
+CPPFLAGS += -I$(NAN_GLEW)/include
+CPPFLAGS += -I$(OPENGL_HEADERS)
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_camera.c b/source/blender/nodes/intern/SHD_nodes/SHD_camera.c
index 63260ff91ed..20136d75540 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_camera.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_camera.c
@@ -46,8 +46,13 @@ static void node_shader_exec_camera(void *data, bNode *node, bNodeStack **in, bN
VECCOPY(out[0]->vec, shi->co); /* get view vector */
out[1]->vec[0]= fabs(shi->co[2]); /* get view z-depth */
out[2]->vec[0]= Normalize(out[0]->vec); /* get view distance */
- }
}
+}
+
+static int gpu_shader_camera(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ return GPU_stack_link(mat, "camera", in, out, GPU_builtin(GPU_VIEW_POSITION));
+}
bNodeType sh_node_camera= {
/* *next,*prev */ NULL, NULL,
@@ -63,6 +68,7 @@ bNodeType sh_node_camera= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_camera
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_curves.c b/source/blender/nodes/intern/SHD_nodes/SHD_curves.c
index b6f1f8d52cd..d277547b636 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_curves.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_curves.c
@@ -56,6 +56,15 @@ static void node_shader_init_curve_vec(bNode* node)
node->storage= curvemapping_add(3, -1.0f, -1.0f, 1.0f, 1.0f);
}
+static int gpu_shader_curve_vec(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ float *array;
+ int size;
+
+ curvemapping_table_RGBA(node->storage, &array, &size);
+ return GPU_stack_link(mat, "curves_vec", in, out, GPU_texture(size, array));
+}
+
bNodeType sh_node_curve_vec= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_CURVE_VEC,
@@ -70,7 +79,8 @@ bNodeType sh_node_curve_vec= {
/* initfunc */ node_shader_init_curve_vec,
/* freestoragefunc */ node_free_curves,
/* copystoragefunc */ node_copy_curves,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_curve_vec
};
@@ -100,6 +110,15 @@ static void node_shader_init_curve_rgb(bNode *node)
node->storage= curvemapping_add(4, 0.0f, 0.0f, 1.0f, 1.0f);
}
+static int gpu_shader_curve_rgb(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ float *array;
+ int size;
+
+ curvemapping_table_RGBA(node->storage, &array, &size);
+ return GPU_stack_link(mat, "curves_rgb", in, out, GPU_texture(size, array));
+}
+
bNodeType sh_node_curve_rgb= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_CURVE_RGB,
@@ -114,6 +133,7 @@ bNodeType sh_node_curve_rgb= {
/* initfunc */ node_shader_init_curve_rgb,
/* freestoragefunc */ node_free_curves,
/* copystoragefunc */ node_copy_curves,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_curve_rgb
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_dynamic.c b/source/blender/nodes/intern/SHD_nodes/SHD_dynamic.c
index 1ba777a0533..4fcfe3a789a 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_dynamic.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_dynamic.c
@@ -27,221 +27,749 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#ifdef USE_PYNODES /* note: won't work without patch */
-
+#ifndef DISABLE_PYTHON
#include <Python.h>
+#include <compile.h>
#include <eval.h>
+#endif
#include "DNA_text_types.h"
#include "BKE_text.h"
+#include "BKE_utildefines.h"
+// XXX
+#if 0
+#ifndef DISABLE_PYTHON
#include "api2_2x/Node.h"
#include "api2_2x/gen_utils.h"
#include "BPY_extern.h"
+#endif
+#endif
#include "../SHD_util.h"
+// XXX
+#if 0
+static void node_dynamic_setup(bNode *node);
+static void node_dynamic_exec_cb(void *data, bNode *node, bNodeStack **in, bNodeStack **out);
+static void node_dynamic_free_storage_cb(bNode *node);
+
+#ifndef DISABLE_PYTHON
static PyObject *init_dynamicdict(void) {
- PyObject *newscriptdict= PyDict_New();
+ PyObject *newscriptdict;
+ PyGILState_STATE gilstate = PyGILState_Ensure();
+
+ newscriptdict= PyDict_New();
+
PyDict_SetItemString(newscriptdict, "__builtins__", PyEval_GetBuiltins());
EXPP_dict_set_item_str(newscriptdict, "__name__", PyString_FromString("__main__"));
+
+ PyGILState_Release(gilstate);
+
return newscriptdict;
}
+#endif
+
+static bNodeType *node_dynamic_find_typeinfo(ListBase *list, ID *id)
+{
+ bNodeType *ntype = list->first;
-static void free_dynamicdict(PyObject *dict) {
- if(dict!=NULL) {
- Py_DECREF(dict);
+ while(ntype) {
+ if (ntype->type == NODE_DYNAMIC && ntype->id == id)
+ break;
+ ntype = ntype->next;
}
+
+ return ntype; /* NULL if doesn't exist */
}
-static void node_dynamic_init(bNode *node) {
- NodeScriptDict *nsd= MEM_callocN(sizeof(NodeScriptDict), "node script dictionary");
- int type= node->custom2;
- node->custom2= 0;
- node->storage= nsd;
- if(type>=NODE_DYNAMIC_MENU) {
- if(type==NODE_DYNAMIC_MENU) {
- nodeMakeDynamicType(node);
- node->custom1= SH_NODE_DYNAMIC_NEW;
- } else {
- node->custom1= SH_NODE_DYNAMIC_ADDEXIST;
+static void node_dynamic_free_typeinfo_sockets(bNodeType *tinfo)
+{
+ bNodeSocketType *sock;
+
+ if (!tinfo) return;
+
+ if (tinfo->inputs) {
+ sock = tinfo->inputs;
+ while (sock->type != -1) {
+ MEM_freeN(sock->name);
+ sock++;
+ }
+ MEM_freeN(tinfo->inputs);
+ tinfo->inputs = NULL;
+ }
+ if (tinfo->outputs) {
+ sock = tinfo->outputs;
+ while (sock->type != -1) {
+ MEM_freeN(sock->name);
+ sock++;
+ }
+ MEM_freeN(tinfo->outputs);
+ tinfo->outputs = NULL;
+ }
+}
+
+static void node_dynamic_free_typeinfo(bNodeType *tinfo)
+{
+ if (!tinfo) return;
+
+ node_dynamic_free_typeinfo_sockets(tinfo);
+
+ if (tinfo->name) { MEM_freeN(tinfo->name); }
+
+ MEM_freeN(tinfo);
+}
+
+static void node_dynamic_free_sockets(bNode *node)
+{
+ BLI_freelistN(&node->inputs);
+ BLI_freelistN(&node->outputs);
+}
+
+/* For now we just remove the socket links. It's the safest
+ * route, since an update in the script may change completely the
+ * inputs and outputs. Trying to recreate the node links would be
+ * nicer for pynode authors, though. */
+static void node_dynamic_update_socket_links(bNode *node, bNodeTree *ntree)
+{
+ if (ntree) {
+ nodeVerifyType(ntree, node);
+ }
+ else {
+ Material *ma;
+
+ for (ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if (ma->nodetree) {
+ bNode *nd;
+ for (nd= ma->nodetree->nodes.first; nd; nd = nd->next) {
+ if (nd == node) nodeVerifyType(ma->nodetree, node);
+ }
+ }
}
- node->id= node->typeinfo->id;
- nodeDynamicParse(node);
- } else {
- if(node->custom1== SH_NODE_DYNAMIC_LOADED) {
- nodeMakeDynamicType(node);
- nodeDynamicParse(node);
- } else if(node->custom1== SH_NODE_DYNAMIC_ADDEXIST)
- nodeDynamicParse(node);
}
}
-static void node_dynamic_free(bNode *node)
+static void node_dynamic_free_storage_cb(bNode *node)
{
- NodeScriptDict *nsd= (NodeScriptDict *)(node->storage);
- BPy_Node *pynode= nsd->node;
- Py_XDECREF(pynode);
- free_dynamicdict((PyObject *)(nsd->dict));
+#ifndef DISABLE_PYTHON
+ NodeScriptDict *nsd;
+ PyObject *pydict;
+ BPy_Node *pynode;
+
+ if (!node->storage) return;
+ nsd = (NodeScriptDict *)(node->storage);
+ pydict = nsd->dict;
+ if (pydict) {
+ Py_DECREF(pydict);
+ }
+ pynode = nsd->node;
+ if (pynode) {
+ Py_DECREF(pynode);
+ }
+#endif
MEM_freeN(node->storage);
+ node->storage = NULL;
}
-static void node_dynamic_copy(bNode *orig_node, bNode *new_node)
+/* Disable pynode when its script fails */
+static void node_dynamic_disable(bNode *node)
{
- NodeScriptDict *nsd= (NodeScriptDict *)(orig_node->storage);
- new_node->storage= MEM_dupallocN(orig_node->storage);
- if(nsd->node)
- Py_INCREF((PyObject *)(nsd->node));
- if(nsd->dict)
- Py_INCREF((PyObject *)(nsd->dict));
+ node->custom1 = 0;
+ node->custom1 = BSET(node->custom1, NODE_DYNAMIC_ERROR);
}
-static void node_dynamic_exec(void *data, bNode *node, bNodeStack **in, bNodeStack **out) {
- BPy_Node *mynode = NULL;
- NodeScriptDict *nsd = NULL;
- PyObject *pyresult = NULL;
- PyObject *args = NULL;
- ShadeInput *shi= ((ShaderCallData *)data)->shi;
+/* Disable all pynodes using the given text (script) id */
+static void node_dynamic_disable_all_by_id(ID *id)
+{
+#ifndef DISABLE_PYTHON
+ Material *ma; /* XXX hardcoded for shaders */
- if(node->custom1==SH_NODE_DYNAMIC_NEW) {
- nodeDynamicParse(node);
- return;
+ for (ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if (ma->nodetree) {
+ bNode *nd;
+ bNodeTree *ntree = ma->nodetree;
+ for (nd= ntree->nodes.first; nd; nd= nd->next) {
+ if (nd->id == id) {
+ nd->custom1 = 0;
+ nd->custom1 = BSET(nd->custom1, NODE_DYNAMIC_ERROR);
+ }
+ }
+ }
}
+#endif
+}
- if(node->custom2<0)
- return;
+static void node_rem_socklist_links(bNodeTree *ntree, ListBase *lb)
+{
+ bNodeLink *link, *next;
+ bNodeSocket *sock;
- if(node->custom1==SH_NODE_DYNAMIC_READY || node->custom1==SH_NODE_DYNAMIC_UPDATED) {
- if(node->custom1== SH_NODE_DYNAMIC_UPDATED)
- node->custom1= SH_NODE_DYNAMIC_READY;
+ if (!lb) return;
- nsd = (NodeScriptDict *)node->storage;
+ for (sock= lb->first; sock; sock= sock->next) {
+ for (link= ntree->links.first; link; link= next) {
+ next= link->next;
+ if (link->fromsock==sock || link->tosock==sock) {
+ nodeRemLink(ntree, link);
+ }
+ }
+ }
+}
- mynode = (BPy_Node *)(nsd->node);
- if(mynode && PyCallable_Check((PyObject *)mynode)) {
- mynode->node= node;
- Node_SetStack(mynode, in, NODE_INPUTSTACK);
- Node_SetStack(mynode, out, NODE_OUTPUTSTACK);
- Node_SetShi(mynode, shi);
- args=Py_BuildValue("()");
- pyresult= PyObject_Call((PyObject *)mynode, args, NULL);
- if(!pyresult) {
- if(PyErr_Occurred()) {
- PyErr_Print();
- node->custom2= -1;
- } else {
- printf("PyObject_Call __call__ failed\n");
+/* XXX hardcoded for shaders */
+static void node_dynamic_rem_all_links(bNodeType *tinfo)
+{
+ Material *ma;
+ int in, out;
+
+ in = tinfo->inputs ? 1 : 0;
+ out = tinfo->outputs ? 1 : 0;
+
+ if (!in && !out) return;
+
+ for (ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if (ma->nodetree) {
+ bNode *nd;
+ bNodeTree *ntree = ma->nodetree;
+ for (nd= ntree->nodes.first; nd; nd= nd->next) {
+ if (nd->typeinfo == tinfo) {
+ if (in)
+ node_rem_socklist_links(ntree, &nd->inputs);
+ if (out)
+ node_rem_socklist_links(ntree, &nd->outputs);
}
}
- Py_XDECREF(pyresult);
- Py_DECREF(args);
}
}
}
-void nodeDynamicParse(struct bNode *node)
+/* node_dynamic_reset: clean a pynode, getting rid of all
+ * data dynamically created for it. */
+static void node_dynamic_reset(bNode *node, int unlink_text)
+{
+ bNodeType *tinfo, *tinfo_default;
+ Material *ma;
+
+ tinfo = node->typeinfo;
+ tinfo_default = node_dynamic_find_typeinfo(&node_all_shaders, NULL);
+
+ if ((tinfo == tinfo_default) && unlink_text) {
+ ID *textID = node->id;
+ /* already at default (empty) state, which happens if this node's
+ * script failed to parse at the first stage: definition. We're here
+ * because its text was removed from Blender. */
+ for (ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if (ma->nodetree) {
+ bNode *nd;
+ for (nd= ma->nodetree->nodes.first; nd; nd = nd->next) {
+ if (nd->id == textID) {
+ nd->id = NULL;
+ nd->custom1 = 0;
+ nd->custom1 = BSET(nd->custom1, NODE_DYNAMIC_NEW);
+ BLI_strncpy(nd->name, "Dynamic", 8);
+ return;
+ }
+ }
+ }
+ }
+ }
+
+ node_dynamic_rem_all_links(tinfo);
+ node_dynamic_free_typeinfo_sockets(tinfo);
+
+ /* reset all other XXX shader nodes sharing this typeinfo */
+ for (ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if (ma->nodetree) {
+ bNode *nd;
+ for (nd= ma->nodetree->nodes.first; nd; nd = nd->next) {
+ if (nd->typeinfo == tinfo) {
+ node_dynamic_free_storage_cb(nd);
+ node_dynamic_free_sockets(nd);
+ //node_dynamic_update_socket_links(nd, ma->nodetree);
+ nd->typeinfo = tinfo_default;
+ if (unlink_text) {
+ nd->id = NULL;
+ nd->custom1 = 0;
+ nd->custom1 = BSET(nd->custom1, NODE_DYNAMIC_NEW);
+ BLI_strncpy(nd->name, "Dynamic", 8);
+ }
+ }
+ }
+ }
+ }
+
+ /* XXX hardcoded for shaders: */
+ if (tinfo->id) { BLI_remlink(&node_all_shaders, tinfo); }
+ node_dynamic_free_typeinfo(tinfo);
+}
+
+/* Special case of the above function: for working pynodes
+ * that were saved on a .blend but fail for some reason when
+ * the file is opened. We need this because pynodes are initialized
+ * before G.main. */
+static void node_dynamic_reset_loaded(bNode *node)
+{
+ bNodeType *tinfo = node->typeinfo;
+
+ node_dynamic_rem_all_links(tinfo);
+ node_dynamic_free_typeinfo_sockets(tinfo);
+ node_dynamic_free_storage_cb(node);
+ /* XXX hardcoded for shaders: */
+ if (tinfo->id) { BLI_remlink(&node_all_shaders, tinfo); }
+
+ node_dynamic_free_typeinfo(tinfo);
+ node->typeinfo = node_dynamic_find_typeinfo(&node_all_shaders, NULL);
+}
+
+int nodeDynamicUnlinkText(ID *txtid) {
+ Material *ma;
+ bNode *nd;
+
+ /* find one node that uses this text */
+ for (ma= G.main->mat.first; ma; ma= ma->id.next) {
+ if (ma->nodetree) {
+ for (nd= ma->nodetree->nodes.first; nd; nd = nd->next) {
+ if ((nd->type == NODE_DYNAMIC) && (nd->id == txtid)) {
+ node_dynamic_reset(nd, 1); /* found, reset all */
+ return 1;
+ }
+ }
+ }
+ }
+ return 0; /* no pynodes used this text */
+}
+
+static void node_dynamic_pyerror_print(bNode *node)
+{
+#ifndef DISABLE_PYTHON
+ PyGILState_STATE gilstate = PyGILState_Ensure();
+
+ fprintf(stderr, "\nError in dynamic node script \"%s\":\n", node->name);
+ if (PyErr_Occurred()) { PyErr_Print(); }
+ else { fprintf(stderr, "Not a valid dynamic node Python script.\n"); }
+
+ PyGILState_Release(gilstate);
+#endif
+}
+
+static void node_dynamic_register_type(bNode *node)
+{
+ nodeRegisterType(&node_all_shaders, node->typeinfo);
+ /* nodeRegisterType copied it to a new one, so we
+ * free the typeinfo itself, but not what it
+ * points to: */
+ MEM_freeN(node->typeinfo);
+ node->typeinfo = node_dynamic_find_typeinfo(&node_all_shaders, node->id);
+ MEM_freeN(node->typeinfo->name);
+ node->typeinfo->name = BLI_strdup(node->name);
+}
+
+#ifndef DISABLE_PYTHON
+/* node_dynamic_get_pynode:
+ * Find the pynode definition from the script */
+static PyObject *node_dynamic_get_pynode(PyObject *dict)
{
- BPy_Node *pynode= NULL;
- PyObject *dict= NULL;
PyObject *key= NULL;
- PyObject *value= NULL;
- PyObject *testinst= NULL;
+ Py_ssize_t pos = 0;
+ PyObject *value = NULL;
+
+ /* script writer specified a node? */
+ value = PyDict_GetItemString(dict, "__node__");
+
+ if (value) {
+ if (PyObject_TypeCheck(value, &PyType_Type)) {
+ Py_INCREF(value);
+ return value;
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "expected class object derived from Scripted node");
+ return NULL;
+ }
+ }
+
+ /* case not, search for it in the script's global dictionary */
+ while (PyDict_Next(dict, &pos, &key, &value)) {
+ /* skip names we know belong to other available objects */
+ if (strcmp("Socket", PyString_AsString(key)) == 0)
+ continue;
+ else if (strcmp("Scripted", PyString_AsString(key)) == 0)
+ continue;
+ /* naive: we grab the first ob of type 'type': */
+ else if (PyObject_TypeCheck(value, &PyType_Type)) {
+ Py_INCREF(value);
+ return value;
+ }
+ }
+
+ PyErr_SetString(PyExc_TypeError,
+ "no PyNode definition found in the script!");
+ return NULL;
+}
+#endif /* DISABLE_PYTHON */
+
+static int node_dynamic_parse(struct bNode *node)
+{
+#ifdef DISABLE_PYTHON
+ return -1;
+#else
+ PyObject *dict= NULL;
+ PyObject *pynode_data= NULL;
+ PyObject *pynode= NULL;
PyObject *args= NULL;
- int pos = 0;
- NodeScriptDict *nsd= NULL;
+ NodeScriptDict *nsd = NULL;
PyObject *pyresult = NULL;
- PyObject *pycompiled = NULL;
- Text *txt = NULL;
- char *buf= NULL;
+ char *buf = NULL;
+ int is_valid_script = 0;
+ PyGILState_STATE gilstate;
+
+ if (!node->id || !node->storage)
+ return 0;
+
+ /* READY, no need to be here */
+ if (BTST(node->custom1, NODE_DYNAMIC_READY))
+ return 0;
+
+ /* for threading */
+ gilstate = PyGILState_Ensure();
+
+ nsd = (NodeScriptDict *)node->storage;
+
+ dict = (PyObject *)(nsd->dict);
+ buf = txt_to_buf((Text *)node->id);
+
+ pyresult = PyRun_String(buf, Py_file_input, dict, dict);
+
+ MEM_freeN(buf);
+
+ if (!pyresult) {
+ if (BTST(node->custom1, NODE_DYNAMIC_LOADED)) {
+ node_dynamic_disable(node);
+ } else {
+ node_dynamic_disable_all_by_id(node->id);
+ }
+ node_dynamic_pyerror_print(node);
+ PyGILState_Release(gilstate);
+ return -1;
+ }
+
+ Py_DECREF(pyresult);
+
+ pynode_data = node_dynamic_get_pynode(dict);
+
+ if (pynode_data) {
+ BPy_NodeSocketLists *socklists = Node_CreateSocketLists(node);
+
+ args = Py_BuildValue("(O)", socklists);
+
+ /* init it to get the input and output sockets */
+ pynode = PyObject_Call(pynode_data, args, NULL);
+
+ Py_DECREF(pynode_data);
+ Py_DECREF(socklists);
+ Py_DECREF(args);
+
+ if (!PyErr_Occurred() && pynode && pytype_is_pynode(pynode)) {
+ InitNode((BPy_Node *)(pynode), node);
+ nsd->node = pynode;
+ node->typeinfo->execfunc = node_dynamic_exec_cb;
+ is_valid_script = 1;
+
+ /* for NEW, LOADED, REPARSE */
+ if (BNTST(node->custom1, NODE_DYNAMIC_ADDEXIST)) {
+ node->typeinfo->pydict = dict;
+ node->typeinfo->pynode = pynode;
+ node->typeinfo->id = node->id;
+ if (BNTST(node->custom1, NODE_DYNAMIC_LOADED))
+ nodeAddSockets(node, node->typeinfo);
+ if (BNTST(node->custom1, NODE_DYNAMIC_REPARSE))
+ node_dynamic_register_type(node);
+ }
+
+ node->custom1 = 0;
+ node->custom1 = BSET(node->custom1, NODE_DYNAMIC_READY);
+ }
+ }
+
+ PyGILState_Release(gilstate);
+
+ if (!is_valid_script) { /* not a valid pynode script */
+ node_dynamic_disable_all_by_id(node->id);
+ node_dynamic_pyerror_print(node);
+ return -1;
+ }
+
+ return 0;
+#endif
+}
+
+/* node_dynamic_setup: prepare for execution (state: NODE_DYNAMIC_READY)
+ * pynodes already linked to a script (node->id != NULL). */
+static void node_dynamic_setup(bNode *node)
+{
+#ifndef DISABLE_PYTHON
+ NodeScriptDict *nsd = NULL;
+ bNodeTree *nodetree = NULL;
+ bNodeType *ntype = NULL;
+ PyGILState_STATE gilstate;
- if(! node->id) {
+ /* Possible cases:
+ * NEW
+ * ADDEXIST
+ * LOADED
+ * REPARSE
+ * ERROR
+ * READY
+ */
+
+ /* NEW, but not linked to a script: link default (empty) typeinfo */
+ if (!node->id) {
+ node->typeinfo = node_dynamic_find_typeinfo(&node_all_shaders,
+ NULL);
return;
}
- if(node->custom1!=SH_NODE_DYNAMIC_READY) {
- txt = (Text *)node->id;
- nsd = (NodeScriptDict *)node->storage;
+ /* READY, no need to be here */
+ if (BTST(node->custom1, NODE_DYNAMIC_READY))
+ return;
+
+ gilstate = PyGILState_Ensure();
+
+ /* ERROR, reset to (empty) defaults */
+ if (BCLR(node->custom1, NODE_DYNAMIC_ERROR) == 0) {
+ node_dynamic_reset(node, 0);
+ PyGILState_Release(gilstate);
+ return;
+ }
+
+ /* User asked to update this pynode, prepare it for reparsing */
+ if (BTST(node->custom1, NODE_DYNAMIC_REPARSE)) {
+ int needs_parsing = 1;
+
+ node->custom1 = BSET(node->custom1, NODE_DYNAMIC_NEW);
+
+ if (BTST(node->custom1, NODE_DYNAMIC_ERROR)) {
+ node->custom1 = BCLR(node->custom1, NODE_DYNAMIC_REPARSE);
+ ntype = node_dynamic_find_typeinfo(&node_all_shaders, node->id);
+
+ if (ntype) {
+ node->typeinfo = ntype;
+ node->custom1 = BSET(node->custom1, NODE_DYNAMIC_ADDEXIST);
+ node->custom1 = BCLR(node->custom1, NODE_DYNAMIC_ERROR);
+ needs_parsing = 0;
+ }
+ else { nodeMakeDynamicType(node); }
+
+ } else {
+ node_dynamic_rem_all_links(node->typeinfo);
+ node_dynamic_free_typeinfo_sockets(node->typeinfo);
+ node_dynamic_update_socket_links(node, NULL);
+ node_dynamic_free_storage_cb(node);
+ }
- if(nsd->dict==NULL && (node->custom1==SH_NODE_DYNAMIC_NEW||node->custom1==SH_NODE_DYNAMIC_LOADED)) {
- nsd->dict= init_dynamicdict();
- } else if(nsd->dict==NULL && node->custom1==SH_NODE_DYNAMIC_ADDEXIST) {
- nsd->dict= node->typeinfo->pydict;
- nsd->node= node->typeinfo->pynode;
- Py_INCREF((PyObject *)(nsd->dict));
- Py_INCREF((PyObject *)(nsd->node));
- node->custom1= SH_NODE_DYNAMIC_READY;
+ if (needs_parsing) {
+ nsd = MEM_callocN(sizeof(NodeScriptDict), "node script dictionary");
+ nsd->dict = init_dynamicdict();
+ node->storage = nsd;
+ /* prepared, now reparse: */
+ node_dynamic_parse(node);
+ PyGILState_Release(gilstate);
return;
}
- dict= (PyObject *)(nsd->dict);
+ }
+ else if (BTST(node->custom1, NODE_DYNAMIC_LOADED)) {
+ /* when loading from a .blend we don't have G.main yet, so we
+ * quickly abuse node->storage in ntreeInitTypes (node.c) to have
+ * our nodetree ptr (needed if a pynode script that worked before
+ * saving the .blend for some reason fails upon loading): */
+ nodetree = (bNodeTree *)node->storage;
+ node->storage = NULL;
+ }
- if(node->custom1!=SH_NODE_DYNAMIC_ADDEXIST) {
- buf = txt_to_buf( txt );
- /*printf("Running script (%s, %d)...", node->name, node->custom1);*/
- pyresult = PyRun_String(buf, Py_file_input, dict, dict);
- /*printf(" done\n");*/
+ if (node->storage)
+ fprintf(stderr, "\nDEBUG: PYNODES ERROR: non NULL node->storage in node_dynamic_setup()\n");
- MEM_freeN(buf);
+ nsd = MEM_callocN(sizeof(NodeScriptDict), "node script dictionary");
+ node->storage = nsd;
+
+ /* NEW, LOADED or REPARSE */
+ if (BNTST(node->custom1, NODE_DYNAMIC_ADDEXIST)) {
+ /* check if there's already a bNodeType linked to this script */
+ /* (XXX hardcoded for shader nodes for now) */
+ ntype = node_dynamic_find_typeinfo(&node_all_shaders, node->id);
- if(!pyresult) {
- if(PyErr_Occurred()) {
- PyErr_Print();
- }
- Py_XDECREF(pyresult);
- return;
+ if (ntype) { /* if so, reuse it */
+ node->typeinfo = ntype;
+ /* so this is actually an ADDEXIST type */
+ node->custom1 = BSET(node->custom1, NODE_DYNAMIC_ADDEXIST);
+ }
+ else { /* create bNodeType for this pynode */
+ nodeMakeDynamicType(node);
+ nsd->dict = init_dynamicdict();
+ if ((node_dynamic_parse(node) == -1) && nodetree) {
+ node_dynamic_reset_loaded(node);
}
+ PyGILState_Release(gilstate);
+ return;
+ }
+ }
- Py_DECREF(pyresult);
+ /* ADDEXIST: new pynode linked to an already registered dynamic type,
+ * we just reuse existing py dict and pynode */
+ nsd->dict = node->typeinfo->pydict;
+ nsd->node = node->typeinfo->pynode;
- while(PyDict_Next( (PyObject *)(nsd->dict), &pos, &key, &value) ) {
- if(PyObject_TypeCheck(value, &PyType_Type)==1) {
- BPy_DefinitionMap *outputdef= Node_CreateOutputDefMap(node);
- BPy_DefinitionMap *inputdef= Node_CreateInputDefMap(node);
-
- args= Py_BuildValue("(OO)", inputdef, outputdef);
- testinst= PyObject_Call(value, args, NULL);
-
- Py_DECREF(outputdef);
- Py_DECREF(inputdef);
- if(testinst && PyObject_TypeCheck(testinst, &Node_Type)==1) {
- Py_INCREF(testinst);
- Py_INCREF(dict);
- InitNode((BPy_Node *)(testinst), node);
- nsd->node= testinst;
- node->typeinfo->execfunc= node_dynamic_exec;
- if(node->custom1== SH_NODE_DYNAMIC_NEW || node->custom1== SH_NODE_DYNAMIC_LOADED) {
- node->typeinfo->pynode= testinst;
- node->typeinfo->pydict= nsd->dict;
- node->typeinfo->id= node->id;
- nodeAddSockets(node, node->typeinfo);
- nodeRegisterType(&node_all_shaders, node->typeinfo);
- node->custom1= SH_NODE_DYNAMIC_READY;
- }
- break;
- }
- Py_DECREF(args);
- }
- }
+ Py_INCREF((PyObject *)(nsd->dict));
+ Py_INCREF((PyObject *)(nsd->node));
+
+ if (BTST(node->custom1, NODE_DYNAMIC_NEW)) {
+ nodeAddSockets(node, node->typeinfo);
+ node->custom1 = BCLR(node->custom1, NODE_DYNAMIC_NEW);
+ }
+
+ node->custom1 = BCLR(node->custom1, NODE_DYNAMIC_ADDEXIST);
+ node->custom1 = BSET(node->custom1, NODE_DYNAMIC_READY);
+
+ PyGILState_Release(gilstate);
+#endif /* DISABLE_PYTHON */
+ return;
+}
+
+/* node_dynamic_init_cb callback: called when a pynode is created.
+ * The pynode type is passed via node->custom2. It can be:
+ * 0: for loaded empty nodes
+ * NODE_DYNAMIC_MENU: for the default Dynamic node type
+ * > NODE_DYNAMIC_MENU: for the new types defined by scripts
+*/
+static void node_dynamic_init_cb(bNode *node) {
+ int type = node->custom2;
+
+ node->custom2 = 0;
+
+ if (type >= NODE_DYNAMIC_MENU) {
+ node->custom1 = 0;
+
+ if (type == NODE_DYNAMIC_MENU) {
+ node->custom1 = BSET(node->custom1, NODE_DYNAMIC_NEW);
+ return;
}
+
+ node->custom1 = BSET(node->custom1, NODE_DYNAMIC_ADDEXIST);
+ node->id = node->typeinfo->id;
}
+
+ node_dynamic_setup(node);
+}
+
+/* node_dynamic_copy_cb: pynode copy callback */
+static void node_dynamic_copy_cb(bNode *orig_node, bNode *new_node)
+{
+#ifdef DISABLE_PYTHON
+ return;
+#else
+ NodeScriptDict *nsd;
+ PyGILState_STATE gilstate;
+
+ if (!orig_node->storage) return;
+
+ nsd = (NodeScriptDict *)(orig_node->storage);
+ new_node->storage = MEM_dupallocN(orig_node->storage);
+
+ gilstate = PyGILState_Ensure();
+
+ if (nsd->node)
+ Py_INCREF((PyObject *)(nsd->node));
+ if (nsd->dict)
+ Py_INCREF((PyObject *)(nsd->dict));
+
+ PyGILState_Release(gilstate);
+#endif
}
+/* node_dynamic_exec_cb: the execution callback called per pixel
+ * during rendering. */
+static void node_dynamic_exec_cb(void *data, bNode *node, bNodeStack **in, bNodeStack **out) {
+#ifdef DISABLE_PYTHON
+ return;
+#else
+ BPy_Node *mynode = NULL;
+ NodeScriptDict *nsd = NULL;
+ PyObject *pyresult = NULL;
+ PyObject *args = NULL;
+ ShadeInput *shi;
+ PyGILState_STATE gilstate;
+
+ if (!node->id)
+ return;
+
+ /*if (G.scene->r.threads > 1)
+ return;*/
+
+ if (BTST2(node->custom1, NODE_DYNAMIC_NEW, NODE_DYNAMIC_REPARSE)) {
+ node_dynamic_setup(node);
+ return;
+ }
+
+ if (BTST(node->custom1, NODE_DYNAMIC_ERROR)) {
+ if (node->storage) node_dynamic_setup(node);
+ return;
+ }
+
+ if (BTST(node->custom1, NODE_DYNAMIC_READY)) {
+ nsd = (NodeScriptDict *)node->storage;
+ mynode = (BPy_Node *)(nsd->node);
+
+
+ if (mynode && PyCallable_Check((PyObject *)mynode)) {
+
+ gilstate = PyGILState_Ensure();
+
+ mynode->node = node;
+ shi = ((ShaderCallData *)data)->shi;
+
+ Node_SetStack(mynode, in, NODE_INPUTSTACK);
+ Node_SetStack(mynode, out, NODE_OUTPUTSTACK);
+ Node_SetShi(mynode, shi);
+
+ args=Py_BuildValue("()");
+ pyresult= PyObject_Call((PyObject *)mynode, args, NULL);
+ Py_DECREF(args);
-bNodeType sh_node_dynamic = {
+ if (!pyresult) {
+ PyGILState_Release(gilstate);
+ node_dynamic_disable_all_by_id(node->id);
+ node_dynamic_pyerror_print(node);
+ node_dynamic_setup(node);
+ return;
+ }
+ Py_DECREF(pyresult);
+ PyGILState_Release(gilstate);
+ }
+ }
+#endif
+}
+
+bNodeType node_dynamic_typeinfo = {
/* next, prev */ NULL, NULL,
- /* type code */ SH_NODE_DYNAMIC,
+ /* type code */ NODE_DYNAMIC,
/* name */ "Dynamic",
/* width+range */ 150, 60, 300,
/* class+opts */ NODE_CLASS_OP_DYNAMIC, NODE_OPTIONS,
/* input sock */ NULL,
/* output sock */ NULL,
/* storage */ "NodeScriptDict",
- /* execfunc */ node_dynamic_exec,
+ /* execfunc */ node_dynamic_exec_cb,
/* butfunc */ NULL,
- /* initfunc */ node_dynamic_init,
- /* freefunc */ node_dynamic_free,
- /* copyfunc */ node_dynamic_copy,
+ /* initfunc */ node_dynamic_init_cb,
+ /* freefunc */ node_dynamic_free_storage_cb,
+ /* copyfunc */ node_dynamic_copy_cb,
/* id */ NULL
};
-#endif /* USE_PYNODES */
+#else
+
+bNodeType node_dynamic_typeinfo = {NULL};
+
+#endif
+
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_geom.c b/source/blender/nodes/intern/SHD_nodes/SHD_geom.c
index 24395059c60..bc345759b98 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_geom.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_geom.c
@@ -29,6 +29,7 @@
#include "../SHD_util.h"
+#include "DNA_customdata_types.h"
/* **************** GEOMETRY ******************** */
@@ -124,6 +125,18 @@ static void node_shader_init_geometry(bNode *node)
node->storage= MEM_callocN(sizeof(NodeGeometry), "NodeGeometry");
}
+static int gpu_shader_geom(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ NodeGeometry *ngeo= (NodeGeometry*)node->storage;
+ GPUNodeLink *orco = GPU_attribute(CD_ORCO, "");
+ GPUNodeLink *mtface = GPU_attribute(CD_MTFACE, ngeo->uvname);
+ GPUNodeLink *mcol = GPU_attribute(CD_MCOL, ngeo->colname);
+
+ return GPU_stack_link(mat, "geom", in, out,
+ GPU_builtin(GPU_VIEW_POSITION), GPU_builtin(GPU_VIEW_NORMAL),
+ GPU_builtin(GPU_INVERSE_VIEW_MATRIX), orco, mtface, mcol);
+}
+
/* node type definition */
bNodeType sh_node_geom= {
/* *next,*prev */ NULL, NULL,
@@ -139,6 +152,7 @@ bNodeType sh_node_geom= {
/* initfunc */ node_shader_init_geometry,
/* freestoragefunc */ node_free_standard_storage,
/* copystoragefunc */ node_copy_standard_storage,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_geom
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_hueSatVal.c b/source/blender/nodes/intern/SHD_nodes/SHD_hueSatVal.c
index 8c07a2d1dc8..1b7b2dfb8e7 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_hueSatVal.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_hueSatVal.c
@@ -54,9 +54,7 @@ static void do_hue_sat_fac(bNode *node, float *out, float *hue, float *sat, floa
hsv[0]+= (*hue - 0.5f);
if(hsv[0]>1.0) hsv[0]-=1.0; else if(hsv[0]<0.0) hsv[0]+= 1.0;
hsv[1]*= *sat;
- if(hsv[1]>1.0) hsv[1]= 1.0; else if(hsv[1]<0.0) hsv[1]= 0.0;
hsv[2]*= *val;
- if(hsv[2]>1.0) hsv[2]= 1.0; else if(hsv[2]<0.0) hsv[2]= 0.0;
hsv_to_rgb(hsv[0], hsv[1], hsv[2], col, col+1, col+2);
out[0]= mfac*in[0] + *fac*col[0];
@@ -73,6 +71,12 @@ static void node_shader_exec_hue_sat(void *data, bNode *node, bNodeStack **in, b
do_hue_sat_fac(node, out[0]->vec, in[0]->vec, in[1]->vec, in[2]->vec, in[4]->vec, in[3]->vec);
}
+
+static int gpu_shader_hue_sat(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ return GPU_stack_link(mat, "hue_sat", in, out);
+}
+
bNodeType sh_node_hue_sat= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_HUE_SAT,
@@ -87,7 +91,8 @@ bNodeType sh_node_hue_sat= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_hue_sat
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_invert.c b/source/blender/nodes/intern/SHD_nodes/SHD_invert.c
index 4d1ce282fce..72ee1483ecf 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_invert.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_invert.c
@@ -64,6 +64,11 @@ bNodeStack **out)
VECCOPY(out[0]->vec, col);
}
+static int gpu_shader_invert(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ return GPU_stack_link(mat, "invert", in, out);
+}
+
bNodeType sh_node_invert= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_INVERT,
@@ -78,6 +83,7 @@ bNodeType sh_node_invert= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_invert
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_mapping.c b/source/blender/nodes/intern/SHD_nodes/SHD_mapping.c
index 589954c8f7b..c081929a2fc 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_mapping.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_mapping.c
@@ -69,6 +69,20 @@ static void node_shader_init_mapping(bNode *node)
node->storage= add_mapping();
}
+static int gpu_shader_mapping(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ TexMapping *texmap= node->storage;
+ float domin= (texmap->flag & TEXMAP_CLIP_MIN) != 0;
+ float domax= (texmap->flag & TEXMAP_CLIP_MAX) != 0;
+ GPUNodeLink *tmat = GPU_uniform((float*)texmap->mat);
+ GPUNodeLink *tmin = GPU_uniform(texmap->min);
+ GPUNodeLink *tmax = GPU_uniform(texmap->max);
+ GPUNodeLink *tdomin = GPU_uniform(&domin);
+ GPUNodeLink *tdomax = GPU_uniform(&domax);
+
+ return GPU_stack_link(mat, "mapping", in, out, tmat, tmin, tmax, tdomin, tdomax);
+}
+
bNodeType sh_node_mapping= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_MAPPING,
@@ -83,7 +97,8 @@ bNodeType sh_node_mapping= {
/* initfunc */ node_shader_init_mapping,
/* freestoragefunc */ node_free_standard_storage,
/* copystoragefunc */ node_copy_standard_storage,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_mapping
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_material.c b/source/blender/nodes/intern/SHD_nodes/SHD_material.c
index bdceb134c0d..c0a2534ac4a 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_material.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_material.c
@@ -54,7 +54,6 @@ static bNodeSocketType sh_node_material_ext_in[]= {
{ SOCK_VALUE, 1, "Refl", 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
{ SOCK_VECTOR, 1, "Normal", 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f},
{ SOCK_RGBA, 1, "Mirror", 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 1, "AmbCol", 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
{ SOCK_VALUE, 1, "Ambient", 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
{ SOCK_VALUE, 1, "Emit", 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
{ SOCK_VALUE, 1, "SpecTra", 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
@@ -117,8 +116,6 @@ static void node_shader_exec_material(void *data, bNode *node, bNodeStack **in,
if (node->type == SH_NODE_MATERIAL_EXT) {
if(in[MAT_IN_MIR]->hasinput)
nodestack_get_vec(&shi->mirr, SOCK_VECTOR, in[MAT_IN_MIR]);
- if(in[MAT_IN_AMBCOL]->hasinput)
- nodestack_get_vec(&shi->ambr, SOCK_VECTOR, in[MAT_IN_AMBCOL]);
if(in[MAT_IN_AMB]->hasinput)
nodestack_get_vec(&shi->amb, SOCK_VALUE, in[MAT_IN_AMB]);
if(in[MAT_IN_EMIT]->hasinput)
@@ -185,6 +182,77 @@ static void node_shader_init_material(bNode* node)
node->custom1= SH_NODE_MAT_DIFF|SH_NODE_MAT_SPEC;
}
+static int gpu_shader_material(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ if(node->id) {
+ GPUShadeInput shi;
+ GPUShadeResult shr;
+
+ GPU_shadeinput_set(mat, (Material*)node->id, &shi);
+
+ /* write values */
+ if(in[MAT_IN_COLOR].hasinput)
+ shi.rgb = in[MAT_IN_COLOR].link;
+
+ if(in[MAT_IN_SPEC].hasinput)
+ shi.specrgb = in[MAT_IN_SPEC].link;
+
+ if(in[MAT_IN_REFL].hasinput)
+ shi.refl = in[MAT_IN_REFL].link;
+
+ /* retrieve normal */
+ if(in[MAT_IN_NORMAL].hasinput) {
+ GPUNodeLink *tmp;
+ shi.vn = in[MAT_IN_NORMAL].link;
+ GPU_link(mat, "vec_math_normalize", shi.vn, &shi.vn, &tmp);
+ }
+
+ /* custom option to flip normal */
+ if(node->custom1 & SH_NODE_MAT_NEG)
+ GPU_link(mat, "vec_math_negate", shi.vn, &shi.vn);
+
+ if (node->type == SH_NODE_MATERIAL_EXT) {
+ if(in[MAT_IN_AMB].hasinput)
+ shi.amb= in[MAT_IN_AMB].link;
+ if(in[MAT_IN_EMIT].hasinput)
+ shi.emit= in[MAT_IN_EMIT].link;
+ if(in[MAT_IN_ALPHA].hasinput)
+ shi.alpha= in[MAT_IN_ALPHA].link;
+ }
+
+ GPU_shaderesult_set(&shi, &shr); /* clears shr */
+
+ /* write to outputs */
+ if(node->custom1 & SH_NODE_MAT_DIFF) {
+ if(node->custom1 & SH_NODE_MAT_SPEC)
+ out[MAT_OUT_COLOR].link= shr.combined;
+ else
+ out[MAT_OUT_COLOR].link= shr.diff;
+ }
+ else if(node->custom1 & SH_NODE_MAT_SPEC) {
+ out[MAT_OUT_COLOR].link= shr.spec;
+ }
+ else
+ GPU_link(mat, "set_rgb_zero", &out[MAT_OUT_COLOR].link);
+
+ GPU_link(mat, "mtex_alpha_to_col", out[MAT_OUT_COLOR].link, shr.alpha, &out[MAT_OUT_COLOR].link);
+
+ out[MAT_OUT_ALPHA].link = shr.alpha; //
+
+ if(node->custom1 & SH_NODE_MAT_NEG)
+ GPU_link(mat, "vec_math_negate", shi.vn, &shi.vn);
+ out[MAT_OUT_NORMAL].link = shi.vn;
+
+ if (node->type == SH_NODE_MATERIAL_EXT) {
+ out[MAT_OUT_DIFFUSE].link = shr.diff;
+ out[MAT_OUT_SPEC].link = shr.spec;
+ }
+
+ return 1;
+ }
+
+ return 0;
+}
bNodeType sh_node_material= {
/* *next,*prev */ NULL, NULL,
@@ -200,8 +268,8 @@ bNodeType sh_node_material= {
/* initfunc */ node_shader_init_material,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
-
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_material
};
bNodeType sh_node_material_ext= {
@@ -218,7 +286,7 @@ bNodeType sh_node_material_ext= {
/* initfunc */ node_shader_init_material,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
-
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_material
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_math.c b/source/blender/nodes/intern/SHD_nodes/SHD_math.c
index 95162e508d5..050c2cdcc95 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_math.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_math.c
@@ -174,10 +174,66 @@ bNodeStack **out)
else
out[0]->vec[0]= (int)(in[1]->vec[0] + 0.5f);
}
- break;
+ break;
+ case 15: /* Less Than */
+ {
+ if( in[0]->vec[0] < in[1]->vec[0] )
+ out[0]->vec[0]= 1.0f;
+ else
+ out[0]->vec[0]= 0.0f;
+ }
+ break;
+ case 16: /* Greater Than */
+ {
+ if( in[0]->vec[0] > in[1]->vec[0] )
+ out[0]->vec[0]= 1.0f;
+ else
+ out[0]->vec[0]= 0.0f;
+ }
+ break;
}
}
+static int gpu_shader_math(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ static char *names[] = {"math_add", "math_subtract", "math_multiply",
+ "math_divide", "math_sine", "math_cosine", "math_tangnet", "math_asin",
+ "math_acos", "math_atan", "math_pow", "math_log", "math_min", "math_max",
+ "math_round", "math_less_than", "math_greater_than"};
+
+ switch (node->custom1) {
+ case 0:
+ case 1:
+ case 2:
+ case 3:
+ case 10:
+ case 11:
+ case 12:
+ case 13:
+ case 15:
+ case 16:
+ GPU_stack_link(mat, names[node->custom1], NULL, out,
+ GPU_socket(&in[0]), GPU_socket(&in[1]));
+ break;
+ case 4:
+ case 5:
+ case 6:
+ case 7:
+ case 8:
+ case 9:
+ case 14:
+ if(in[0].hasinput || !in[1].hasinput)
+ GPU_stack_link(mat, names[node->custom1], NULL, out, GPU_socket(&in[0]));
+ else
+ GPU_stack_link(mat, names[node->custom1], NULL, out, GPU_socket(&in[1]));
+ break;
+ default:
+ return 0;
+ }
+
+ return 1;
+}
+
bNodeType sh_node_math= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_MATH,
@@ -192,6 +248,7 @@ bNodeType sh_node_math= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_math
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_mixRgb.c b/source/blender/nodes/intern/SHD_nodes/SHD_mixRgb.c
index dba70253fda..2da1dee5623 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_mixRgb.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_mixRgb.c
@@ -60,6 +60,17 @@ static void node_shader_exec_mix_rgb(void *data, bNode *node, bNodeStack **in, b
VECCOPY(out[0]->vec, col);
}
+static int gpu_shader_mix_rgb(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ static char *names[] = {"mix_blend", "mix_add", "mix_mult", "mix_sub",
+ "mix_screen", "mix_div", "mix_diff", "mix_dark", "mix_light",
+ "mix_overlay", "mix_dodge", "mix_burn", "mix_hue", "mix_sat",
+ "mix_val", "mix_color"};
+
+ return GPU_stack_link(mat, names[node->custom1], in, out);
+}
+
+
bNodeType sh_node_mix_rgb= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_MIX_RGB,
@@ -74,6 +85,7 @@ bNodeType sh_node_mix_rgb= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_mix_rgb
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_normal.c b/source/blender/nodes/intern/SHD_nodes/SHD_normal.c
index f1ffd3446af..9d4ea1ccf67 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_normal.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_normal.c
@@ -57,6 +57,14 @@ static void node_shader_exec_normal(void *data, bNode *node, bNodeStack **in, bN
out[1]->vec[0]= -INPR(out[0]->vec, vec);
}
+static int gpu_shader_normal(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ bNodeSocket *sock= node->outputs.first;
+ GPUNodeLink *vec = GPU_uniform(sock->ns.vec);
+
+ return GPU_stack_link(mat, "normal", in, out, vec);
+}
+
bNodeType sh_node_normal= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_NORMAL,
@@ -71,6 +79,7 @@ bNodeType sh_node_normal= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_normal
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_output.c b/source/blender/nodes/intern/SHD_nodes/SHD_output.c
index 0a9a30c452b..76856cfd2e8 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_output.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_output.c
@@ -62,6 +62,19 @@ static void node_shader_exec_output(void *data, bNode *node, bNodeStack **in, bN
}
}
+static int gpu_shader_output(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ GPUNodeLink *outlink;
+
+ /*if(in[1].hasinput)
+ GPU_material_enable_alpha(mat);*/
+
+ GPU_stack_link(mat, "output_node", in, out, &outlink);
+ GPU_material_output_link(mat, outlink);
+
+ return 1;
+}
+
bNodeType sh_node_output= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_OUTPUT,
@@ -76,7 +89,8 @@ bNodeType sh_node_output= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_output
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_rgb.c b/source/blender/nodes/intern/SHD_nodes/SHD_rgb.c
index 4e56e26d3ad..1aa1a2ffc33 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_rgb.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_rgb.c
@@ -42,6 +42,14 @@ static void node_shader_exec_rgb(void *data, bNode *node, bNodeStack **in, bNode
VECCOPY(out[0]->vec, sock->ns.vec);
}
+static int gpu_shader_rgb(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ bNodeSocket *sock= node->outputs.first;
+ GPUNodeLink *vec = GPU_uniform(sock->ns.vec);
+
+ return GPU_stack_link(mat, "set_rgba", in, out, vec);
+}
+
bNodeType sh_node_rgb= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_RGB,
@@ -56,6 +64,7 @@ bNodeType sh_node_rgb= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_rgb
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_sepcombRGB.c b/source/blender/nodes/intern/SHD_nodes/SHD_sepcombRGB.c
index 2b52a8e2229..6d5df2a1321 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_sepcombRGB.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_sepcombRGB.c
@@ -48,6 +48,11 @@ static void node_shader_exec_seprgb(void *data, bNode *node, bNodeStack **in, bN
out[2]->vec[0] = in[0]->vec[2];
}
+static int gpu_shader_seprgb(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ return GPU_stack_link(mat, "separate_rgb", in, out);
+}
+
bNodeType sh_node_seprgb= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_SEPRGB,
@@ -62,7 +67,8 @@ bNodeType sh_node_seprgb= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_seprgb
};
@@ -86,6 +92,11 @@ static void node_shader_exec_combrgb(void *data, bNode *node, bNodeStack **in, b
out[0]->vec[2] = in[2]->vec[0];
}
+static int gpu_shader_combrgb(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ return GPU_stack_link(mat, "combine_rgb", in, out);
+}
+
bNodeType sh_node_combrgb= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_COMBRGB,
@@ -100,6 +111,7 @@ bNodeType sh_node_combrgb= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_combrgb
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_squeeze.c b/source/blender/nodes/intern/SHD_nodes/SHD_squeeze.c
index 30abad666c4..d3480a6ae9d 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_squeeze.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_squeeze.c
@@ -54,6 +54,11 @@ bNodeStack **out)
out[0]->vec[0] = 1.0f / (1.0f + pow(2.71828183,-((vec[0]-vec[2])*vec[1]))) ;
}
+static int gpu_shader_squeeze(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ return GPU_stack_link(mat, "squeeze", in, out);
+}
+
bNodeType sh_node_squeeze= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_SQUEEZE,
@@ -68,6 +73,7 @@ bNodeType sh_node_squeeze= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_squeeze
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_texture.c b/source/blender/nodes/intern/SHD_nodes/SHD_texture.c
index ace11a20d42..31dbde940fd 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_texture.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_texture.c
@@ -27,6 +27,8 @@
* ***** END GPL LICENSE BLOCK *****
*/
+#include "DNA_texture_types.h"
+
#include "../SHD_util.h"
/* **************** TEXTURE ******************** */
@@ -110,6 +112,18 @@ static void node_shader_exec_texture(void *data, bNode *node, bNodeStack **in, b
}
}
+static int gpu_shader_texture(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ Tex *tex = (Tex*)node->id;
+
+ if(tex && tex->type == TEX_IMAGE && tex->ima) {
+ GPUNodeLink *texlink = GPU_image(tex->ima, NULL);
+ return GPU_stack_link(mat, "texture_image", in, out, texlink);
+ }
+ else
+ return 0;
+}
+
bNodeType sh_node_texture= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_TEXTURE,
@@ -124,7 +138,8 @@ bNodeType sh_node_texture= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_texture
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_valToRgb.c b/source/blender/nodes/intern/SHD_nodes/SHD_valToRgb.c
index cf7e33d9dca..301c0cb7031 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_valToRgb.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_valToRgb.c
@@ -59,6 +59,15 @@ static void node_shader_init_valtorgb(bNode *node)
node->storage= add_colorband(1);
}
+static int gpu_shader_valtorgb(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ float *array;
+ int size;
+
+ colorband_table_RGBA(node->storage, &array, &size);
+ return GPU_stack_link(mat, "valtorgb", in, out, GPU_texture(size, array));
+}
+
bNodeType sh_node_valtorgb= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_VALTORGB,
@@ -73,7 +82,8 @@ bNodeType sh_node_valtorgb= {
/* initfunc */ node_shader_init_valtorgb,
/* freestoragefunc */ node_free_standard_storage,
/* copystoragefunc */ node_copy_standard_storage,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_valtorgb
};
@@ -96,6 +106,11 @@ static void node_shader_exec_rgbtobw(void *data, bNode *node, bNodeStack **in, b
out[0]->vec[0]= in[0]->vec[0]*0.35f + in[0]->vec[1]*0.45f + in[0]->vec[2]*0.2f;
}
+static int gpu_shader_rgbtobw(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ return GPU_stack_link(mat, "rgbtobw", in, out);
+}
+
bNodeType sh_node_rgbtobw= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_RGBTOBW,
@@ -110,7 +125,8 @@ bNodeType sh_node_rgbtobw= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_rgbtobw
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_value.c b/source/blender/nodes/intern/SHD_nodes/SHD_value.c
index 57ef7226066..768ef3cda3d 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_value.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_value.c
@@ -42,7 +42,13 @@ static void node_shader_exec_value(void *data, bNode *node, bNodeStack **in, bNo
out[0]->vec[0]= sock->ns.vec[0];
}
+static int gpu_shader_value(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ bNodeSocket *sock= node->outputs.first;
+ GPUNodeLink *vec = GPU_uniform(sock->ns.vec);
+ return GPU_stack_link(mat, "set_value", in, out, vec);
+}
bNodeType sh_node_value= {
/* *next,*prev */ NULL, NULL,
@@ -58,7 +64,8 @@ bNodeType sh_node_value= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_value
};
diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_vectMath.c b/source/blender/nodes/intern/SHD_nodes/SHD_vectMath.c
index 8d0a4b3abe3..96db8db18a6 100644
--- a/source/blender/nodes/intern/SHD_nodes/SHD_vectMath.c
+++ b/source/blender/nodes/intern/SHD_nodes/SHD_vectMath.c
@@ -99,6 +99,34 @@ static void node_shader_exec_vect_math(void *data, bNode *node, bNodeStack **in,
}
+static int gpu_shader_vect_math(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out)
+{
+ static char *names[] = {"vec_math_add", "vec_math_subtract",
+ "vec_math_average", "vec_math_dot", "vec_math_cross",
+ "vec_math_normalize"};
+
+ switch (node->custom1) {
+ case 0:
+ case 1:
+ case 2:
+ case 3:
+ case 4:
+ GPU_stack_link(mat, names[node->custom1], NULL, out,
+ GPU_socket(&in[0]), GPU_socket(&in[1]));
+ break;
+ case 5:
+ if(in[0].hasinput || !in[1].hasinput)
+ GPU_stack_link(mat, names[node->custom1], NULL, out, GPU_socket(&in[0]));
+ else
+ GPU_stack_link(mat, names[node->custom1], NULL, out, GPU_socket(&in[1]));
+ break;
+ default:
+ return 0;
+ }
+
+ return 1;
+}
+
bNodeType sh_node_vect_math= {
/* *next,*prev */ NULL, NULL,
/* type code */ SH_NODE_VECT_MATH,
@@ -113,6 +141,7 @@ bNodeType sh_node_vect_math= {
/* initfunc */ NULL,
/* freestoragefunc */ NULL,
/* copystoragefunc */ NULL,
- /* id */ NULL
+ /* id */ NULL, NULL, NULL,
+ /* gpufunc */ gpu_shader_vect_math
};
diff --git a/source/blender/nodes/intern/SHD_util.c b/source/blender/nodes/intern/SHD_util.c
index c9f58fbce49..f673834d2b7 100644
--- a/source/blender/nodes/intern/SHD_util.c
+++ b/source/blender/nodes/intern/SHD_util.c
@@ -164,7 +164,7 @@ void nodeShaderSynchronizeID(bNode *node, int copyto)
case MAT_IN_MIR:
VECCOPY(&ma->mirr, sock->ns.vec); break;
case MAT_IN_AMB:
- VECCOPY(&ma->ambr, sock->ns.vec); break;
+ ma->amb= sock->ns.vec[0]; break;
case MAT_IN_EMIT:
ma->emit= sock->ns.vec[0]; break;
case MAT_IN_SPECTRA:
@@ -188,7 +188,7 @@ void nodeShaderSynchronizeID(bNode *node, int copyto)
case MAT_IN_MIR:
VECCOPY(sock->ns.vec, &ma->mirr); break;
case MAT_IN_AMB:
- VECCOPY(sock->ns.vec, &ma->ambr); break;
+ sock->ns.vec[0]= ma->amb; break;
case MAT_IN_EMIT:
sock->ns.vec[0]= ma->emit; break;
case MAT_IN_SPECTRA:
diff --git a/source/blender/nodes/intern/SHD_util.h b/source/blender/nodes/intern/SHD_util.h
index fcab420f3f2..0d9783fdd4b 100644
--- a/source/blender/nodes/intern/SHD_util.h
+++ b/source/blender/nodes/intern/SHD_util.h
@@ -72,6 +72,8 @@
#include "RE_pipeline.h"
#include "RE_shader_ext.h"
+#include "GPU_material.h"
+
//XXX #include "butspace.h"
//XXX #include "wm_event_types.h"
@@ -100,13 +102,12 @@ typedef struct ShaderCallData {
#define MAT_IN_REFL 2
#define MAT_IN_NORMAL 3
#define MAT_IN_MIR 4
-#define MAT_IN_AMBCOL 5
-#define MAT_IN_AMB 6
-#define MAT_IN_EMIT 7
-#define MAT_IN_SPECTRA 8
-#define MAT_IN_RAY_MIRROR 9
-#define MAT_IN_ALPHA 10
-#define MAT_IN_TRANSLUCENCY 11
+#define MAT_IN_AMB 5
+#define MAT_IN_EMIT 6
+#define MAT_IN_SPECTRA 7
+#define MAT_IN_RAY_MIRROR 8
+#define MAT_IN_ALPHA 9
+#define MAT_IN_TRANSLUCENCY 10
/* output socket defines */
#define MAT_OUT_COLOR 0
diff --git a/source/blender/python/BPY_extern.h b/source/blender/python/BPY_extern.h
index 8da2f126de0..1761ce14ed6 100644
--- a/source/blender/python/BPY_extern.h
+++ b/source/blender/python/BPY_extern.h
@@ -6,11 +6,7 @@
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
-<<<<<<< .mine
* of the License, or (at your option) any later version.
-=======
- * of the License, or (at your option) any later version.
->>>>>>> .r13159
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -35,6 +31,7 @@
#define BPY_EXTERN_H
extern char bprogname[]; /* holds a copy of argv[0], from creator.c */
+extern char btempdir[]; /* use this to store a valid temp directory */
struct Text; /* defined in DNA_text_types.h */
struct ID; /* DNA_ID.h */
@@ -44,13 +41,14 @@ struct ScriptLink; /* DNA_scriptlink_types.h */
struct ListBase; /* DNA_listBase.h */
struct SpaceText; /* DNA_space_types.h */
struct SpaceScript; /* DNA_space_types.h */
-struct Script; /* BPI_script.h */
struct ScrArea; /* DNA_screen_types.h */
struct bScreen; /* DNA_screen_types.h */
struct bConstraint; /* DNA_constraint_types.h */
struct bPythonConstraint; /* DNA_constraint_types.h */
struct bConstraintOb; /* DNA_constraint_types.h */
struct bConstraintTarget; /* DNA_constraint_types.h*/
+struct Script; /* DNA_screen_types.h */
+struct BPyMenu;
#ifdef __cplusplus
extern "C" {
#endif
@@ -79,24 +77,30 @@ extern "C" {
void BPY_pyconstraint_target(struct bPythonConstraint *con, struct bConstraintTarget *ct);
void BPY_pyconstraint_update(struct Object *owner, struct bConstraint *con);
int BPY_is_pyconstraint(struct Text *text);
+ void BPY_free_pyconstraint_links(struct Text *text);
void BPY_start_python( int argc, char **argv );
void BPY_end_python( void );
void BPY_post_start_python( void );
void init_syspath( int first_time );
void syspath_append( char *dir );
-
+ void BPY_rebuild_syspath( void );
+ int BPY_path_update( void );
+
int BPY_Err_getLinenumber( void );
const char *BPY_Err_getFilename( void );
int BPY_txt_do_python_Text( struct Text *text );
int BPY_menu_do_python( short menutype, int event );
- void BPY_run_python_script( char *filename );
+ int BPY_menu_do_shortcut( short menutype, unsigned short key, unsigned short modifiers );
+ int BPY_menu_invoke( struct BPyMenu *pym, short menutype );
+ void BPY_run_python_script( const char *filename );
+ int BPY_run_script(struct Script *script);
void BPY_free_compiled_text( struct Text *text );
void BPY_clear_bad_scriptlinks( struct Text *byebye );
int BPY_has_onload_script( void );
- void BPY_do_all_scripts( short event );
+ void BPY_do_all_scripts( short event, short anim );
int BPY_check_all_scriptlinks( struct Text *text );
void BPY_do_pyscript( struct ID *id, short event );
void BPY_free_scriptlink( struct ScriptLink *slink );
@@ -108,7 +112,7 @@ extern "C" {
int BPY_has_spacehandler(struct Text *text, struct ScrArea *sa);
void BPY_screen_free_spacehandlers(struct bScreen *sc);
int BPY_do_spacehandlers(struct ScrArea *sa, unsigned short event,
- unsigned short space_event);
+ short eventValue, unsigned short space_event);
void BPY_pydriver_update(void);
float BPY_pydriver_eval(struct IpoDriver *driver);
@@ -124,7 +128,10 @@ extern "C" {
unsigned short event, short val, char ascii );
void BPY_clear_script( struct Script *script );
void BPY_free_finished_script( struct Script *script );
-
+ void BPY_scripts_clear_pyobjects( void );
+
+ void error_pyscript( void );
+
/* void BPY_Err_Handle(struct Text *text); */
/* void BPY_clear_bad_scriptlink(struct ID *id, struct Text *byebye); */
/* void BPY_clear_bad_scriptlist(struct ListBase *, struct Text *byebye); */
diff --git a/source/blender/python/Makefile b/source/blender/python/Makefile
index d0eb6ddbae5..c830fbb3ccf 100644
--- a/source/blender/python/Makefile
+++ b/source/blender/python/Makefile
@@ -1,12 +1,12 @@
#
-# $Id: Makefile
+# $Id: Makefile 14444 2008-04-16 22:40:48Z hos $
#
# ***** BEGIN GPL LICENSE BLOCK *****
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
+# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
diff --git a/source/blender/quicktime/SConscript b/source/blender/quicktime/SConscript
index d9ab68251dd..49ecfc94a5d 100644
--- a/source/blender/quicktime/SConscript
+++ b/source/blender/quicktime/SConscript
@@ -2,7 +2,7 @@
Import ('env')
source_files = ['apple/quicktime_import.c',
- 'apple/quicktime_export.c']
+ 'apple/quicktime_export.c']
incs = ['.',
'../quicktime',
@@ -20,10 +20,10 @@ incs = ['.',
incs.append(env['BF_QUICKTIME_INC'])
if env['OURPLATFORM'] in ['win32-vc', 'darwin']:
- types = ['core', 'player']
- priorities = [115, 200]
+ types = ['core', 'player']
+ priorities = [115, 200]
else:
- types = ['core']
- priorities = [115]
+ types = ['core']
+ priorities = [115]
env.BlenderLib ('bf_quicktime', sources=source_files, includes=incs, defines=['WITH_QUICKTIME'], libtype=types, priority=priorities)
diff --git a/source/blender/quicktime/apple/quicktime_export.c b/source/blender/quicktime/apple/quicktime_export.c
index 06c5d9132bc..ca025a0b8a3 100644
--- a/source/blender/quicktime/apple/quicktime_export.c
+++ b/source/blender/quicktime/apple/quicktime_export.c
@@ -307,6 +307,7 @@ static void QT_EndCreateMyVideoTrack(void)
static void QT_StartAddVideoSamplesToMedia (const Rect *trackFrame, int rectx, int recty)
{
+ SCTemporalSettings gTemporalSettings;
OSErr err = noErr;
qtexport->ibuf = IMB_allocImBuf (rectx, recty, 32, IB_rect, 0);
@@ -325,7 +326,18 @@ static void QT_StartAddVideoSamplesToMedia (const Rect *trackFrame, int rectx, i
SCDefaultPixMapSettings (qtdata->theComponent, qtexport->thePixMap, true);
- SCSetInfo(qtdata->theComponent, scTemporalSettingsType, &qtdata->gTemporalSettings);
+ // workaround for crash with H.264, which requires an upgrade to
+ // the new callback based api for proper encoding, but that's not
+ // really compatible with rendering out frames sequentially
+ gTemporalSettings = qtdata->gTemporalSettings;
+ if(qtdata->gSpatialSettings.codecType == kH264CodecType) {
+ if(gTemporalSettings.temporalQuality != codecMinQuality) {
+ fprintf(stderr, "Only minimum quality compression supported for QuickTime H.264.\n");
+ gTemporalSettings.temporalQuality = codecMinQuality;
+ }
+ }
+
+ SCSetInfo(qtdata->theComponent, scTemporalSettingsType, &gTemporalSettings);
SCSetInfo(qtdata->theComponent, scSpatialSettingsType, &qtdata->gSpatialSettings);
SCSetInfo(qtdata->theComponent, scDataRateSettingsType, &qtdata->aDataRateSetting);
@@ -415,7 +427,7 @@ void makeqtstring (char *string) {
if (string==0) return;
strcpy(string, G.scene->r.pic);
- BLI_convertstringcode(string, G.sce, G.scene->r.cfra);
+ BLI_convertstringcode(string, G.sce);
BLI_make_existing_file(string);
@@ -569,13 +581,13 @@ static void check_renderbutton_framerate(void) {
CheckError( err, "SCSetInfo error" );
if(qtdata->gTemporalSettings.frameRate == 1571553) { // 23.98 fps
- qtdata->kVideoTimeScale = 2400;
+ qtdata->kVideoTimeScale = 24000;
qtdata->duration = 1001;
} else if (qtdata->gTemporalSettings.frameRate == 1964113) { // 29.97 fps
- qtdata->kVideoTimeScale = 3000;
+ qtdata->kVideoTimeScale = 30000;
qtdata->duration = 1001;
} else if (qtdata->gTemporalSettings.frameRate == 3928227) { // 59.94 fps
- qtdata->kVideoTimeScale = 6000;
+ qtdata->kVideoTimeScale = 60000;
qtdata->duration = 1001;
} else {
qtdata->kVideoTimeScale = (qtdata->gTemporalSettings.frameRate >> 16) * 100;
@@ -644,13 +656,13 @@ int get_qtcodec_settings(void)
G.scene->r.frs_sec = 24;
G.scene->r.frs_sec_base = 1.001;
} else if (qtdata->gTemporalSettings.frameRate == 1964113) { // 29.97 fps
- qtdata->kVideoTimeScale = 3000;
+ qtdata->kVideoTimeScale = 30000;
qtdata->duration = 1001;
G.scene->r.frs_sec = 30;
G.scene->r.frs_sec_base = 1.001;
} else if (qtdata->gTemporalSettings.frameRate == 3928227) { // 59.94 fps
- qtdata->kVideoTimeScale = 6000;
+ qtdata->kVideoTimeScale = 60000;
qtdata->duration = 1001;
G.scene->r.frs_sec = 60;
@@ -658,7 +670,7 @@ int get_qtcodec_settings(void)
} else {
double fps = qtdata->gTemporalSettings.frameRate;
- qtdata->kVideoTimeScale = 600;
+ qtdata->kVideoTimeScale = 60000;
qtdata->duration = qtdata->kVideoTimeScale / (qtdata->gTemporalSettings.frameRate / 65536);
if ((qtdata->gTemporalSettings.frameRate & 0xffff) == 0) {
diff --git a/source/blender/radiosity/CMakeLists.txt b/source/blender/radiosity/CMakeLists.txt
index 9ffa0e61d6a..e76f7409f99 100644
--- a/source/blender/radiosity/CMakeLists.txt
+++ b/source/blender/radiosity/CMakeLists.txt
@@ -27,9 +27,9 @@
FILE(GLOB SRC intern/source/*.c)
SET(INC
- extern/include ../blenlib ../blenkernel ../makesdna ../include
+ extern/include ../blenlib ../blenkernel ../makesdna ../editors/include
../../../intern/guardedalloc ../render/extern/include
- ../render/intern/include ../editors/include
+ ../render/intern/include ../blenloader ../../../extern/glew/include
)
BLENDERLIB_NOLIST(blender_radiosity "${SRC}" "${INC}")
diff --git a/source/blender/radiosity/SConscript b/source/blender/radiosity/SConscript
index 9939690b664..528b4e29c04 100644
--- a/source/blender/radiosity/SConscript
+++ b/source/blender/radiosity/SConscript
@@ -5,7 +5,7 @@ sources = env.Glob('intern/source/*.c')
incs = 'extern/include ../blenlib ../blenkernel ../makesdna ../editors/include'
incs += ' #/intern/guardedalloc ../render/extern/include'
-incs += ' ../render/intern/include'
+incs += ' ../render/intern/include ../blenloader #/extern/glew/include'
incs += ' ' + env['BF_OPENGL_INC']
diff --git a/source/blender/radiosity/intern/source/Makefile b/source/blender/radiosity/intern/source/Makefile
index bd4ebce742f..44b38de9bae 100644
--- a/source/blender/radiosity/intern/source/Makefile
+++ b/source/blender/radiosity/intern/source/Makefile
@@ -36,6 +36,7 @@ include nan_compile.mk
CFLAGS += $(LEVEL_1_C_WARNINGS)
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(OPENGL_HEADERS)
# not very neat....
@@ -44,6 +45,7 @@ CPPFLAGS += -I../../../blenlib
CPPFLAGS += -I../../../makesdna
CPPFLAGS += -I../../../imbuf
CPPFLAGS += -I../../../
+CPPFLAGS += -I../../../blenloader
CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include
# first /include is my own includes, second are the external includes
diff --git a/source/blender/radiosity/intern/source/radfactors.c b/source/blender/radiosity/intern/source/radfactors.c
index 0065d993b15..1a400ff57a8 100644
--- a/source/blender/radiosity/intern/source/radfactors.c
+++ b/source/blender/radiosity/intern/source/radfactors.c
@@ -51,9 +51,9 @@
#include "RE_render_ext.h" /* for `RE_zbufferall_radio and RE_zbufferall_radio */
/* locals */
-void rad_setmatrices(RadView *vw);
-void clearsubflagelem(RNode *rn);
-void setsubflagelem(RNode *rn);
+static void rad_setmatrices(RadView *vw);
+static void clearsubflagelem(RNode *rn);
+static void setsubflagelem(RNode *rn);
RadView hemitop, hemiside;
@@ -252,7 +252,7 @@ void rad_make_hocos(RadView *vw)
/* } */
}
-void rad_setmatrices(RadView *vw) /* for hemi's */
+static void rad_setmatrices(RadView *vw) /* for hemi's */
{
float up1[3], len, twist;
@@ -626,7 +626,7 @@ void minmaxradelemfilt(RNode *rn, float *min, float *max, float *errmin, float *
}
}
-void setsubflagelem(RNode *rn)
+static void setsubflagelem(RNode *rn)
{
if(rn->down1) {
@@ -638,7 +638,7 @@ void setsubflagelem(RNode *rn)
}
}
-void clearsubflagelem(RNode *rn)
+static void clearsubflagelem(RNode *rn)
{
if(rn->down1) {
@@ -739,11 +739,9 @@ void subdivideshootElements(int it)
}
}
if(rn) {
- min[0]= min[1]= min[2]= 1.0e10;
- max[0]= max[1]= max[2]= -1.0e10;
+ INIT_MINMAX(min, max);
/* errmin and max are the filtered colors */
- errmin[0]= errmin[1]= errmin[2]= 1.0e10;
- errmax[0]= errmax[1]= errmax[2]= -1.0e10;
+ INIT_MINMAX(errmin, errmax);
minmaxradelemfilt(rp->first, min, max, errmin, errmax);
/* if small difference between colors: no subdiv */
diff --git a/source/blender/radiosity/intern/source/radnode.c b/source/blender/radiosity/intern/source/radnode.c
index ca37d021639..fa23ca5da57 100644
--- a/source/blender/radiosity/intern/source/radnode.c
+++ b/source/blender/radiosity/intern/source/radnode.c
@@ -48,15 +48,17 @@
#include "radio.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
/* locals */
-void *malloc_fast(int size);
-void *calloc_fast(int size);
-void free_fast(void *poin, int siz);
-void deleteTriNodes(RNode *node);
+static void *malloc_fast(int size);
+static void *calloc_fast(int size);
+static void free_fast(void *poin, int siz);
+static void deleteTriNodes(RNode *node);
/* lower because of local type define */
/* void check_mallocgroup(MallocGroup *mg); */
@@ -118,7 +120,7 @@ void check_mallocgroup(MallocGroup *mg)
printf("fastmalloc: shouldnt be here\n");
}
-void *malloc_fast(int size)
+static void *malloc_fast(int size)
{
MallocGroup *mg;
void *retval;
@@ -152,7 +154,7 @@ void *malloc_fast(int size)
return mg->data;
}
-void *calloc_fast(int size)
+static void *calloc_fast(int size)
{
void *poin;
@@ -162,17 +164,17 @@ void *calloc_fast(int size)
return poin;
}
-void free_fast(void *poin, int size)
+static void free_fast(void *poin, int size)
{
MallocGroup *mg;
- long val;
+ intptr_t val;
mg= MallocBase.last;
while(mg) {
if(mg->size==size) {
- if( ((long)poin) >= ((long)mg->data) ) {
- if( ((long)poin) < ((long)(mg->data+MAL_GROUPSIZE*size)) ) {
- val= ((long)poin) - ((long)mg->data);
+ if( ((intptr_t)poin) >= ((intptr_t)mg->data) ) {
+ if( ((intptr_t)poin) < ((intptr_t)(mg->data+MAL_GROUPSIZE*size)) ) {
+ val= ((intptr_t)poin) - ((intptr_t)mg->data);
val/= size;
mg->curfree= val;
mg->flags[val]= 0;
@@ -954,7 +956,7 @@ int comparelevel(RNode *node, RNode *nb, int level)
return 1;
}
-void deleteTriNodes(RNode *node) /* both children of node */
+static void deleteTriNodes(RNode *node) /* both children of node */
{
RNode *n1, *n2;
diff --git a/source/blender/radiosity/intern/source/radpreprocess.c b/source/blender/radiosity/intern/source/radpreprocess.c
index 345a5911ac8..eec75942da0 100644
--- a/source/blender/radiosity/intern/source/radpreprocess.c
+++ b/source/blender/radiosity/intern/source/radpreprocess.c
@@ -64,6 +64,8 @@
#include "radio.h"
+#include "BLO_sys_types.h" // for intptr_t support
+
void setparelem(RNode *rn, RPatch *par);
void splitconnected()
@@ -171,7 +173,7 @@ int vergedge(const void *v1,const void *v2)
void addedge(float *v1, float *v2, EdSort *es)
{
- if( ((long)v1)<((long)v2) ) {
+ if( ((intptr_t)v1)<((intptr_t)v2) ) {
es->v1= v1;
es->v2= v2;
}
@@ -279,7 +281,7 @@ void setedgepointers()
MEM_freeN(esblock);
}
-int materialIndex(Material *ma)
+static int materialIndex(Material *ma)
{
int i = 0;
for(i=0;i< RG.totmat; i++)
diff --git a/source/blender/radiosity/intern/source/radrender.c b/source/blender/radiosity/intern/source/radrender.c
index 9a97690de54..0233ffbcf9f 100644
--- a/source/blender/radiosity/intern/source/radrender.c
+++ b/source/blender/radiosity/intern/source/radrender.c
@@ -76,22 +76,23 @@ static float maxenergy;
/* find the face with maximum energy to become shooter */
/* nb: _rr means rad-render version of existing radio call */
-static VlakRen *findshoot_rr(Render *re)
+static void findshoot_rr(Render *re, VlakRen **shoot_p, RadFace **shootrf_p)
{
- RadFace *rf;
+ RadFace *rf, *shootrf, **radface;
ObjectRen *obr;
VlakRen *vlr=NULL, *shoot;
float energy;
int a;
shoot= NULL;
+ shootrf= NULL;
maxenergy= 0.0;
for(obr=re->objecttable.first; obr; obr=obr->next) {
for(a=0; a<obr->totvlak; a++) {
if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak; else vlr++;
- if(vlr->radface) {
- rf= vlr->radface;
+ if((radface=RE_vlakren_get_radface(obr, vlr, 0)) && *radface) {
+ rf= *radface;
rf->flag &= ~RAD_SHOOT;
energy= rf->unshot[0]*rf->area;
@@ -100,26 +101,32 @@ static VlakRen *findshoot_rr(Render *re)
if(energy>maxenergy) {
shoot= vlr;
+ shootrf= rf;
maxenergy= energy;
}
}
}
}
- if(shoot) {
+ if(shootrf) {
maxenergy/= RG.totenergy;
- if(maxenergy<RG.convergence) return NULL;
- shoot->radface->flag |= RAD_SHOOT;
+ if(maxenergy<RG.convergence) {
+ *shoot_p= NULL;
+ *shootrf_p= NULL;
+ return;
+ }
+ shootrf->flag |= RAD_SHOOT;
}
- return shoot;
+ *shoot_p= shoot;
+ *shootrf_p= shootrf;
}
-static void backface_test_rr(Render *re, VlakRen *shoot)
+static void backface_test_rr(Render *re, VlakRen *shoot, RadFace *shootrf)
{
ObjectRen *obr;
VlakRen *vlr=NULL;
- RadFace *rf;
+ RadFace *rf, **radface;
float tvec[3];
int a;
@@ -127,9 +134,9 @@ static void backface_test_rr(Render *re, VlakRen *shoot)
for(obr=re->objecttable.first; obr; obr=obr->next) {
for(a=0; a<obr->totvlak; a++) {
if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak; else vlr++;
- if(vlr->radface && vlr!=shoot) {
- rf= vlr->radface;
- VecSubf(tvec, shoot->radface->cent, rf->cent);
+ if(vlr != shoot && (radface=RE_vlakren_get_radface(obr, vlr, 0)) && *radface) {
+ rf= *radface;
+ VecSubf(tvec, shootrf->cent, rf->cent);
if(tvec[0]*rf->norm[0]+ tvec[1]*rf->norm[1]+ tvec[2]*rf->norm[2] < 0.0)
rf->flag |= RAD_BACKFACE;
@@ -142,7 +149,7 @@ static void clear_backface_test_rr(Render *re)
{
ObjectRen *obr;
VlakRen *vlr=NULL;
- RadFace *rf;
+ RadFace *rf, **radface;
int a;
/* backface flag clear */
@@ -150,8 +157,8 @@ static void clear_backface_test_rr(Render *re)
for(a=0; a<obr->totvlak; a++) {
if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak; else vlr++;
- if(vlr->radface) {
- rf= vlr->radface;
+ if((radface=RE_vlakren_get_radface(obr, vlr, 0)) && *radface) {
+ rf= *radface;
rf->flag &= ~RAD_BACKFACE;
}
}
@@ -161,11 +168,11 @@ static void clear_backface_test_rr(Render *re)
extern RadView hemitop, hemiside; // radfactors.c
/* hemi-zbuffering, delivers formfactors array */
-static void makeformfactors_rr(Render *re, VlakRen *shoot)
+static void makeformfactors_rr(Render *re, VlakRen *shoot, RadFace *shootrf)
{
ObjectRen *obr;
VlakRen *vlr=NULL;
- RadFace *rf;
+ RadFace *rf, **radface;
float len, vec[3], up[3], side[3], tar[5][3], *fp;
int a;
@@ -174,25 +181,25 @@ static void makeformfactors_rr(Render *re, VlakRen *shoot)
/* set up hemiview */
/* first: upvector for hemitop, we use diagonal hemicubes to prevent aliasing */
- VecSubf(vec, shoot->v1->co, shoot->radface->cent);
- Crossf(up, shoot->radface->norm, vec);
+ VecSubf(vec, shoot->v1->co, shootrf->cent);
+ Crossf(up, shootrf->norm, vec);
len= Normalize(up);
VECCOPY(hemitop.up, up);
- VECCOPY(hemiside.up, shoot->radface->norm);
+ VECCOPY(hemiside.up, shootrf->norm);
- Crossf(side, shoot->radface->norm, up);
+ Crossf(side, shootrf->norm, up);
/* five targets */
- VecAddf(tar[0], shoot->radface->cent, shoot->radface->norm);
- VecAddf(tar[1], shoot->radface->cent, up);
- VecSubf(tar[2], shoot->radface->cent, up);
- VecAddf(tar[3], shoot->radface->cent, side);
- VecSubf(tar[4], shoot->radface->cent, side);
+ VecAddf(tar[0], shootrf->cent, shootrf->norm);
+ VecAddf(tar[1], shootrf->cent, up);
+ VecSubf(tar[2], shootrf->cent, up);
+ VecAddf(tar[3], shootrf->cent, side);
+ VecSubf(tar[4], shootrf->cent, side);
/* camera */
- VECCOPY(hemiside.cam, shoot->radface->cent);
- VECCOPY(hemitop.cam, shoot->radface->cent);
+ VECCOPY(hemiside.cam, shootrf->cent);
+ VECCOPY(hemitop.cam, shootrf->cent);
/* do it! */
VECCOPY(hemitop.tar, tar[0]);
@@ -210,10 +217,10 @@ static void makeformfactors_rr(Render *re, VlakRen *shoot)
for(a=0; a<obr->totvlak; a++) {
if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak; else vlr++;
- if(vlr->radface) {
- rf= vlr->radface;
+ if((radface=RE_vlakren_get_radface(obr, vlr, 0)) && *radface) {
+ rf= *radface;
if(*fp!=0.0 && rf->area!=0.0) {
- *fp *= shoot->radface->area/rf->area;
+ *fp *= shootrf->area/rf->area;
if(*fp>1.0) *fp= 1.0001;
}
fp++;
@@ -223,17 +230,17 @@ static void makeformfactors_rr(Render *re, VlakRen *shoot)
}
/* based at RG.formfactors array, distribute shoot energy over other faces */
-static void applyformfactors_rr(Render *re, VlakRen *shoot)
+static void applyformfactors_rr(Render *re, VlakRen *shoot, RadFace *shootrf)
{
ObjectRen *obr;
VlakRen *vlr=NULL;
- RadFace *rf;
+ RadFace *rf, **radface;
float *fp, *ref, unr, ung, unb, r, g, b;
int a;
- unr= shoot->radface->unshot[0];
- ung= shoot->radface->unshot[1];
- unb= shoot->radface->unshot[2];
+ unr= shootrf->unshot[0];
+ ung= shootrf->unshot[1];
+ unb= shootrf->unshot[2];
fp= RG.formfactors;
@@ -241,8 +248,8 @@ static void applyformfactors_rr(Render *re, VlakRen *shoot)
for(a=0; a<obr->totvlak; a++) {
if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak; else vlr++;
- if(vlr->radface) {
- rf= vlr->radface;
+ if((radface=RE_vlakren_get_radface(obr, vlr, 0)) && *radface) {
+ rf= *radface;
if(*fp!= 0.0) {
ref= &(vlr->mat->r);
@@ -266,7 +273,7 @@ static void applyformfactors_rr(Render *re, VlakRen *shoot)
}
}
/* shoot energy has been shot */
- shoot->radface->unshot[0]= shoot->radface->unshot[1]= shoot->radface->unshot[2]= 0.0;
+ shootrf->unshot[0]= shootrf->unshot[1]= shootrf->unshot[2]= 0.0;
}
@@ -274,29 +281,30 @@ static void applyformfactors_rr(Render *re, VlakRen *shoot)
static void progressiverad_rr(Render *re)
{
VlakRen *shoot;
+ RadFace *shootrf;
float unshot[3];
int it= 0;
- shoot= findshoot_rr(re);
+ findshoot_rr(re, &shoot, &shootrf);
while( shoot ) {
/* backfaces receive no energy, but are zbuffered... */
- backface_test_rr(re, shoot);
+ backface_test_rr(re, shoot, shootrf);
/* ...unless it's two sided */
- if(shoot->radface->flag & RAD_TWOSIDED) {
- VECCOPY(unshot, shoot->radface->unshot);
- VecMulf(shoot->radface->norm, -1.0);
- makeformfactors_rr(re, shoot);
- applyformfactors_rr(re, shoot);
- VecMulf(shoot->radface->norm, -1.0);
- VECCOPY(shoot->radface->unshot, unshot);
+ if(shootrf->flag & RAD_TWOSIDED) {
+ VECCOPY(unshot, shootrf->unshot);
+ VecMulf(shootrf->norm, -1.0);
+ makeformfactors_rr(re, shoot, shootrf);
+ applyformfactors_rr(re, shoot, shootrf);
+ VecMulf(shootrf->norm, -1.0);
+ VECCOPY(shootrf->unshot, unshot);
}
/* hemi-zbuffers */
- makeformfactors_rr(re, shoot);
+ makeformfactors_rr(re, shoot, shootrf);
/* based at RG.formfactors array, distribute shoot energy over other faces */
- applyformfactors_rr(re, shoot);
+ applyformfactors_rr(re, shoot, shootrf);
it++;
re->timecursor(it);
@@ -306,7 +314,7 @@ static void progressiverad_rr(Render *re)
if(re->test_break()) break;
if(RG.maxiter && RG.maxiter<=it) break;
- shoot= findshoot_rr(re);
+ findshoot_rr(re, &shoot, &shootrf);
}
printf(" Unshot energy:%f\n", 1000.0*maxenergy);
@@ -319,7 +327,7 @@ static void initradfaces(Render *re)
{
ObjectRen *obr;
VlakRen *vlr= NULL;
- RadFace *rf;
+ RadFace *rf, **radface;
int a, b;
/* globals */
@@ -356,9 +364,18 @@ printf(" Rad elems: %d emittors %d\n", RG.totelem, RG.totpatch);
if(vlr->mat->mode & MA_RADIO) {
/* during render, vlr->n gets flipped/corrected, we cannot have that */
- if(vlr->v4) CalcNormFloat4(vlr->v1->co, vlr->v2->co, vlr->v3->co, vlr->v4->co, rf->norm);
- else CalcNormFloat(vlr->v1->co, vlr->v2->co, vlr->v3->co, rf->norm);
-
+ if (obr->ob->transflag & OB_NEG_SCALE){
+ /* The object has negative scale that will cause the normals to flip.
+ To counter this unwanted normal flip, swap vertex 2 and 4 for a quad
+ or vertex 2 and 3 (see flip_face) for a triangle in the call to CalcNormFloat4
+ in order to flip the normals back to the way they were in the original mesh. */
+ if(vlr->v4) CalcNormFloat4(vlr->v1->co, vlr->v4->co, vlr->v3->co, vlr->v2->co, rf->norm);
+ else CalcNormFloat(vlr->v1->co, vlr->v3->co, vlr->v2->co, rf->norm);
+ }else{
+ if(vlr->v4) CalcNormFloat4(vlr->v1->co, vlr->v2->co, vlr->v3->co, vlr->v4->co, rf->norm);
+ else CalcNormFloat(vlr->v1->co, vlr->v2->co, vlr->v3->co, rf->norm);
+ }
+
rf->totrad[0]= vlr->mat->emit*vlr->mat->r;
rf->totrad[1]= vlr->mat->emit*vlr->mat->g;
rf->totrad[2]= vlr->mat->emit*vlr->mat->b;
@@ -385,7 +402,8 @@ printf(" Rad elems: %d emittors %d\n", RG.totelem, RG.totpatch);
// uncommented; this isnt satisfying, but i leave it in the code for now (ton)
// if(vlr->mat->translucency!=0.0) rf->flag |= RAD_TWOSIDED;
- vlr->radface= rf++;
+ radface=RE_vlakren_get_radface(obr, vlr, 1);
+ *radface= rf++;
}
}
}
@@ -420,7 +438,7 @@ static void make_vertex_rad_values(Render *re)
ObjectRen *obr;
VertRen *v1=NULL;
VlakRen *vlr=NULL;
- RadFace *rf;
+ RadFace *rf, **radface;
float *col;
int a;
@@ -432,8 +450,8 @@ static void make_vertex_rad_values(Render *re)
for(a=0; a<obr->totvlak; a++) {
if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak; else vlr++;
- if(vlr->radface) {
- rf= vlr->radface;
+ if((radface=RE_vlakren_get_radface(obr, vlr, 0)) && *radface) {
+ rf= *radface;
/* apply correction */
rf->totrad[0]= RG.radfactor*pow( rf->totrad[0], RG.igamma);
diff --git a/source/blender/readblenfile/intern/BLO_readblenfile.c b/source/blender/readblenfile/intern/BLO_readblenfile.c
index 6e5bf149c7a..ec71611b31d 100644
--- a/source/blender/readblenfile/intern/BLO_readblenfile.c
+++ b/source/blender/readblenfile/intern/BLO_readblenfile.c
@@ -159,7 +159,7 @@ blo_read_runtime(
} else {
//printf("starting to read runtime from %s at datastart %d\n", path, datastart);
lseek(fd, datastart, SEEK_SET);
- bfd = blo_read_blendafterruntime(fd, actualsize-datastart, error_r);
+ bfd = blo_read_blendafterruntime(fd, path, actualsize-datastart, error_r);
fd= -1; // file was closed in blo_read_blendafterruntime()
}
diff --git a/source/blender/render/CMakeLists.txt b/source/blender/render/CMakeLists.txt
index b543dff49ff..0b659554d1a 100644
--- a/source/blender/render/CMakeLists.txt
+++ b/source/blender/render/CMakeLists.txt
@@ -29,7 +29,7 @@ FILE(GLOB SRC intern/source/*.c)
SET(INC
intern/include ../../../intern/guardedalloc ../blenlib ../makesdna
extern/include ../blenkernel ../radiosity/extern/include ../imbuf
- ../quicktime ../include ../../kernel/gen_messaging ../yafray
+ ../quicktime ../include ../../kernel/gen_messaging ../yafray ../blenloader
)
IF(WITH_OPENEXR)
diff --git a/source/blender/render/SConscript b/source/blender/render/SConscript
index d06331a5b48..7f799a78834 100644
--- a/source/blender/render/SConscript
+++ b/source/blender/render/SConscript
@@ -6,26 +6,26 @@ sources = env.Glob('intern/source/*.c')
incs = 'intern/include #/intern/guardedalloc ../blenlib ../makesdna'
incs += ' extern/include ../blenkernel ../radiosity/extern/include ../imbuf'
-incs += ' ../quicktime ../editors/include ../../kernel/gen_messaging'
+incs += ' ../include ../blenloader'
defs = []
-if env['WITH_BF_YAFRAY'] == 1:
- incs += ' ../yafray'
+if env['WITH_BF_YAFRAY']:
+ incs += ' ../yafray'
else:
- defs.append('DISABLE_YAFRAY')
+ defs.append('DISABLE_YAFRAY')
-if env['WITH_BF_QUICKTIME'] == 1:
- defs.append('WITH_QUICKTIME')
- incs += ' ' + env['BF_QUICKTIME_INC']
+if env['WITH_BF_QUICKTIME']:
+ defs.append('WITH_QUICKTIME')
+ incs += ' ../quicktime ' + env['BF_QUICKTIME_INC']
-if env['WITH_BF_FFMPEG'] == 1:
- defs.append('WITH_FFMPEG')
+if env['WITH_BF_FFMPEG']:
+ defs.append('WITH_FFMPEG')
if env['WITH_BF_OPENEXR']:
- defs.append('WITH_OPENEXR')
+ defs.append('WITH_OPENEXR')
if env['OURPLATFORM']=='linux2':
- cflags='-pthread'
+ cflags='-pthread'
env.BlenderLib ( libname = 'bf_render', sources = sources, includes = Split(incs), defines=defs, libtype='core', priority=55, compileflags=cflags )
diff --git a/source/blender/render/extern/include/RE_pipeline.h b/source/blender/render/extern/include/RE_pipeline.h
index d202ea1eed5..60557403143 100644
--- a/source/blender/render/extern/include/RE_pipeline.h
+++ b/source/blender/render/extern/include/RE_pipeline.h
@@ -38,6 +38,7 @@ struct Scene;
struct RenderData;
struct NodeBlurData;
struct Object;
+struct bNodeTree;
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* this include is what is exposed of render to outside world */
@@ -73,7 +74,7 @@ typedef struct RenderLayer {
/* copy of RenderData */
char name[RE_MAXNAME];
- unsigned int lay;
+ unsigned int lay, lay_zmask;
int layflag, passflag, pass_xor;
struct Material *mat_override;
@@ -88,10 +89,11 @@ typedef struct RenderLayer {
} RenderLayer;
typedef struct RenderResult {
+ struct RenderResult *next, *prev;
/* target image size */
int rectx, recty;
- short crop, pad;
+ short crop, sample_nr;
/* optional, 32 bits version of picture, used for ogl render and image curves */
int *rect32;
@@ -113,7 +115,6 @@ typedef struct RenderResult {
volatile RenderLayer *renlay;
/* optional saved endresult on disk */
- char exrfile[FILE_MAXDIR];
void *exrhandle;
/* for render results in Image, verify validity for sequences */
@@ -121,6 +122,7 @@ typedef struct RenderResult {
} RenderResult;
+
typedef struct RenderStats {
int totface, totvert, totstrand, tothalo, totlamp, totpart;
short curfield, curblur, curpart, partsdone, convertdone;
@@ -151,7 +153,7 @@ struct RenderLayer *RE_GetRenderLayer(struct RenderResult *rr, const char *name)
float *RE_RenderLayerGetPass(struct RenderLayer *rl, int passtype);
/* obligatory initialize call, disprect is optional */
-void RE_InitState (struct Render *re, struct RenderData *rd, int winx, int winy, rcti *disprect);
+void RE_InitState (struct Render *re, struct Render *source, struct RenderData *rd, int winx, int winy, rcti *disprect);
/* use this to change disprect of active render */
void RE_SetDispRect (struct Render *re, rcti *disprect);
@@ -175,17 +177,23 @@ void RE_DataBase_ApplyWindow(struct Render *re);
/* override the scene setting for amount threads, commandline */
void RE_set_max_threads(int threads);
+/* set the render threads based on the commandline and autothreads setting */
+void RE_init_threadcount(Render *re);
+
/* the main processor, assumes all was set OK! */
void RE_TileProcessor(struct Render *re, int firsttile, int threaded);
/* only RE_NewRender() needed, main Blender render calls */
void RE_BlenderFrame(struct Render *re, struct Scene *scene, int frame);
-void RE_BlenderAnim(struct Render *re, struct Scene *scene, int sfra, int efra);
+void RE_BlenderAnim(struct Render *re, struct Scene *scene, int sfra, int efra, int tfra);
void RE_ReadRenderResult(struct Scene *scene, struct Scene *scenode);
void RE_WriteRenderResult(RenderResult *rr, char *filename, int compress);
struct RenderResult *RE_MultilayerConvert(void *exrhandle, int rectx, int recty);
+/* do a full sample buffer compo */
+void RE_MergeFullSample(struct Render *re, struct Scene *sce, struct bNodeTree *ntree);
+
/* ancient stars function... go away! */
void RE_make_stars(struct Render *re, void (*initfunc)(void),
void (*vertexfunc)(float*), void (*termfunc)(void));
@@ -206,11 +214,14 @@ float RE_filter_value(int type, float x);
void RE_zbuf_accumulate_vecblur(struct NodeBlurData *nbd, int xsize, int ysize, float *newrect, float *imgrect, float *vecbufrect, float *zbufrect);
/* shaded view or baking options */
-#define RE_BAKE_LIGHT 0
-#define RE_BAKE_ALL 1
-#define RE_BAKE_AO 2
-#define RE_BAKE_NORMALS 3
-#define RE_BAKE_TEXTURE 4
+#define RE_BAKE_LIGHT 0
+#define RE_BAKE_ALL 1
+#define RE_BAKE_AO 2
+#define RE_BAKE_NORMALS 3
+#define RE_BAKE_TEXTURE 4
+#define RE_BAKE_DISPLACEMENT 5
+#define RE_BAKE_SHADOW 6
+
void RE_Database_Baking(struct Render *re, struct Scene *scene, int type, struct Object *actob);
void RE_DataBase_GetView(struct Render *re, float mat[][4]);
diff --git a/source/blender/render/extern/include/RE_raytrace.h b/source/blender/render/extern/include/RE_raytrace.h
index 39bf2be4256..8f429f7dd90 100644
--- a/source/blender/render/extern/include/RE_raytrace.h
+++ b/source/blender/render/extern/include/RE_raytrace.h
@@ -70,7 +70,7 @@ typedef struct Isect {
int ob_last;
short isect; /* which half of quad */
- short mode; /* RE_RAYSHADOW, RE_RAYMIRROR, RE_RAYSHADOW_TRA */
+ short mode; /* RE_RAY_SHADOW, RE_RAY_MIRROR, RE_RAY_SHADOW_TRA */
int lay; /* -1 default, set for layer lamps */
/* only used externally */
@@ -89,7 +89,7 @@ typedef struct Isect {
/* function callbacks for face type abstraction */
typedef void (*RayCoordsFunc)(RayFace *face,
float **v1, float **v2, float **v3, float **v4);
-typedef int (*RayCheckFunc)(Isect *is, RayFace *face);
+typedef int (*RayCheckFunc)(Isect *is, int ob, RayFace *face);
typedef float *(*RayObjectTransformFunc)(void *userdata, int ob);
/* tree building and freeing */
diff --git a/source/blender/render/extern/include/RE_shader_ext.h b/source/blender/render/extern/include/RE_shader_ext.h
index 5b81052f5d2..888474ffa18 100644
--- a/source/blender/render/extern/include/RE_shader_ext.h
+++ b/source/blender/render/extern/include/RE_shader_ext.h
@@ -47,7 +47,7 @@ typedef struct ShadeResult
{
float combined[4];
float col[4];
- float alpha;
+ float alpha, mist, z;
float diff[3]; /* no ramps, shadow, etc */
float spec[3];
float shad[3];
@@ -64,6 +64,7 @@ struct ShadeInputCopy {
struct Material *mat;
struct VlakRen *vlr;
+ struct StrandRen *strand;
struct ObjectInstanceRen *obi;
struct ObjectRen *obr;
int facenr;
@@ -96,6 +97,7 @@ typedef struct ShadeInput
struct Material *mat;
struct VlakRen *vlr;
+ struct StrandRen *strand;
struct ObjectInstanceRen *obi;
struct ObjectRen *obr;
int facenr;
@@ -132,7 +134,8 @@ typedef struct ShadeInput
/* texture coordinates */
float lo[3], gl[3], ref[3], orn[3], winco[3], sticky[3], vcol[4], rad[3];
float refcol[4], displace[3];
- float strand, tang[3], stress, winspeed[4];
+ float strandco, tang[3], nmaptang[3], stress, winspeed[4];
+ float duplilo[3], dupliuv[3];
ShadeInputUV uv[8]; /* 8 = MAX_MTFACE */
ShadeInputCol col[8]; /* 8 = MAX_MCOL */
@@ -154,6 +157,8 @@ typedef struct ShadeInput
int xs, ys; /* pixel to be rendered */
int mask; /* subsample mask */
+ float scanco[3]; /* original scanline coordinate without jitter */
+
int samplenr; /* sample counter, to detect if we should do shadow again */
int depth; /* 1 or larger on raytrace shading */
@@ -166,6 +171,7 @@ typedef struct ShadeInput
/* from initialize, part or renderlayer */
short do_preview; /* for nodes, in previewrender */
short thread, sample; /* sample: ShadeSample array index */
+
unsigned int lay;
int layflag, passflag, combinedflag;
struct Group *light_override;
diff --git a/source/blender/render/intern/include/occlusion.h b/source/blender/render/intern/include/occlusion.h
new file mode 100644
index 00000000000..646ad30b318
--- /dev/null
+++ b/source/blender/render/intern/include/occlusion.h
@@ -0,0 +1,49 @@
+/*
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2008 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Brecht Van Lommel.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef OCCLUSION_H
+#define OCCLUSION_H
+
+struct Render;
+struct ShadeInput;
+struct ShadeResult;
+struct RenderPart;
+struct ShadeSample;
+struct DerivedMesh;
+struct ObjectRen;
+
+void make_occ_tree(struct Render *re);
+void free_occ(struct Render *re);
+void sample_occ(struct Render *re, struct ShadeInput *shi);
+
+void cache_occ_samples(struct Render *re, struct RenderPart *pa, struct ShadeSample *ssamp);
+void free_occ_samples(struct Render *re, struct RenderPart *pa);
+
+#endif
+
diff --git a/source/blender/render/intern/include/pixelblending.h b/source/blender/render/intern/include/pixelblending.h
index 04c5a3977a3..f7f4bc76eae 100644
--- a/source/blender/render/intern/include/pixelblending.h
+++ b/source/blender/render/intern/include/pixelblending.h
@@ -35,6 +35,8 @@
*/
void add_filt_fmask(unsigned int mask, float *col, float *rowbuf, int row_w);
void add_filt_fmask_pixsize(unsigned int mask, float *in, float *rowbuf, int row_w, int pixsize);
+void add_filt_fmask_coord(float filt[][3], float *col, float *rowbuf, int row_w, int col_h, int x, int y);
+void mask_array(unsigned int mask, float filt[][3]);
/**
* Alpha-over blending for floats.
diff --git a/source/blender/render/intern/include/pixelshading.h b/source/blender/render/intern/include/pixelshading.h
index d2235784a59..c6b11b4af9a 100644
--- a/source/blender/render/intern/include/pixelshading.h
+++ b/source/blender/render/intern/include/pixelshading.h
@@ -45,7 +45,7 @@
* mask is pixel coverage in bits
* @return pointer to the object
*/
-void shadeHaloFloat(HaloRen *har,
+int shadeHaloFloat(HaloRen *har,
float *col, int zz,
float dist, float xn,
float yn, short flarec);
@@ -55,7 +55,8 @@ void shadeHaloFloat(HaloRen *har,
*/
void shadeSkyPixel(float *collector, float fx, float fy);
void shadeSkyView(float *colf, float *rco, float *view, float *dxyview);
-
+void shadeAtmPixel(struct SunSky *sunsky, float *collector, float fx, float fy, float distance);
+void shadeSunView(float *colf, float *view);
/* ------------------------------------------------------------------------- */
#endif
diff --git a/source/blender/render/intern/include/render_types.h b/source/blender/render/intern/include/render_types.h
index 7fbbd0f5abc..1768b052b54 100644
--- a/source/blender/render/intern/include/render_types.h
+++ b/source/blender/render/intern/include/render_types.h
@@ -42,6 +42,9 @@
#include "RE_pipeline.h"
#include "RE_shader_ext.h" /* TexResult, ShadeResult, ShadeInput */
+#include "sunsky.h"
+
+#include "BLO_sys_types.h" // for intptr_t support
struct Object;
struct MemArena;
@@ -64,8 +67,10 @@ typedef struct SampleTables
typedef struct QMCSampler
{
+ struct QMCSampler *next, *prev;
int type;
int tot;
+ int used;
double *samp2d;
double offs[BLENDER_MAX_THREADS][2];
} QMCSampler;
@@ -79,17 +84,18 @@ typedef struct RenderPart
{
struct RenderPart *next, *prev;
- /* result of part rendering */
- RenderResult *result;
+ RenderResult *result; /* result of part rendering */
+ ListBase fullresult; /* optional full sample buffers */
int *recto; /* object table for objects */
int *rectp; /* polygon index table */
int *rectz; /* zbuffer */
- long *rectdaps; /* delta acum buffer for pixel structs */
+ int *rectmask; /* negative zmask */
+ intptr_t *rectdaps; /* delta acum buffer for pixel structs */
int *rectbacko; /* object table for backside sss */
int *rectbackp; /* polygon index table for backside sss */
int *rectbackz; /* zbuffer for backside sss */
- long *rectall; /* buffer for all faces for sss */
+ intptr_t *rectall; /* buffer for all faces for sss */
rcti disprect; /* part coordinates within total picture */
int rectx, recty; /* the size */
@@ -113,6 +119,8 @@ struct Render
RenderResult *result;
/* if render with single-layer option, other rendered layers are stored here */
RenderResult *pushedresult;
+ /* a list of RenderResults, for fullsample */
+ ListBase fullresult;
/* window size, display rect, viewplane */
int winx, winy;
@@ -147,7 +155,10 @@ struct Render
/* samples */
SampleTables *samples;
float jit[32][2];
- QMCSampler *qsa;
+ ListBase *qmcsamplers;
+
+ /* shadow counter, detect shadow-reuse for shaders */
+ int shadowsamplenr[BLENDER_MAX_THREADS];
/* scene, and its full copy of renderdata and world */
Scene *scene;
@@ -158,6 +169,10 @@ struct Render
/* octree tables and variables for raytrace */
void *raytree;
+
+ /* occlusion tree */
+ void *occlusiontree;
+ ListBase strandsurface;
/* use this instead of R.r.cfra */
float cfra;
@@ -170,11 +185,9 @@ struct Render
ListBase lampren; /* storage, for free */
ListBase objecttable;
- struct RenderBuckets *strandbuckets;
struct ObjectInstanceRen *objectinstance;
ListBase instancetable;
- struct GHash *objecthash;
int totinstance;
struct Image *backbuf, *bakebuf;
@@ -215,7 +228,7 @@ struct ISBData;
typedef struct ShadSampleBuf {
struct ShadSampleBuf *next, *prev;
- long *zbuf;
+ intptr_t *zbuf;
char *cbuf;
} ShadSampleBuf;
@@ -241,7 +254,9 @@ typedef struct ObjectRen {
struct ObjectRen *next, *prev;
struct Object *ob, *par;
struct Scene *sce;
- int index, psysindex;
+ int index, psysindex, flag, lay;
+
+ float boundbox[2][3];
int totvert, totvlak, totstrand, tothalo;
int vertnodeslen, vlaknodeslen, strandnodeslen, blohalen;
@@ -249,11 +264,13 @@ typedef struct ObjectRen {
struct VlakTableNode *vlaknodes;
struct StrandTableNode *strandnodes;
struct HaloRen **bloha;
- ListBase strandbufs;
+ struct StrandBuffer *strandbuf;
char (*mtface)[32];
char (*mcol)[32];
- int actmtface, actmcol;
+ int actmtface, actmcol, bakemtface;
+
+ float obmat[4][4]; /* only used in convertblender.c, for instancing */
} ObjectRen;
typedef struct ObjectInstanceRen {
@@ -261,11 +278,14 @@ typedef struct ObjectInstanceRen {
ObjectRen *obr;
Object *ob, *par;
- int index, psysindex;
+ int index, psysindex, lay;
- float mat[4][4], imat[3][3];
+ float mat[4][4], nmat[3][3]; /* nmat is inverse mat tranposed */
short flag;
+ float dupliorco[3], dupliuv[2];
+ float (*duplitexmat)[4];
+
float *vectors;
int totvector;
} ObjectInstanceRen;
@@ -302,13 +322,10 @@ typedef struct RadFace {
typedef struct VlakRen {
struct VertRen *v1, *v2, *v3, *v4; /* keep in order for ** addressing */
- unsigned int lay;
float n[3];
struct Material *mat;
char puno;
char flag, ec;
- RadFace *radface;
- ObjectRen *obr;
int index;
} VlakRen;
@@ -328,22 +345,43 @@ typedef struct HaloRen
struct Material *mat;
} HaloRen;
+/* ------------------------------------------------------------------------- */
+
typedef struct StrandVert {
float co[3];
float strandco;
} StrandVert;
+typedef struct StrandSurface {
+ struct StrandSurface *next, *prev;
+ ObjectRen obr;
+ int (*face)[4];
+ float (*co)[3];
+ /* for occlusion caching */
+ float (*col)[3];
+ /* for speedvectors */
+ float (*prevco)[3], (*nextco)[3];
+ int totvert, totface;
+} StrandSurface;
+
+typedef struct StrandBound {
+ int start, end;
+ float boundbox[2][3];
+} StrandBound;
+
typedef struct StrandBuffer {
struct StrandBuffer *next, *prev;
struct StrandVert *vert;
- int totvert;
+ struct StrandBound *bound;
+ int totvert, totbound;
struct ObjectRen *obr;
struct Material *ma;
+ struct StrandSurface *surface;
unsigned int lay;
int overrideuv;
int flag, maxdepth;
- float adaptcos, minwidth;
+ float adaptcos, minwidth, widthfade;
float winmat[4][4];
int winx, winy;
@@ -380,8 +418,10 @@ typedef struct LampRen {
float xs, ys, dist;
float co[3];
- short type, mode;
+ short type;
+ int mode;
float r, g, b, k;
+ float shdwr, shdwg, shdwb;
float energy, haint;
int lay;
float spotsi,spotbl;
@@ -420,9 +460,11 @@ typedef struct LampRen {
float area_size, area_sizey, area_sizez;
float adapt_thresh;
+ /* sun/sky */
+ struct SunSky *sunsky;
+
struct ShadBuf *shb;
float *jitter;
- QMCSampler *qsa;
float imat[3][3];
float spottexfac;
@@ -463,6 +505,9 @@ typedef struct LampRen {
#define R_LAMPHALO 8
#define R_GLOB_NOPUNOFLIP 16
#define R_NEED_TANGENT 32
+#define R_SKIP_MULTIRES 64
+#define R_BAKE_TRACE 128
+#define R_BAKING 256
/* vlakren->flag (vlak = face in dutch) char!!! */
#define R_SMOOTH 1
@@ -481,10 +526,14 @@ typedef struct LampRen {
#define R_STRAND_BSPLINE 1
#define R_STRAND_B_UNITS 2
+/* objectren->flag */
+#define R_INSTANCEABLE 1
+
/* objectinstance->flag */
#define R_DUPLI_TRANSFORMED 1
#define R_ENV_TRANSFORMED 2
#define R_TRANSFORMED (1|2)
+#define R_NEED_VECTORS 4
#endif /* RENDER_TYPES_H */
diff --git a/source/blender/render/intern/include/rendercore.h b/source/blender/render/intern/include/rendercore.h
index ab009a980a5..4b28529a147 100644
--- a/source/blender/render/intern/include/rendercore.h
+++ b/source/blender/render/intern/include/rendercore.h
@@ -37,8 +37,8 @@
/* vector defines */
-#define CROSS(dest, a, b) dest[0]= a[1] * b[2] - a[2] * b[1]; dest[1]= a[2] * b[0] - a[0] * b[2]; dest[2]= a[0] * b[1] - a[1] * b[0]
-#define VECMUL(dest, f) dest[0]*= f; dest[1]*= f; dest[2]*= f
+#define CROSS(dest, a, b) { dest[0]= a[1] * b[2] - a[2] * b[1]; dest[1]= a[2] * b[0] - a[0] * b[2]; dest[2]= a[0] * b[1] - a[1] * b[0]; }
+#define VECMUL(dest, f) { dest[0]*= f; dest[1]*= f; dest[2]*= f; }
struct HaloRen;
struct ShadeInput;
@@ -47,13 +47,14 @@ struct World;
struct RenderPart;
struct RenderLayer;
struct ObjectRen;
+struct ListBase;
/* ------------------------------------------------------------------------- */
typedef struct PixStr
{
struct PixStr *next;
- int obi, facenr, z;
+ int obi, facenr, z, maskz;
unsigned short mask;
short shadfac;
} PixStr;
@@ -87,6 +88,9 @@ void zbufshadeDA_tile(struct RenderPart *pa);
void zbufshade_sss_tile(struct RenderPart *pa);
+int get_sample_layers(struct RenderPart *pa, struct RenderLayer *rl, struct RenderLayer **rlpp);
+
+
/* -------- ray.c ------- */
extern void freeraytree(Render *re);
@@ -97,9 +101,7 @@ extern void ray_trace(ShadeInput *, ShadeResult *);
extern void ray_ao(ShadeInput *, float *);
extern void init_jitter_plane(LampRen *lar);
extern void init_ao_sphere(struct World *wrld);
-extern void init_lamp_hammersley(LampRen *lar);
-extern void free_lamp_qmcsampler(LampRen *lar);
-extern void init_render_hammersley(Render *re);
+extern void init_render_qmcsampler(Render *re);
extern void free_render_qmcsampler(Render *re);
#endif /* RENDER_EXT_H */
diff --git a/source/blender/render/intern/include/renderdatabase.h b/source/blender/render/intern/include/renderdatabase.h
index c919a54008e..dc28eae1cc2 100644
--- a/source/blender/render/intern/include/renderdatabase.h
+++ b/source/blender/render/intern/include/renderdatabase.h
@@ -42,6 +42,7 @@ struct CustomData;
struct StrandBuffer;
struct StrandRen;
struct ObjectInstanceRen;
+struct RadFace;
#define RE_QUAD_MASK 0x7FFFFFF
#define RE_QUAD_OFFS 0x8000000
@@ -63,6 +64,8 @@ typedef struct VlakTableNode {
struct MCol *mcol;
int totmtface, totmcol;
float *surfnor;
+ float *tangent;
+ struct RadFace **radface;
} VlakTableNode;
typedef struct StrandTableNode {
@@ -70,6 +73,7 @@ typedef struct StrandTableNode {
float *winspeed;
float *surfnor;
float *simplify;
+ int *face;
struct MCol *mcol;
float *uv;
int totuv, totmcol;
@@ -82,6 +86,7 @@ void free_renderdata_vlaknodes(struct VlakTableNode *vlaknodes);
void set_normalflags(struct Render *re, struct ObjectRen *obr);
void project_renderdata(struct Render *re, void (*projectfunc)(float *, float mat[][4], float *), int do_pano, float xoffs, int do_buckets);
+int clip_render_object(float boundbox[][3], float *bounds, float mat[][4]);
/* functions are not exported... so wrong names */
@@ -93,8 +98,8 @@ struct HaloRen *RE_inithalo(struct Render *re, struct ObjectRen *obr, struct Mat
struct HaloRen *RE_inithalo_particle(struct Render *re, struct ObjectRen *obr, struct DerivedMesh *dm, struct Material *ma, float *vec, float *vec1, float *orco, float *uvco, float hasize, float vectsize, int seed);
struct StrandBuffer *RE_addStrandBuffer(struct ObjectRen *obr, int totvert);
-struct ObjectRen *RE_addRenderObject(struct Render *re, struct Object *ob, struct Object *par, int index, int psysindex);
-void RE_addRenderInstance(struct Render *re, struct ObjectRen *obr, struct Object *ob, struct Object *par, int index, int psysindex, float mat[][4]);
+struct ObjectRen *RE_addRenderObject(struct Render *re, struct Object *ob, struct Object *par, int index, int psysindex, int lay);
+struct ObjectInstanceRen *RE_addRenderInstance(struct Render *re, struct ObjectRen *obr, struct Object *ob, struct Object *par, int index, int psysindex, float mat[][4], int lay);
void RE_makeRenderInstances(struct Render *re);
void RE_instanceTransformNormal(struct ObjectInstanceRen *obi, float *nor, float *tnor);
@@ -108,12 +113,15 @@ float *RE_vertren_get_winspeed(struct ObjectInstanceRen *obi, struct VertRen *ve
struct MTFace *RE_vlakren_get_tface(struct ObjectRen *obr, VlakRen *ren, int n, char **name, int verify);
struct MCol *RE_vlakren_get_mcol(struct ObjectRen *obr, VlakRen *ren, int n, char **name, int verify);
float *RE_vlakren_get_surfnor(struct ObjectRen *obr, VlakRen *ren, int verify);
+float *RE_vlakren_get_nmap_tangent(struct ObjectRen *obr, VlakRen *ren, int verify);
+RadFace **RE_vlakren_get_radface(struct ObjectRen *obr, VlakRen *ren, int verify);
int RE_vlakren_get_normal(struct Render *re, struct ObjectInstanceRen *obi, struct VlakRen *vlr, float *nor);
float *RE_strandren_get_surfnor(struct ObjectRen *obr, struct StrandRen *strand, int verify);
float *RE_strandren_get_uv(struct ObjectRen *obr, struct StrandRen *strand, int n, char **name, int verify);
struct MCol *RE_strandren_get_mcol(struct ObjectRen *obr, struct StrandRen *strand, int n, char **name, int verify);
float *RE_strandren_get_simplify(struct ObjectRen *obr, struct StrandRen *strand, int verify);
+int *RE_strandren_get_face(struct ObjectRen *obr, struct StrandRen *strand, int verify);
float *RE_strandren_get_winspeed(struct ObjectInstanceRen *obi, struct StrandRen *strand, int verify);
struct VertRen *RE_vertren_copy(struct ObjectRen *obr, struct VertRen *ver);
diff --git a/source/blender/render/intern/include/shadbuf.h b/source/blender/render/intern/include/shadbuf.h
index a96baab8294..7015b4bc1bf 100644
--- a/source/blender/render/intern/include/shadbuf.h
+++ b/source/blender/render/intern/include/shadbuf.h
@@ -54,7 +54,7 @@ void threaded_makeshadowbufs(struct Render *re);
* @param inp The inproduct between viewvector and ?
*
*/
-float testshadowbuf(struct ShadBuf *shb, float *rco, float *dxco, float *dyco, float inp);
+float testshadowbuf(struct Render *re, struct ShadBuf *shb, float *rco, float *dxco, float *dyco, float inp, float mat_bias);
/**
* Determines the shadow factor for lamp <lar>, between <p1>
diff --git a/source/blender/render/intern/include/shading.h b/source/blender/render/intern/include/shading.h
index 6ca63a2976d..54311d2515a 100644
--- a/source/blender/render/intern/include/shading.h
+++ b/source/blender/render/intern/include/shading.h
@@ -40,13 +40,13 @@ struct ObjectInstanceRen obi;
/* needed to calculate shadow and AO for an entire pixel */
typedef struct ShadeSample {
- int tot; /* amount of shi in use, can be 1 for not FULL_OSA */
+ int tot; /* amount of shi in use, can be 1 for not FULL_OSA */
+
+ RenderLayer *rlpp[RE_MAX_OSA]; /* fast lookup from sample to renderlayer (fullsample buf) */
/* could be malloced once */
ShadeInput shi[RE_MAX_OSA];
ShadeResult shr[RE_MAX_OSA];
-
- int samplenr; /* counter, detect shadow-reuse for shaders */
} ShadeSample;
@@ -56,7 +56,8 @@ void shade_material_loop(struct ShadeInput *shi, struct ShadeResult *shr);
void shade_input_set_triangle_i(struct ShadeInput *shi, struct ObjectInstanceRen *obi, struct VlakRen *vlr, short i1, short i2, short i3);
void shade_input_set_triangle(struct ShadeInput *shi, volatile int obi, volatile int facenr, int normal_flip);
void shade_input_copy_triangle(struct ShadeInput *shi, struct ShadeInput *from);
-void shade_input_set_viewco(struct ShadeInput *shi, float x, float y, float z);
+void shade_input_calc_viewco(struct ShadeInput *shi, float x, float y, float z, float *view, float *dxyview, float *co, float *dxco, float *dyco);
+void shade_input_set_viewco(struct ShadeInput *shi, float x, float y, float sx, float sy, float z);
void shade_input_set_uv(struct ShadeInput *shi);
void shade_input_set_normals(struct ShadeInput *shi);
void shade_input_flip_normals(struct ShadeInput *shi);
@@ -69,6 +70,7 @@ void shade_input_initialize(struct ShadeInput *shi, struct RenderPart *pa, struc
void shade_sample_initialize(struct ShadeSample *ssamp, struct RenderPart *pa, struct RenderLayer *rl);
void shade_samples_do_AO(struct ShadeSample *ssamp);
+void shade_samples_fill_with_ps(struct ShadeSample *ssamp, struct PixStr *ps, int x, int y);
int shade_samples(struct ShadeSample *ssamp, struct PixStr *ps, int x, int y);
void vlr_set_uv_indices(struct VlakRen *vlr, int *i1, int *i2, int *i3);
diff --git a/source/blender/render/intern/include/sss.h b/source/blender/render/intern/include/sss.h
index 660fb544227..9ffdcaf206a 100644
--- a/source/blender/render/intern/include/sss.h
+++ b/source/blender/render/intern/include/sss.h
@@ -59,7 +59,7 @@ void sss_add_points(Render *re, float (*co)[3], float (*color)[3], float *area,
void free_sss(struct Render *re);
int sample_sss(struct Render *re, struct Material *mat, float *co, float *col);
-int has_sss_tree(struct Render *re, struct Material *mat);
+int sss_pass_done(struct Render *re, struct Material *mat);
#endif /*SSS_H*/
diff --git a/source/blender/render/intern/include/strand.h b/source/blender/render/intern/include/strand.h
index c6ec72125ad..09988125830 100644
--- a/source/blender/render/intern/include/strand.h
+++ b/source/blender/render/intern/include/strand.h
@@ -41,6 +41,9 @@ struct RenderBuckets;
struct RenderPrimitiveIterator;
struct ZSpan;
struct ObjectInstanceRen;
+struct StrandSurface;
+struct DerivedMesh;
+struct ObjectRen;
typedef struct StrandPoint {
/* position within segment */
@@ -61,6 +64,7 @@ typedef struct StrandPoint {
float co1[3], co2[3];
float hoco1[4], hoco2[4];
float zco1[3], zco2[3];
+ int clip1, clip2;
/* screen space */
float hoco[4];
@@ -81,9 +85,20 @@ typedef struct StrandSegment {
int shaded;
} StrandSegment;
+struct StrandShadeCache;
+typedef struct StrandShadeCache StrandShadeCache;
+
void strand_eval_point(StrandSegment *sseg, StrandPoint *spoint);
-void render_strand_segment(struct Render *re, float winmat[][4], struct StrandPart *spart, struct ZSpan *zspan, StrandSegment *sseg);
-void project_strands(Render *re, void (*projectfunc)(float *, float mat[][4], float *), int do_pano, int do_buckets);
+void render_strand_segment(struct Render *re, float winmat[][4], struct StrandPart *spart, struct ZSpan *zspan, int totzspan, StrandSegment *sseg);
+void strand_minmax(struct StrandRen *strand, float *min, float *max);
+
+struct StrandSurface *cache_strand_surface(struct Render *re, struct ObjectRen *obr, struct DerivedMesh *dm, float mat[][4], int timeoffset);
+void free_strand_surface(struct Render *re);
+
+struct StrandShadeCache *strand_shade_cache_create(void);
+void strand_shade_cache_free(struct StrandShadeCache *cache);
+void strand_shade_segment(struct Render *re, struct StrandShadeCache *cache, struct StrandSegment *sseg, struct ShadeSample *ssamp, float t, float s, int addpassflag);
+void strand_shade_unref(struct StrandShadeCache *cache, struct StrandVert *svert);
struct RenderBuckets *init_buckets(struct Render *re);
void add_buckets_primitive(struct RenderBuckets *buckets, float *min, float *max, void *prim);
diff --git a/source/blender/render/intern/include/sunsky.h b/source/blender/render/intern/include/sunsky.h
new file mode 100644
index 00000000000..f61338bcf27
--- /dev/null
+++ b/source/blender/render/intern/include/sunsky.h
@@ -0,0 +1,144 @@
+ /**
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * Contributor(s): zaghaghi
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+/**
+ * This feature comes from Preetham paper on "A Practical Analytic Model for Daylight"
+ * and example code from Brian Smits, another author of that paper in
+ * http://www.cs.utah.edu/vissim/papers/sunsky/code/
+ * */
+#ifndef SUNSKY_H_
+#define SUNSKY_H_
+
+#define SPECTRUM_MAX_COMPONENTS 100
+#define SPECTRUM_START 350.0
+#define SPECTRUM_END 800.0
+
+typedef struct SunSky
+{
+ short effect_type, skyblendtype, sky_colorspace;
+ float turbidity;
+ float theta, phi;
+
+ float toSun[3];
+
+ /*float sunSpectralRaddata[SPECTRUM_MAX_COMPONENTS];*/
+ float sunSolidAngle;
+
+ float zenith_Y, zenith_x, zenith_y;
+
+ float perez_Y[5], perez_x[5], perez_y[5];
+
+ /* suggested by glome in
+ * http://projects.blender.org/tracker/?func=detail&atid=127&aid=8063&group_id=9*/
+ float horizon_brightness;
+ float spread;
+ float sun_brightness;
+ float sun_size;
+ float backscattered_light;
+ float skyblendfac;
+ float sky_exposure;
+
+ float atm_HGg;
+
+ float atm_SunIntensity;
+ float atm_InscatteringMultiplier;
+ float atm_ExtinctionMultiplier;
+ float atm_BetaRayMultiplier;
+ float atm_BetaMieMultiplier;
+ float atm_DistanceMultiplier;
+
+ float atm_BetaRay[3];
+ float atm_BetaDashRay[3];
+ float atm_BetaMie[3];
+ float atm_BetaDashMie[3];
+ float atm_BetaRM[3];
+}SunSky;
+
+/**
+ * InitSunSky:
+ * this function compute some sun,sky parameters according to input parameters and also initiate some other sun, sky parameters
+ * parameters:
+ * sunSky, is a structure that contains informtion about sun, sky and atmosphere, in this function, most of its values initiated
+ * turb, is atmosphere turbidity
+ * toSun, contains sun direction
+ * horizon_brighness, controls the brightness of the horizon colors
+ * spread, controls colors spreed at horizon
+ * sun_brightness, controls sun's brightness
+ * sun_size, controls sun's size
+ * back_scatter, controls back scatter light
+ * */
+void InitSunSky(struct SunSky *sunsky, float turb, float *toSun, float horizon_brightness,
+ float spread,float sun_brightness, float sun_size, float back_scatter,
+ float skyblendfac, short skyblendtype, float sky_exposure, float sky_colorspace);
+
+/**
+ * GetSkyXYZRadiance:
+ * this function compute sky radiance according to a view parameters `theta' and `phi'and sunSky values
+ * parameters:
+ * sunSky, sontains sun and sky parameters
+ * theta, is sun's theta
+ * phi, is sun's phi
+ * color_out, is computed color that shows sky radiance in XYZ color format
+ * */
+void GetSkyXYZRadiance(struct SunSky* sunsky, float theta, float phi, float color_out[3]);
+
+/**
+ * GetSkyXYZRadiancef:
+ * this function compute sky radiance according to a view direction `varg' and sunSky values
+ * parameters:
+ * sunSky, sontains sun and sky parameters
+ * varg, shows direction
+ * color_out, is computed color that shows sky radiance in XYZ color format
+ * */
+void GetSkyXYZRadiancef(struct SunSky* sunsky, const float varg[3], float color_out[3]);
+
+/**
+ * InitAtmosphere:
+ * this function intiate sunSky structure with user input parameters.
+ * parameters:
+ * sunSky, contains information about sun, and in this function some atmosphere parameters will initiated
+ * sun_intens, shows sun intensity value
+ * mief, Mie scattering factor this factor currently call with 1.0
+ * rayf, Rayleigh scattering factor, this factor currently call with 1.0
+ * inscattf, inscatter light factor that range from 0.0 to 1.0, 0.0 means no inscatter light and 1.0 means full inscatter light
+ * extincf, extinction light factor that range from 0.0 to 1.0, 0.0 means no extinction and 1.0 means full extinction
+ * disf, is distance factor, multiplyed to pixle's z value to compute each pixle's distance to camera,
+ * */
+void InitAtmosphere(struct SunSky *sunSky, float sun_intens, float mief, float rayf, float inscattf, float extincf, float disf);
+
+/**
+ * AtmospherePixleShader:
+ * this function apply atmosphere effect on a pixle color `rgb' at distance `s'
+ * parameters:
+ * sunSky, contains information about sun parameters and user values
+ * view, is camera view vector
+ * s, is distance
+ * rgb, contains rendered color value for a pixle
+ * */
+void AtmospherePixleShader( struct SunSky* sunSky, float view[3], float s, float rgb[3]);
+
+/**
+ * ClipColor:
+ * clip a color to range [0,1];
+ * */
+void ClipColor(float c[3]);
+
+#endif /*SUNSKY_H_*/
diff --git a/source/blender/render/intern/include/texture.h b/source/blender/render/intern/include/texture.h
index 8e56c4a852f..be5471e07c4 100644
--- a/source/blender/render/intern/include/texture.h
+++ b/source/blender/render/intern/include/texture.h
@@ -55,7 +55,7 @@ struct ImBuf;
void do_halo_tex(struct HaloRen *har, float xn, float yn, float *colf);
void do_sky_tex(float *rco, float *lo, float *dxyview, float *hor, float *zen, float *blend, int skyflag);
void do_material_tex(struct ShadeInput *shi);
-void do_lamp_tex(LampRen *la, float *lavec, struct ShadeInput *shi, float *colf);
+void do_lamp_tex(LampRen *la, float *lavec, struct ShadeInput *shi, float *colf, int effect);
void init_render_textures(Render *re);
diff --git a/source/blender/render/intern/include/zbuf.h b/source/blender/render/intern/include/zbuf.h
index 4d30c1e0dfb..b6d0c656f63 100644
--- a/source/blender/render/intern/include/zbuf.h
+++ b/source/blender/render/intern/include/zbuf.h
@@ -36,6 +36,8 @@ struct LampRen;
struct VlakRen;
struct ListBase;
struct ZSpan;
+struct APixstrand;
+struct StrandShadeCache;
void fillrect(int *rect, int x, int y, int val);
@@ -48,12 +50,11 @@ void projectverto(float *v1, float winmat[][4], float *adr);
int testclip(float *v);
void zbuffer_shadow(struct Render *re, float winmat[][4], struct LampRen *lar, int *rectz, int size, float jitx, float jity);
-void zbuffer_solid(struct RenderPart *pa, unsigned int layer, short layflag, void (*fillfunc)(struct RenderPart*, struct ZSpan*, int, void*), void *data);
+void zbuffer_solid(struct RenderPart *pa, struct RenderLayer *rl, void (*fillfunc)(struct RenderPart*, struct ZSpan*, int, void*), void *data);
-unsigned short *zbuffer_transp_shade(struct RenderPart *pa, struct RenderLayer *rl, float *pass);
-unsigned short *zbuffer_strands_shade(struct Render *re, struct RenderPart *pa, struct RenderLayer *rl, float *pass);
-void convert_zbuf_to_distbuf(struct RenderPart *pa, struct RenderLayer *rl);
+unsigned short *zbuffer_transp_shade(struct RenderPart *pa, struct RenderLayer *rl, float *pass, struct ListBase *psmlist);
void zbuffer_sss(RenderPart *pa, unsigned int lay, void *handle, void (*func)(void*, int, int, int, int, int));
+int zbuffer_strands_abuf(struct Render *re, struct RenderPart *pa, struct RenderLayer *rl, struct APixstrand *apixbuf, struct ListBase *apsmbase, struct StrandShadeCache *cache);
typedef struct APixstr {
unsigned short mask[4]; /* jitter mask */
@@ -64,10 +65,20 @@ typedef struct APixstr {
struct APixstr *next;
} APixstr;
+typedef struct APixstrand {
+ unsigned short mask[4]; /* jitter mask */
+ int z[4]; /* distance */
+ int p[4]; /* index */
+ int obi[4]; /* object instance */
+ int seg[4]; /* for strands, segment number */
+ float u[4], v[4]; /* for strands, u,v coordinate in segment */
+ struct APixstrand *next;
+} APixstrand;
+
typedef struct APixstrMain
{
struct APixstrMain *next, *prev;
- struct APixstr *ps;
+ void *ps;
} APixstrMain;
/* span fill in method, is also used to localize data for zbuffering */
@@ -84,12 +95,15 @@ typedef struct ZSpan {
int *rectz1; /* seconday z buffer for shadowbuffer (2nd closest z) */
int *rectp; /* polygon index buffer */
int *recto; /* object buffer */
+ int *rectmask; /* negative zmask buffer */
APixstr *apixbuf, *curpstr; /* apixbuf for transparent */
+ APixstrand *curpstrand; /* same for strands */
struct ListBase *apsmbase;
int polygon_offset; /* offset in Z */
float shad_alpha; /* copy from material, used by irregular shadbuf */
int mask, apsmcounter; /* in use by apixbuf */
+ int apstrandmcounter;
float clipcrop; /* for shadow, was in R global before */
diff --git a/source/blender/render/intern/source/convertblender.c b/source/blender/render/intern/source/convertblender.c
index d8ad518da14..a9bc2131d77 100644
--- a/source/blender/render/intern/source/convertblender.c
+++ b/source/blender/render/intern/source/convertblender.c
@@ -54,6 +54,7 @@
#include "DNA_meshdata_types.h"
#include "DNA_meta_types.h"
#include "DNA_modifier_types.h"
+#include "DNA_node_types.h"
#include "DNA_object_types.h"
#include "DNA_object_force.h"
#include "DNA_object_fluidsim.h"
@@ -99,6 +100,7 @@
#include "envmap.h"
//XXX #include "multires.h"
+#include "occlusion.h"
#include "render_types.h"
#include "rendercore.h"
#include "renderdatabase.h"
@@ -106,9 +108,12 @@
#include "radio.h"
#include "shadbuf.h"
#include "shading.h"
+#include "strand.h"
#include "texture.h"
#include "sss.h"
+#include "strand.h"
#include "zbuf.h"
+#include "sunsky.h"
#ifndef DISABLE_YAFRAY /* disable yafray */
@@ -198,6 +203,7 @@ void RE_make_stars(Render *re, void (*initfunc)(void),
else stargrid *= 1.0; /* then it draws fewer */
if(re) MTC_Mat4Invert(mat, re->viewmat);
+ else MTC_Mat4One(mat);
/* BOUNDING BOX CALCULATION
* bbox goes from z = loc_near_var | loc_far_var,
@@ -228,7 +234,7 @@ void RE_make_stars(Render *re, void (*initfunc)(void),
}
if(re) /* add render object for stars */
- obr= RE_addRenderObject(re, NULL, NULL, 0, 0);
+ obr= RE_addRenderObject(re, NULL, NULL, 0, 0, 0);
for (x = sx, fx = sx * stargrid; x <= ex; x++, fx += stargrid) {
for (y = sy, fy = sy * stargrid; y <= ey ; y++, fy += stargrid) {
@@ -447,34 +453,8 @@ static void calc_edge_stress(Render *re, ObjectRen *obr, Mesh *me)
MEM_freeN(accum);
}
-void tangent_from_uv(float *uv1, float *uv2, float *uv3, float *co1, float *co2, float *co3, float *n, float *tang)
-{
- float tangv[3], ct[3], e1[3], e2[3], s1, t1, s2, t2, det;
-
- s1= uv2[0] - uv1[0];
- s2= uv3[0] - uv1[0];
- t1= uv2[1] - uv1[1];
- t2= uv3[1] - uv1[1];
- det= 1.0f / (s1 * t2 - s2 * t1);
-
- /* normals in render are inversed... */
- VecSubf(e1, co1, co2);
- VecSubf(e2, co1, co3);
- tang[0] = (t2*e1[0] - t1*e2[0])*det;
- tang[1] = (t2*e1[1] - t1*e2[1])*det;
- tang[2] = (t2*e1[2] - t1*e2[2])*det;
- tangv[0] = (s1*e2[0] - s2*e1[0])*det;
- tangv[1] = (s1*e2[1] - s2*e1[1])*det;
- tangv[2] = (s1*e2[2] - s2*e1[2])*det;
- Crossf(ct, tang, tangv);
-
- /* check flip */
- if ((ct[0]*n[0] + ct[1]*n[1] + ct[2]*n[2]) < 0.0f)
- VecMulf(tang, -1.0f);
-}
-
/* gets tangent from tface or orco */
-static void calc_tangent_vector(ObjectRen *obr, VlakRen *vlr)
+static void calc_tangent_vector(ObjectRen *obr, VertexTangent **vtangents, MemArena *arena, VlakRen *vlr, int do_nmap_tangent, int do_tangent)
{
MTFace *tface= RE_vlakren_get_tface(obr, vlr, obr->actmtface, NULL, 0);
VertRen *v1=vlr->v1, *v2=vlr->v2, *v3=vlr->v3, *v4=vlr->v4;
@@ -500,30 +480,55 @@ static void calc_tangent_vector(ObjectRen *obr, VlakRen *vlr)
tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, vlr->n, tang);
- tav= RE_vertren_get_tangent(obr, v1, 1);
- VECADD(tav, tav, tang);
- tav= RE_vertren_get_tangent(obr, v2, 1);
- VECADD(tav, tav, tang);
- tav= RE_vertren_get_tangent(obr, v3, 1);
- VECADD(tav, tav, tang);
-
- if(v4) {
- tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, vlr->n, tang);
-
+ if(do_tangent) {
tav= RE_vertren_get_tangent(obr, v1, 1);
VECADD(tav, tav, tang);
- tav= RE_vertren_get_tangent(obr, v3, 1);
+ tav= RE_vertren_get_tangent(obr, v2, 1);
VECADD(tav, tav, tang);
- tav= RE_vertren_get_tangent(obr, v4, 1);
+ tav= RE_vertren_get_tangent(obr, v3, 1);
VECADD(tav, tav, tang);
}
+
+ if(do_nmap_tangent) {
+ sum_or_add_vertex_tangent(arena, &vtangents[v1->index], tang, uv1);
+ sum_or_add_vertex_tangent(arena, &vtangents[v2->index], tang, uv2);
+ sum_or_add_vertex_tangent(arena, &vtangents[v3->index], tang, uv3);
+ }
+
+ if(v4) {
+ tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, vlr->n, tang);
+
+ if(do_tangent) {
+ tav= RE_vertren_get_tangent(obr, v1, 1);
+ VECADD(tav, tav, tang);
+ tav= RE_vertren_get_tangent(obr, v3, 1);
+ VECADD(tav, tav, tang);
+ tav= RE_vertren_get_tangent(obr, v4, 1);
+ VECADD(tav, tav, tang);
+ }
+
+ if(do_nmap_tangent) {
+ sum_or_add_vertex_tangent(arena, &vtangents[v1->index], tang, uv1);
+ sum_or_add_vertex_tangent(arena, &vtangents[v3->index], tang, uv3);
+ sum_or_add_vertex_tangent(arena, &vtangents[v4->index], tang, uv4);
+ }
+ }
}
-static void calc_vertexnormals(Render *re, ObjectRen *obr, int do_tangent)
+static void calc_vertexnormals(Render *re, ObjectRen *obr, int do_tangent, int do_nmap_tangent)
{
+ MemArena *arena= NULL;
+ VertexTangent **vtangents= NULL;
int a;
+ if(do_nmap_tangent) {
+ arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
+ BLI_memarena_use_calloc(arena);
+
+ vtangents= MEM_callocN(sizeof(VertexTangent*)*obr->totvert, "VertexTangent");
+ }
+
/* clear all vertex normals */
for(a=0; a<obr->totvert; a++) {
VertRen *ver= RE_findOrAddVert(obr, a);
@@ -596,10 +601,10 @@ static void calc_vertexnormals(Render *re, ObjectRen *obr, int do_tangent)
v3->n[2] +=fac3*vlr->n[2];
}
- if(do_tangent) {
+ if(do_nmap_tangent || do_tangent) {
/* tangents still need to be calculated for flat faces too */
/* weighting removed, they are not vertexnormals */
- calc_tangent_vector(obr, vlr);
+ calc_tangent_vector(obr, vtangents, arena, vlr, do_nmap_tangent, do_tangent);
}
}
@@ -618,6 +623,30 @@ static void calc_vertexnormals(Render *re, ObjectRen *obr, int do_tangent)
if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
}
}
+
+ if(do_nmap_tangent) {
+ VertRen *v1=vlr->v1, *v2=vlr->v2, *v3=vlr->v3, *v4=vlr->v4;
+ MTFace *tface= RE_vlakren_get_tface(obr, vlr, obr->actmtface, NULL, 0);
+
+ if(tface) {
+ float *vtang, *ftang= RE_vlakren_get_nmap_tangent(obr, vlr, 1);
+
+ vtang= find_vertex_tangent(vtangents[v1->index], tface->uv[0]);
+ VECCOPY(ftang, vtang);
+ Normalize(ftang);
+ vtang= find_vertex_tangent(vtangents[v2->index], tface->uv[1]);
+ VECCOPY(ftang+3, vtang);
+ Normalize(ftang+3);
+ vtang= find_vertex_tangent(vtangents[v3->index], tface->uv[2]);
+ VECCOPY(ftang+6, vtang);
+ Normalize(ftang+6);
+ if(v4) {
+ vtang= find_vertex_tangent(vtangents[v4->index], tface->uv[3]);
+ VECCOPY(ftang+9, vtang);
+ Normalize(ftang+9);
+ }
+ }
+ }
}
/* normalize vertex normals */
@@ -636,94 +665,12 @@ static void calc_vertexnormals(Render *re, ObjectRen *obr, int do_tangent)
}
}
}
-}
-// NT same as calc_vertexnormals, but dont modify the existing vertex normals
-// only recalculate other render data. If this is at some point used for other things than fluidsim,
-// this could be made on option for the normal calc_vertexnormals
-static void calc_fluidsimnormals(Render *re, ObjectRen *obr, int do_tangent)
-{
- int a;
-
- /* dont clear vertex normals here */
- // OFF for(a=0; a<obr->totvert; a++) { VertRen *ver= RE_findOrAddVert(obr, a); ver->n[0]=ver->n[1]=ver->n[2]= 0.0; }
- /* calculate cos of angles and point-masses, use as weight factor to add face normal to vertex */
- for(a=0; a<obr->totvlak; a++) {
- VlakRen *vlr= RE_findOrAddVlak(obr, a);
- if(vlr->flag & ME_SMOOTH) {
- VertRen *v1= vlr->v1;
- VertRen *v2= vlr->v2;
- VertRen *v3= vlr->v3;
- VertRen *v4= vlr->v4;
- float n1[3], n2[3], n3[3], n4[3];
- float fac1, fac2, fac3, fac4=0.0f;
-
- if(re->flag & R_GLOB_NOPUNOFLIP)
- vlr->flag |= R_NOPUNOFLIP;
-
- VecSubf(n1, v2->co, v1->co);
- Normalize(n1);
- VecSubf(n2, v3->co, v2->co);
- Normalize(n2);
- if(v4==NULL) {
- VecSubf(n3, v1->co, v3->co);
- Normalize(n3);
- fac1= saacos(-n1[0]*n3[0]-n1[1]*n3[1]-n1[2]*n3[2]);
- fac2= saacos(-n1[0]*n2[0]-n1[1]*n2[1]-n1[2]*n2[2]);
- fac3= saacos(-n2[0]*n3[0]-n2[1]*n3[1]-n2[2]*n3[2]);
- }
- else {
- VecSubf(n3, v4->co, v3->co);
- Normalize(n3);
- VecSubf(n4, v1->co, v4->co);
- Normalize(n4);
- fac1= saacos(-n4[0]*n1[0]-n4[1]*n1[1]-n4[2]*n1[2]);
- fac2= saacos(-n1[0]*n2[0]-n1[1]*n2[1]-n1[2]*n2[2]);
- fac3= saacos(-n2[0]*n3[0]-n2[1]*n3[1]-n2[2]*n3[2]);
- fac4= saacos(-n3[0]*n4[0]-n3[1]*n4[1]-n3[2]*n4[2]);
-
- if(!(vlr->flag & R_NOPUNOFLIP)) {
- if( check_vnormal(vlr->n, v4->n) ) fac4= -fac4;
- }
- }
-
- //if(do_tangent)
- // calc_tangent_vector(obr, vlr, fac1, fac2, fac3, fac4);
- }
- if(do_tangent) {
- /* tangents still need to be calculated for flat faces too */
- /* weighting removed, they are not vertexnormals */
- calc_tangent_vector(obr, vlr);
- }
- }
-
- /* do solid faces */
- for(a=0; a<obr->totvlak; a++) {
- VlakRen *vlr= RE_findOrAddVlak(obr, a);
- if((vlr->flag & ME_SMOOTH)==0) {
- float *f1= vlr->v1->n;
- if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
- f1= vlr->v2->n;
- if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
- f1= vlr->v3->n;
- if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
- if(vlr->v4) {
- f1= vlr->v4->n;
- if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
- }
- }
- }
-
- /* normalize vertex normals */
- for(a=0; a<obr->totvert; a++) {
- VertRen *ver= RE_findOrAddVert(obr, a);
- Normalize(ver->n);
- if(do_tangent) {
- float *tav= RE_vertren_get_tangent(obr, ver, 0);
- if(tav) Normalize(tav);
- }
- }
+ if(arena)
+ BLI_memarena_free(arena);
+ if(vtangents)
+ MEM_freeN(vtangents);
}
/* ------------------------------------------------------------------------- */
@@ -926,6 +873,8 @@ static float *get_object_orco(Render *re, Object *ob)
orco = make_orco_curve(ob);
} else if (ob->type==OB_SURF) {
orco = make_orco_surf(ob);
+ } else if (ob->type==OB_MBALL) {
+ orco = make_orco_mball(ob);
}
if (orco)
@@ -951,6 +900,26 @@ static void free_mesh_orco_hash(Render *re)
}
}
+static void flag_render_node_material(Render *re, bNodeTree *ntree)
+{
+ bNode *node;
+
+ for(node=ntree->nodes.first; node; node= node->next) {
+ if(node->id) {
+ if(GS(node->id->name)==ID_MA) {
+ Material *ma= (Material *)node->id;
+
+ if(ma->mode & MA_ZTRA)
+ re->flag |= R_ZTRA;
+
+ ma->flag |= MA_IS_USED;
+ }
+ else if(node->type==NODE_GROUP)
+ flag_render_node_material(re, (bNodeTree *)node->id);
+ }
+ }
+}
+
static Material *give_render_material(Render *re, Object *ob, int nr)
{
extern Material defmaterial; /* material.c */
@@ -959,14 +928,17 @@ static Material *give_render_material(Render *re, Object *ob, int nr)
ma= give_current_material(ob, nr);
if(ma==NULL)
ma= &defmaterial;
- else
- if(ma->mode & MA_ZTRA)
- re->flag |= R_ZTRA;
if(re->r.mode & R_SPEED) ma->texco |= NEED_UV;
+ if(ma->mode & MA_ZTRA)
+ re->flag |= R_ZTRA;
+
/* for light groups */
ma->flag |= MA_IS_USED;
+
+ if(ma->nodetree && ma->use_nodes)
+ flag_render_node_material(re, ma->nodetree);
return ma;
}
@@ -977,7 +949,7 @@ static Material *give_render_material(Render *re, Object *ob, int nr)
/* future thread problem... */
static void static_particle_strand(Render *re, ObjectRen *obr, Material *ma, float *orco, float *surfnor,
- float *uvco, int totuv, float *vec, float *vec1, float ctime,
+ float *uvco, int totuv, MCol *mcol, int totcol, float *vec, float *vec1, float ctime,
int first, int line, int adapt, float adapt_angle, float adapt_pix, int override_uv)
{
static VertRen *v1= NULL, *v2= NULL;
@@ -1040,7 +1012,6 @@ static void static_particle_strand(Render *re, ObjectRen *obr, Material *ma, flo
if(line) {
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
vlr->flag= flag;
- vlr->obr= obr;
vlr->v1= RE_findOrAddVert(obr, obr->totvert++);
vlr->v2= RE_findOrAddVert(obr, obr->totvert++);
vlr->v3= RE_findOrAddVert(obr, obr->totvert++);
@@ -1074,7 +1045,6 @@ static void static_particle_strand(Render *re, ObjectRen *obr, Material *ma, flo
vlr->mat= ma;
vlr->ec= ME_V2V3;
- vlr->lay= obr->ob->lay;
if(surfnor) {
float *snor= RE_vlakren_get_surfnor(obr, vlr, 1);
@@ -1101,6 +1071,14 @@ static void static_particle_strand(Render *re, ObjectRen *obr, Material *ma, flo
mtf->uv[2][1]=mtf->uv[3][1]=1.0f;
}
}
+ if(mcol){
+ for(i=0; i<totcol; i++){
+ MCol *mc;
+ mc=RE_vlakren_get_mcol(obr,vlr,i,NULL,1);
+ mc[0]=mc[1]=mc[2]=mc[3]=mcol[i];
+ mc[0]=mc[1]=mc[2]=mc[3]=mcol[i];
+ }
+ }
}
/* first two vertices of a strand */
else if(first) {
@@ -1130,7 +1108,6 @@ static void static_particle_strand(Render *re, ObjectRen *obr, Material *ma, flo
if(adapt==0 || second){
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
vlr->flag= flag;
- vlr->obr= obr;
vlr->v1= v1;
vlr->v2= v2;
vlr->v3= RE_findOrAddVert(obr, obr->totvert++);
@@ -1160,7 +1137,6 @@ static void static_particle_strand(Render *re, ObjectRen *obr, Material *ma, flo
if(Inpf(anor,nor)<adapt_angle && w>adapt_pix){
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
vlr->flag= flag;
- vlr->obr= obr;
vlr->v1= v1;
vlr->v2= v2;
vlr->v3= RE_findOrAddVert(obr, obr->totvert++);
@@ -1193,7 +1169,6 @@ static void static_particle_strand(Render *re, ObjectRen *obr, Material *ma, flo
vlr->mat= ma;
vlr->ec= ME_V2V3;
- vlr->lay= obr->ob->lay;
if(surfnor) {
float *snor= RE_vlakren_get_surfnor(obr, vlr, 1);
@@ -1220,6 +1195,14 @@ static void static_particle_strand(Render *re, ObjectRen *obr, Material *ma, flo
mtf->uv[2][1]=mtf->uv[3][1]=(vlr->v3->accum+1.0f)/2.0f;
}
}
+ if(mcol){
+ for(i=0; i<totcol; i++){
+ MCol *mc;
+ mc=RE_vlakren_get_mcol(obr,vlr,i,NULL,1);
+ mc[0]=mc[1]=mc[2]=mc[3]=mcol[i];
+ mc[0]=mc[1]=mc[2]=mc[3]=mcol[i];
+ }
+ }
}
}
@@ -1230,7 +1213,6 @@ static void static_particle_wire(ObjectRen *obr, Material *ma, float *vec, float
if(line) {
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
- vlr->obr= obr;
vlr->v1= RE_findOrAddVert(obr, obr->totvert++);
vlr->v2= RE_findOrAddVert(obr, obr->totvert++);
vlr->v3= vlr->v2;
@@ -1246,7 +1228,6 @@ static void static_particle_wire(ObjectRen *obr, Material *ma, float *vec, float
vlr->mat= ma;
vlr->ec= ME_V1V2;
- vlr->lay= obr->ob->lay;
}
else if(first) {
@@ -1255,7 +1236,6 @@ static void static_particle_wire(ObjectRen *obr, Material *ma, float *vec, float
}
else {
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
- vlr->obr= obr;
vlr->v1= v1;
vlr->v2= RE_findOrAddVert(obr, obr->totvert++);
vlr->v3= vlr->v2;
@@ -1270,7 +1250,6 @@ static void static_particle_wire(ObjectRen *obr, Material *ma, float *vec, float
vlr->mat= ma;
vlr->ec= ME_V1V2;
- vlr->lay= obr->ob->lay;
}
}
@@ -1287,7 +1266,6 @@ static void particle_billboard(Render *re, ObjectRen *obr, Material *ma, Object
onevec[align]=1.0f;
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
- vlr->obr= obr;
vlr->v1= RE_findOrAddVert(obr, obr->totvert++);
vlr->v2= RE_findOrAddVert(obr, obr->totvert++);
vlr->v3= RE_findOrAddVert(obr, obr->totvert++);
@@ -1370,7 +1348,6 @@ static void particle_billboard(Render *re, ObjectRen *obr, Material *ma, Object
vlr->mat= ma;
vlr->ec= ME_V2V3;
- vlr->lay= obr->ob->lay;
if(uv_split>1){
uvdx=uvdy=1.0f/(float)uv_split;
@@ -1456,7 +1433,8 @@ static void particle_billboard(Render *re, ObjectRen *obr, Material *ma, Object
}
static void render_new_particle(Render *re, ObjectRen *obr, DerivedMesh *dm, Material *ma, int path, int first, int line,
float time, float *loc, float *loc1, float *orco, float *surfnor, int totuv, float *uvco,
- float size, int seed, int override_uv, int adapt, float adapt_angle, float adapt_pix)
+ int totcol, MCol *mcol, float size, int seed, int override_uv,
+ int adapt, float adapt_angle, float adapt_pix)
{
HaloRen *har=0;
if(path){
@@ -1467,19 +1445,18 @@ static void render_new_particle(Render *re, ObjectRen *obr, DerivedMesh *dm, Mat
if(har) har->lay= obr->ob->lay;
}
else
- static_particle_strand(re, obr, ma, orco, surfnor, uvco, totuv, loc, loc1, time, first, line, adapt, adapt_angle, adapt_pix, override_uv);
+ static_particle_strand(re, obr, ma, orco, surfnor, uvco, totuv, mcol, totcol, loc, loc1, time, first, line, adapt, adapt_angle, adapt_pix, override_uv);
}
else{
har= RE_inithalo_particle(re, obr, dm, ma, loc, NULL, orco, uvco, size, 0.0, seed);
if(har) har->lay= obr->ob->lay;
}
}
-static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem *psys)
+static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem *psys, int timeoffset)
{
Object *ob= obr->ob;
Object *tob=0, *bb_ob=re->scene->camera;
Material *ma=0;
- CustomDataLayer *layer;
MTFace *mtface;
ParticleSystemModifierData *psmd;
ParticleSystem *tpsys=0;
@@ -1490,21 +1467,25 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
ParticleCacheKey *cache=0;
StrandBuffer *strandbuf=0;
StrandVert *svert=0;
+ StrandBound *sbound= 0;
StrandRen *strand=0;
RNG *rng= 0;
+ MCol *mcol= 0;
float loc[3],loc1[3],loc0[3],vel[3],mat[4][4],nmat[3][3],co[3],nor[3],time;
float *orco=0,*surfnor=0,*uvco=0, strandlen=0.0f, curlen=0.0f;
float hasize, pa_size, pa_time, r_tilt, cfra=bsystem_time(ob,(float)CFRA,0.0);
- float loc_tex[3], size_tex[3], adapt_angle=0.0, adapt_pix=0.0, random;
- float simplify[2];
- int i, a, k, max_k=0, totpart, totuv=0, override_uv=-1, dosimplify = 0;
- int path_possible=0, keys_possible=0, baked_keys=0, totchild=psys->totchild;
- int seed, path_nbr=0, path=0, orco1=0, adapt=0, uv[3]={0,0,0};
+ float adapt_angle=0.0, adapt_pix=0.0, random, simplify[2];
+ int i, a, k, max_k=0, totpart, totuv=0, totcol=0, override_uv=-1, dosimplify = 0, dosurfacecache = 0;
+ int path_possible=0, keys_possible=0, baked_keys=0, totchild=0;
+ int seed, path_nbr=0, path=0, orco1=0, adapt=0, uv[3]={0,0,0}, num;
+ int totface, *origindex = 0;
char **uv_name=0;
/* 1. check that everything is ok & updated */
if(psys==NULL)
return 0;
+
+ totchild=psys->totchild;
part=psys->part;
pars=psys->particles;
@@ -1547,6 +1528,7 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
RE_set_customdata_names(obr, &psmd->dm->faceData);
totuv=CustomData_number_of_layers(&psmd->dm->faceData,CD_MTFACE);
+ totcol=CustomData_number_of_layers(&psmd->dm->faceData,CD_MCOL);
if(ma->texco & TEXCO_UV && totuv) {
uvco = MEM_callocN(totuv*2*sizeof(float),"particle_uvs");
@@ -1557,6 +1539,9 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
}
}
+ if(totcol)
+ mcol = MEM_callocN(totcol*sizeof(MCol),"particle_mcols");
+
if(part->draw_as==PART_DRAW_BB){
int first_uv=CustomData_get_layer_index(&psmd->dm->faceData,CD_MTFACE);
@@ -1607,8 +1592,6 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
totpart=psys->totpart;
- mesh_get_texspace(ob->data, loc_tex, NULL, size_tex);
-
if(psys->pathcache){
path_possible=1;
keys_possible=1;
@@ -1645,12 +1628,37 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
strandbuf->overrideuv= override_uv;
strandbuf->minwidth= ma->strand_min;
+ if(ma->strand_widthfade == 0.0f)
+ strandbuf->widthfade= 0.0f;
+ else if(ma->strand_widthfade >= 1.0f)
+ strandbuf->widthfade= 2.0f - ma->strand_widthfade;
+ else
+ strandbuf->widthfade= 1.0f/MAX2(ma->strand_widthfade, 1e-5f);
+
if(part->flag & PART_HAIR_BSPLINE)
strandbuf->flag |= R_STRAND_BSPLINE;
if(ma->mode & MA_STR_B_UNITS)
strandbuf->flag |= R_STRAND_B_UNITS;
svert= strandbuf->vert;
+
+ if(re->r.mode & R_SPEED)
+ dosurfacecache= 1;
+ else if((re->wrld.mode & WO_AMB_OCC) && (re->wrld.ao_gather_method == WO_AOGATHER_APPROX))
+ if(ma->amb != 0.0f)
+ dosurfacecache= 1;
+
+ totface= psmd->dm->getNumFaces(psmd->dm);
+ origindex= psmd->dm->getFaceDataArray(psmd->dm, CD_ORIGINDEX);
+ if(origindex) {
+ for(a=0; a<totface; a++)
+ strandbuf->totbound= MAX2(strandbuf->totbound, origindex[a]);
+ strandbuf->totbound++;
+ }
+ strandbuf->totbound++;
+ strandbuf->bound= MEM_callocN(sizeof(StrandBound)*strandbuf->totbound, "StrandBound");
+ sbound= strandbuf->bound;
+ sbound->start= sbound->end= 0;
}
}
}
@@ -1669,7 +1677,7 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
psys->lattice=psys_get_lattice(ob,psys);
/* 3. start creating renderable things */
- for(a=0,pa=pars; a<totpart+totchild; a++, pa++) {
+ for(a=0,pa=pars; a<totpart+totchild; a++, pa++, seed++) {
random = rng_getFloat(rng);
if(a<totpart){
@@ -1694,20 +1702,43 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
/* get orco */
if(tpsys && (part->from==PART_FROM_PARTICLE || part->phystype==PART_PHYS_NO)){
tpa=tpsys->particles+pa->num;
- psys_particle_on_emitter(ob, psmd,tpart->from,tpa->num, -1,tpa->fuv,tpa->foffset,co,nor,0,0,orco,0);
+ psys_particle_on_emitter(psmd,tpart->from,tpa->num,pa->num_dmcache,tpa->fuv,tpa->foffset,co,nor,0,0,orco,0);
}
else
- psys_particle_on_emitter(ob, psmd,part->from,pa->num,-1,pa->fuv,pa->foffset,co,nor,0,0,orco,0);
+ psys_particle_on_emitter(psmd,part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,nor,0,0,orco,0);
+
+ num= pa->num_dmcache;
+
+ if(num == DMCACHE_NOTFOUND)
+ if(pa->num < psmd->dm->getNumFaces(psmd->dm))
+ num= pa->num;
if(uvco && ELEM(part->from,PART_FROM_FACE,PART_FROM_VOLUME)){
- layer=psmd->dm->faceData.layers + CustomData_get_layer_index(&psmd->dm->faceData,CD_MFACE);
for(i=0; i<totuv; i++){
- MFace *mface=psmd->dm->getFaceData(psmd->dm,pa->num,CD_MFACE);
-
- mtface=(MTFace*)CustomData_get_layer_n(&psmd->dm->faceData,CD_MTFACE,i);
- mtface+=pa->num;
-
- psys_interpolate_uvs(mtface,mface->v4,pa->fuv,uvco+2*i);
+ if(num != DMCACHE_NOTFOUND) {
+ MFace *mface=psmd->dm->getFaceData(psmd->dm,num,CD_MFACE);
+ mtface=(MTFace*)CustomData_get_layer_n(&psmd->dm->faceData,CD_MTFACE,i);
+ mtface+=num;
+
+ psys_interpolate_uvs(mtface,mface->v4,pa->fuv,uvco+2*i);
+ }
+ else {
+ uvco[2*i]= 0.0f;
+ uvco[2*i + 1]= 0.0f;
+ }
+ }
+ }
+ if(mcol && ELEM(part->from,PART_FROM_FACE,PART_FROM_VOLUME)){
+ for(i=0; i<totcol; i++){
+ if(num != DMCACHE_NOTFOUND) {
+ MFace *mface=psmd->dm->getFaceData(psmd->dm,num,CD_MFACE);
+ MCol *mc=(MCol*)CustomData_get_layer_n(&psmd->dm->faceData,CD_MCOL,i);
+ mc+=num*4;
+
+ psys_interpolate_mcol(mc,mface->v4,pa->fuv,mcol+i);
+ }
+ else
+ memset(&mcol[i], 0, sizeof(MCol));
}
}
@@ -1744,14 +1775,22 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
r_tilt=2.0f*cpa->rand[2];
+ num= cpa->num;
+
/* get orco */
- psys_particle_on_emitter(ob, psmd,
- (part->childtype == PART_CHILD_FACES)? PART_FROM_FACE: PART_FROM_PARTICLE,
- cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co,nor,0,0,orco,0);
+ if(part->childtype == PART_CHILD_FACES) {
+ psys_particle_on_emitter(psmd,
+ PART_FROM_FACE, cpa->num,DMCACHE_ISCHILD,
+ cpa->fuv,cpa->foffset,co,nor,0,0,orco,0);
+ }
+ else {
+ ParticleData *par = psys->particles + cpa->parent;
+ psys_particle_on_emitter(psmd, part->from,
+ par->num,DMCACHE_ISCHILD,par->fuv,
+ par->foffset,co,nor,0,0,orco,0);
+ }
if(uvco){
- layer=psmd->dm->faceData.layers + CustomData_get_layer_index(&psmd->dm->faceData,CD_MFACE);
-
if(part->from!=PART_FROM_PARTICLE && part->childtype==PART_CHILD_FACES){
for(i=0; i<totuv; i++){
if(part->childtype==PART_CHILD_FACES){
@@ -1768,30 +1807,77 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
}
}
else if(ELEM(part->from,PART_FROM_FACE,PART_FROM_VOLUME)){
- for(i=0; i<totuv; i++){
- ParticleData *parent = psys->particles+cpa->parent;
- MFace *mface=psmd->dm->getFaceData(psmd->dm,parent->num,CD_MFACE);
+ ParticleData *parent = psys->particles + cpa->parent;
+ num= parent->num_dmcache;
- mtface=(MTFace*)CustomData_get_layer_n(&psmd->dm->faceData,CD_MTFACE,i);
- mtface+=parent->num;
-
- psys_interpolate_uvs(mtface,mface->v4,parent->fuv,uvco+2*i);
+ if(num == DMCACHE_NOTFOUND)
+ if(parent->num < psmd->dm->getNumFaces(psmd->dm))
+ num= parent->num;
+
+ for(i=0; i<totuv; i++) {
+ if(num != DMCACHE_NOTFOUND) {
+ MFace *mface=psmd->dm->getFaceData(psmd->dm,num,CD_MFACE);
+ mtface=(MTFace*)CustomData_get_layer_n(&psmd->dm->faceData,CD_MTFACE,i);
+ mtface+=num;
+ psys_interpolate_uvs(mtface,mface->v4,parent->fuv,uvco+2*i);
+ }
+ else {
+ uvco[2*i]= 0.0f;
+ uvco[2*i + 1]= 0.0f;
+ }
+ }
+ }
+ }
+
+ if(mcol){
+ if(part->from!=PART_FROM_PARTICLE && part->childtype==PART_CHILD_FACES){
+ for(i=0; i<totcol; i++){
+ if(part->childtype==PART_CHILD_FACES){
+ MFace *mface=psmd->dm->getFaceData(psmd->dm,cpa->num,CD_MFACE);
+ MCol *mc=(MCol*)CustomData_get_layer_n(&psmd->dm->faceData,CD_MCOL,i);
+ mc+=cpa->num*4;
+
+ psys_interpolate_mcol(mc,mface->v4,cpa->fuv,mcol+i);
+ }
+ else
+ memset(&mcol[i], 0, sizeof(MCol));
+ }
+ }
+ else if(ELEM(part->from,PART_FROM_FACE,PART_FROM_VOLUME)){
+ ParticleData *parent = psys->particles + cpa->parent;
+ num= parent->num_dmcache;
+
+ if(num == DMCACHE_NOTFOUND)
+ if(parent->num < psmd->dm->getNumFaces(psmd->dm))
+ num= parent->num;
+
+ for(i=0; i<totcol; i++){
+ if(num != DMCACHE_NOTFOUND) {
+ MFace *mface=psmd->dm->getFaceData(psmd->dm,num,CD_MFACE);
+ MCol *mc=(MCol*)CustomData_get_layer_n(&psmd->dm->faceData,CD_MCOL,i);
+ mc+=num*4;
+
+ psys_interpolate_mcol(mc,mface->v4,parent->fuv,mcol+i);
+ }
+ else
+ memset(&mcol[i], 0, sizeof(MCol));
}
}
}
dosimplify= psys_render_simplify_params(psys, cpa, simplify);
- if(path_nbr) {
+ if(path_nbr && psys->childcache) {
cache = psys->childcache[a-totpart];
max_k = (int)cache->steps;
}
- }
- if(orco) {
- orco[0] = (orco[0]-loc_tex[0])/size_tex[0];
- orco[1] = (orco[1]-loc_tex[1])/size_tex[1];
- orco[2] = (orco[2]-loc_tex[2])/size_tex[2];
+ if(strandbuf) {
+ if(origindex[cpa->num]+1 > sbound - strandbuf->bound) {
+ sbound= strandbuf->bound + origindex[cpa->num]+1;
+ sbound->start= sbound->end= obr->totstrand;
+ }
+ }
}
/* surface normal shading setup */
@@ -1820,8 +1906,13 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
VECCOPY(snor, surfnor);
}
- if(uvco){
- for(i=0; i<totuv; i++){
+ if(dosurfacecache && num >= 0) {
+ int *facenum= RE_strandren_get_face(obr, strand, 1);
+ *facenum= num;
+ }
+
+ if(uvco) {
+ for(i=0; i<totuv; i++) {
if(i != override_uv) {
float *uv= RE_strandren_get_uv(obr, strand, i, NULL, 1);
@@ -1830,6 +1921,14 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
}
}
}
+ if(mcol) {
+ for(i=0; i<totcol; i++) {
+ MCol *mc= RE_strandren_get_mcol(obr, strand, i, NULL, 1);
+ *mc = mcol[i];
+ }
+ }
+
+ sbound->end++;
}
/* strandco computation setup */
@@ -1879,7 +1978,7 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
VECADDFAC(loc1,loc,vel,part->draw_line[1]);
render_new_particle(re,obr,psmd->dm,ma,1,0,1,0.0f,loc0,loc1,
- orco,surfnor,totuv,uvco,hasize,seed,override_uv,0,0,0);
+ orco,surfnor,totuv,uvco,totcol,mcol,hasize,seed,override_uv,0,0,0);
}
else if(part->draw_as==PART_DRAW_BB) {
VECCOPY(vel,state.vel);
@@ -1899,13 +1998,13 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
VECSUB(loc0,loc1,loc);
VECADD(loc0,loc1,loc0);
render_new_particle(re,obr,psmd->dm,ma,path,1,0,0.0f,loc1,loc0,
- orco,surfnor,totuv,uvco,hasize,seed,override_uv,
+ orco,surfnor,totuv,uvco,totcol,mcol,hasize,seed,override_uv,
adapt,adapt_angle,adapt_pix);
}
if(path_nbr==0 || k)
render_new_particle(re,obr,psmd->dm,ma,path,0,0,time,loc,loc1,
- orco,surfnor,totuv,uvco,hasize,seed,override_uv,
+ orco,surfnor,totuv,uvco,totcol,mcol,hasize,seed,override_uv,
adapt,adapt_angle,adapt_pix);
VECCOPY(loc1,loc);
@@ -1919,6 +2018,9 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
break;
}
+ if(dosurfacecache)
+ strandbuf->surface= cache_strand_surface(re, obr, psmd->dm, mat, timeoffset);
+
/* 4. clean up */
if(ma) do_mat_ipo(ma);
@@ -1927,6 +2029,9 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
if(uvco)
MEM_freeN(uvco);
+
+ if(mcol)
+ MEM_freeN(mcol);
if(uv_name)
MEM_freeN(uv_name);
@@ -1944,7 +2049,7 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
}
if(path && (ma->mode_l & MA_TANGENT_STR)==0)
- calc_vertexnormals(re, obr, 0);
+ calc_vertexnormals(re, obr, 0, 0);
return 1;
}
@@ -2005,7 +2110,8 @@ static void make_render_halos(Render *re, ObjectRen *obr, Mesh *me, int totvert,
static int verghalo(const void *a1, const void *a2)
{
- const HaloRen *har1= a1, *har2= a2;
+ const HaloRen *har1= *(const HaloRen**)a1;
+ const HaloRen *har2= *(const HaloRen**)a2;
if(har1->zs < har2->zs) return 1;
else if(har1->zs > har2->zs) return -1;
@@ -2053,11 +2159,11 @@ static short test_for_displace(Render *re, Object *ob)
return 0;
}
-static void displace_render_vert(Render *re, ObjectRen *obr, ShadeInput *shi, VertRen *vr, int vindex, float *scale)
+static void displace_render_vert(Render *re, ObjectRen *obr, ShadeInput *shi, VertRen *vr, int vindex, float *scale, float mat[][4], float imat[][3])
{
MTFace *tface;
short texco= shi->mat->texco;
- float sample=0;
+ float sample=0, displace[3];
char *name;
int i;
@@ -2066,6 +2172,15 @@ static void displace_render_vert(Render *re, ObjectRen *obr, ShadeInput *shi, Ve
/* vertex normal is used for textures type 'col' and 'var' */
VECCOPY(shi->vn, vr->n);
+ if(mat)
+ Mat4MulVecfl(mat, shi->co);
+
+ if(imat) {
+ shi->vn[0]= imat[0][0]*vr->n[0]+imat[0][1]*vr->n[1]+imat[0][2]*vr->n[2];
+ shi->vn[1]= imat[1][0]*vr->n[0]+imat[1][1]*vr->n[1]+imat[1][2]*vr->n[2];
+ shi->vn[2]= imat[2][0]*vr->n[0]+imat[2][1]*vr->n[1]+imat[2][2]*vr->n[2];
+ }
+
if (texco & TEXCO_UV) {
shi->totuv= 0;
shi->actuv= obr->actmtface;
@@ -2111,11 +2226,18 @@ static void displace_render_vert(Render *re, ObjectRen *obr, ShadeInput *shi, Ve
//printf("no=%f, %f, %f\nbefore co=%f, %f, %f\n", vr->n[0], vr->n[1], vr->n[2],
//vr->co[0], vr->co[1], vr->co[2]);
+
+ displace[0]= shi->displace[0] * scale[0];
+ displace[1]= shi->displace[1] * scale[1];
+ displace[2]= shi->displace[2] * scale[2];
+ if(mat)
+ Mat3MulVecfl(imat, displace);
+
/* 0.5 could become button once? */
- vr->co[0] += shi->displace[0] * scale[0] ;
- vr->co[1] += shi->displace[1] * scale[1] ;
- vr->co[2] += shi->displace[2] * scale[2] ;
+ vr->co[0] += displace[0];
+ vr->co[1] += displace[1];
+ vr->co[2] += displace[2];
//printf("after co=%f, %f, %f\n", vr->co[0], vr->co[1], vr->co[2]);
@@ -2133,28 +2255,36 @@ static void displace_render_vert(Render *re, ObjectRen *obr, ShadeInput *shi, Ve
return;
}
-static void displace_render_face(Render *re, VlakRen *vlr, float *scale)
+static void displace_render_face(Render *re, ObjectRen *obr, VlakRen *vlr, float *scale, float mat[][4], float imat[][3])
{
ShadeInput shi;
+ /* Warning, This is not that nice, and possibly a bit slow,
+ however some variables were not initialized properly in, unless using shade_input_initialize(...), we need to do a memset */
+ memset(&shi, 0, sizeof(ShadeInput));
+ /* end warning! - Campbell */
+
/* set up shadeinput struct for multitex() */
- shi.osatex= 0; /* signal not to use dx[] and dy[] texture AA vectors */
+
+ /* memset above means we dont need this */
+ /*shi.osatex= 0;*/ /* signal not to use dx[] and dy[] texture AA vectors */
+
shi.vlr= vlr; /* current render face */
shi.mat= vlr->mat; /* current input material */
/* Displace the verts, flag is set when done */
if (!vlr->v1->flag)
- displace_render_vert(re, vlr->obr, &shi, vlr->v1,0, scale);
+ displace_render_vert(re, obr, &shi, vlr->v1,0, scale, mat, imat);
if (!vlr->v2->flag)
- displace_render_vert(re, vlr->obr, &shi, vlr->v2, 1, scale);
+ displace_render_vert(re, obr, &shi, vlr->v2, 1, scale, mat, imat);
if (!vlr->v3->flag)
- displace_render_vert(re, vlr->obr, &shi, vlr->v3, 2, scale);
+ displace_render_vert(re, obr, &shi, vlr->v3, 2, scale, mat, imat);
if (vlr->v4) {
if (!vlr->v4->flag)
- displace_render_vert(re, vlr->obr, &shi, vlr->v4, 3, scale);
+ displace_render_vert(re, obr, &shi, vlr->v4, 3, scale, mat, imat);
/* closest in displace value. This will help smooth edges. */
if ( fabs(vlr->v1->accum - vlr->v3->accum) > fabs(vlr->v2->accum - vlr->v4->accum))
@@ -2171,7 +2301,7 @@ static void displace_render_face(Render *re, VlakRen *vlr, float *scale)
}
}
-static void do_displacement(Render *re, ObjectRen *obr)
+static void do_displacement(Render *re, ObjectRen *obr, float mat[][4], float imat[][3])
{
VertRen *vr;
VlakRen *vlr;
@@ -2196,11 +2326,11 @@ static void do_displacement(Render *re, ObjectRen *obr)
for(i=0; i<obr->totvlak; i++){
vlr=RE_findOrAddVlak(obr, i);
- displace_render_face(re, vlr, scale);
+ displace_render_face(re, obr, vlr, scale, mat, imat);
}
/* Recalc vertex normals */
- calc_vertexnormals(re, obr, 0);
+ calc_vertexnormals(re, obr, 0, 0);
}
/* ------------------------------------------------------------------------- */
@@ -2214,8 +2344,8 @@ static void init_render_mball(Render *re, ObjectRen *obr)
VertRen *ver;
VlakRen *vlr, *vlr1;
Material *ma;
- float *data, *nors, mat[4][4], imat[3][3], xn, yn, zn;
- int a, need_orco, *index;
+ float *data, *nors, *orco, mat[4][4], imat[3][3], xn, yn, zn;
+ int a, need_orco, vlakindex, *index;
if (ob!=find_basis_mball(ob))
return;
@@ -2237,8 +2367,9 @@ static void init_render_mball(Render *re, ObjectRen *obr)
data= dl->verts;
nors= dl->nors;
+ orco= get_object_orco(re, ob);
- for(a=0; a<dl->nr; a++, data+=3, nors+=3) {
+ for(a=0; a<dl->nr; a++, data+=3, nors+=3, orco+=3) {
ver= RE_findOrAddVert(obr, obr->totvert++);
VECCOPY(ver->co, data);
@@ -2256,14 +2387,13 @@ static void init_render_mball(Render *re, ObjectRen *obr)
Normalize(ver->n);
//if(ob->transflag & OB_NEG_SCALE) VecMulf(ver->n. -1.0);
- if(need_orco) ver->orco= data;
+ if(need_orco) ver->orco= orco;
}
index= dl->index;
for(a=0; a<dl->parts; a++, index+=4) {
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
- vlr->obr= obr;
vlr->v1= RE_findOrAddVert(obr, index[0]);
vlr->v2= RE_findOrAddVert(obr, index[1]);
vlr->v3= RE_findOrAddVert(obr, index[2]);
@@ -2277,12 +2407,13 @@ static void init_render_mball(Render *re, ObjectRen *obr)
vlr->mat= ma;
vlr->flag= ME_SMOOTH+R_NOPUNOFLIP;
vlr->ec= 0;
- vlr->lay= ob->lay;
/* mball -too bad- always has triangles, because quads can be non-planar */
if(index[3] && index[3]!=index[2]) {
vlr1= RE_findOrAddVlak(obr, obr->totvlak++);
+ vlakindex= vlr1->index;
*vlr1= *vlr;
+ vlr1->index= vlakindex;
vlr1->v2= vlr1->v3;
vlr1->v3= RE_findOrAddVert(obr, index[3]);
if(ob->transflag & OB_NEG_SCALE)
@@ -2292,14 +2423,8 @@ static void init_render_mball(Render *re, ObjectRen *obr)
}
}
- if(need_orco) {
- /* store displist and scale */
- make_orco_mball(ob);
- }
- else {
- /* enforce display lists remade */
- freedisplist(&ob->disp);
- }
+ /* enforce display lists remade */
+ freedisplist(&ob->disp);
/* this enforces remake for real, orco displist is small (in scale) */
ob->recalc |= OB_RECALC_DATA;
@@ -2316,7 +2441,7 @@ static int dl_surf_to_renderdata(ObjectRen *obr, DispList *dl, Material **matar,
VertRen *v1, *v2, *v3, *v4, *ver;
VlakRen *vlr, *vlr1, *vlr2, *vlr3;
Curve *cu= ob->data;
- float *data, n1[3], flen;
+ float *data, n1[3];
int u, v, orcoret= 0;
int p1, p2, p3, p4, a;
int sizeu, nsizeu, sizev, nsizev;
@@ -2386,13 +2511,12 @@ static int dl_surf_to_renderdata(ObjectRen *obr, DispList *dl, Material **matar,
v4= RE_findOrAddVert(obr, p4);
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
- vlr->obr= obr;
vlr->v1= v1; vlr->v2= v2; vlr->v3= v3; vlr->v4= v4;
- flen= CalcNormFloat4(vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co, n1);
+ CalcNormFloat4(vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co, n1);
+
VECCOPY(vlr->n, n1);
- vlr->lay= ob->lay;
vlr->mat= matar[ dl->col];
vlr->ec= ME_V1V2+ME_V2V3;
vlr->flag= dl->rt;
@@ -2524,7 +2648,7 @@ static void init_render_surf(Render *re, ObjectRen *obr)
freedisplist(&displist);
}
-static void init_render_curve(Render *re, ObjectRen *obr, int only_verts)
+static void init_render_curve(Render *re, ObjectRen *obr, int timeoffset)
{
Object *ob= obr->ob;
Curve *cu;
@@ -2539,7 +2663,8 @@ static void init_render_curve(Render *re, ObjectRen *obr, int only_verts)
int frontside, need_orco=0;
cu= ob->data;
- if(cu->nurb.first==NULL) return;
+ if(ob->type==OB_FONT && cu->str==NULL) return;
+ else if(ob->type==OB_CURVE && cu->nurb.first==NULL) return;
/* no modifier call here, is in makedisp */
@@ -2602,13 +2727,12 @@ static void init_render_curve(Render *re, ObjectRen *obr, int only_verts)
}
}
- if(only_verts==0) {
+ if(timeoffset==0) {
startvlak= obr->totvlak;
index= dl->index;
for(a=0; a<dl->parts; a++, index+=3) {
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
- vlr->obr = obr;
vlr->v1= RE_findOrAddVert(obr, startvert+index[0]);
vlr->v2= RE_findOrAddVert(obr, startvert+index[1]);
vlr->v3= RE_findOrAddVert(obr, startvert+index[2]);
@@ -2627,7 +2751,6 @@ static void init_render_curve(Render *re, ObjectRen *obr, int only_verts)
vlr->flag |= R_NOPUNOFLIP;
}
vlr->ec= 0;
- vlr->lay= ob->lay;
}
}
}
@@ -2657,14 +2780,16 @@ static void init_render_curve(Render *re, ObjectRen *obr, int only_verts)
}
}
- if(dl->bevelSplitFlag || only_verts==0) {
+ if(dl->bevelSplitFlag || timeoffset==0) {
startvlak= obr->totvlak;
for(a=0; a<dl->parts; a++) {
frontside= (a >= dl->nr/2);
-
- DL_SURFINDEX(dl->flag & DL_CYCL_U, dl->flag & DL_CYCL_V, dl->nr, dl->parts);
+
+ if (surfindex_displist(dl, a, &b, &p1, &p2, &p3, &p4)==0)
+ break;
+
p1+= startvert;
p2+= startvert;
p3+= startvert;
@@ -2672,7 +2797,6 @@ static void init_render_curve(Render *re, ObjectRen *obr, int only_verts)
for(; b<dl->nr; b++) {
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
- vlr->obr= obr;
vlr->v1= RE_findOrAddVert(obr, p2);
vlr->v2= RE_findOrAddVert(obr, p1);
vlr->v3= RE_findOrAddVert(obr, p3);
@@ -2681,7 +2805,6 @@ static void init_render_curve(Render *re, ObjectRen *obr, int only_verts)
if(a==0) vlr->ec+= ME_V1V2;
vlr->flag= dl->rt;
- vlr->lay= ob->lay;
/* this is not really scientific: the vertices
* 2, 3 en 4 seem to give better vertexnormals than 1 2 3:
@@ -2875,7 +2998,7 @@ static void use_mesh_edge_lookup(ObjectRen *obr, DerivedMesh *dm, MEdge *medge,
}
}
-static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
+static void init_render_mesh(Render *re, ObjectRen *obr, int timeoffset)
{
Object *ob= obr->ob;
Mesh *me;
@@ -2889,9 +3012,9 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
CustomDataMask mask;
float xn, yn, zn, imat[3][3], mat[4][4]; //nor[3],
float *orco=0;
- int a, a1, ok, need_orco=0, need_stress=0, need_tangent=0, vertofs;
+ int need_orco=0, need_stress=0, need_nmap_tangent=0, need_tangent=0;
+ int a, a1, ok, vertofs;
int end, do_autosmooth=0, totvert = 0;
- int useFluidmeshNormals= 0; // NT fluidsim, use smoothed normals?
int use_original_normals= 0;
me= ob->data;
@@ -2912,11 +3035,19 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
if(ma->texco & TEXCO_STRESS)
need_stress= 1;
/* normalmaps, test if tangents needed, separated from shading */
- if ((ma->mode_l & MA_TANGENT_V) || (ma->mode_l & MA_NORMAP_TANG)) {
+ if(ma->mode_l & MA_TANGENT_V) {
need_tangent= 1;
if(me->mtface==NULL)
need_orco= 1;
}
+ if(ma->mode_l & MA_NORMAP_TANG) {
+ if(me->mtface==NULL) {
+ need_orco= 1;
+ need_tangent= 1;
+ }
+ need_nmap_tangent= 1;
+ }
+
/* radio faces need autosmooth, to separate shared vertices in corners */
if(re->r.mode & R_RADIO)
if(ma->mode & MA_RADIO)
@@ -2926,23 +3057,32 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
if(re->flag & R_NEED_TANGENT) {
/* exception for tangent space baking */
- need_tangent= 1;
- if(me->mtface==NULL)
+ if(me->mtface==NULL) {
need_orco= 1;
+ need_tangent= 1;
+ }
+ need_nmap_tangent= 1;
}
/* check autosmooth and displacement, we then have to skip only-verts optimize */
do_autosmooth |= (me->flag & ME_AUTOSMOOTH);
if(do_autosmooth)
- only_verts= 0;
+ timeoffset= 0;
if(test_for_displace(re, ob ) )
- only_verts= 0;
+ timeoffset= 0;
mask= CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL;
- if(!only_verts)
+ if(!timeoffset)
if(need_orco)
mask |= CD_MASK_ORCO;
+ if(me->mr) {
+ if(re->flag & R_SKIP_MULTIRES)
+ me->mr->flag |= MULTIRES_NO_RENDER;
+ else
+ me->mr->flag &= ~MULTIRES_NO_RENDER;
+ }
+
dm= mesh_create_derived_render(ob, mask);
if(dm==NULL) return; /* in case duplicated object fails? */
@@ -2954,12 +3094,6 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
}
}
- if((ob->fluidsimFlag & OB_FLUIDSIM_ENABLE) &&
- (ob->fluidsimSettings->type & OB_FLUIDSIM_DOMAIN)&&
- (ob->fluidsimSettings->meshSurface) ) {
- useFluidmeshNormals = 1;
- }
-
mvert= dm->getVertArray(dm);
totvert= dm->getNumVerts(dm);
@@ -2982,17 +3116,6 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
if(do_autosmooth==0) /* autosmooth on original unrotated data to prevent differences between frames */
MTC_Mat4MulVecfl(mat, ver->co);
- if(useFluidmeshNormals) {
- /* normals are inverted in render */
- xn = -mvert->no[0]/ 32767.0;
- yn = -mvert->no[1]/ 32767.0;
- zn = -mvert->no[2]/ 32767.0;
- /* transfor to cam space */
- ver->n[0]= imat[0][0]*xn+imat[0][1]*yn+imat[0][2]*zn;
- ver->n[1]= imat[1][0]*xn+imat[1][1]*yn+imat[1][2]*zn;
- ver->n[2]= imat[2][0]*xn+imat[2][1]*yn+imat[2][2]*zn;
- } // useFluidmeshNormals
-
if(orco) {
ver->orco= orco;
orco+=3;
@@ -3005,7 +3128,7 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
}
}
- if(!only_verts) {
+ if(!timeoffset) {
/* store customdata names, because DerivedMesh is freed */
RE_set_customdata_names(obr, &dm->faceData);
@@ -3052,7 +3175,6 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
flag= mface->flag & ME_SMOOTH;
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
- vlr->obr= obr;
vlr->v1= RE_findOrAddVert(obr, vertofs+v1);
vlr->v2= RE_findOrAddVert(obr, vertofs+v2);
vlr->v3= RE_findOrAddVert(obr, vertofs+v3);
@@ -3082,7 +3204,6 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
vlr->flag |= R_NOPUNOFLIP;
}
vlr->ec= 0; /* mesh edges rendered separately */
- vlr->lay= ob->lay;
if(len==0) obr->totvlak--;
else {
@@ -3133,7 +3254,6 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
MVert *v1 = &mvert[medge->v2];
vlr= RE_findOrAddVlak(obr, obr->totvlak++);
- vlr->obr= obr;
vlr->v1= RE_findOrAddVert(obr, vertofs+medge->v1);
vlr->v2= RE_findOrAddVert(obr, vertofs+medge->v2);
vlr->v3= vlr->v2;
@@ -3154,7 +3274,6 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
vlr->mat= ma;
vlr->flag= 0;
vlr->ec= ME_V1V2;
- vlr->lay= ob->lay;
}
}
if(edgetable)
@@ -3163,22 +3282,20 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int only_verts)
}
}
- if(!only_verts) {
+ if(!timeoffset) {
if (test_for_displace(re, ob ) ) {
- calc_vertexnormals(re, obr, 0);
- do_displacement(re, obr);
+ calc_vertexnormals(re, obr, 0, 0);
+ if(do_autosmooth)
+ do_displacement(re, obr, mat, imat);
+ else
+ do_displacement(re, obr, NULL, NULL);
}
if(do_autosmooth) {
autosmooth(re, obr, mat, me->smoothresh);
}
- if(useFluidmeshNormals) {
- // do not recalculate, only init render data
- calc_fluidsimnormals(re, obr, need_tangent);
- } else {
- calc_vertexnormals(re, obr, need_tangent);
- }
+ calc_vertexnormals(re, obr, need_tangent, need_nmap_tangent);
if(need_stress)
calc_edge_stress(re, obr, me);
@@ -3209,8 +3326,6 @@ static void initshadowbuf(Render *re, LampRen *lar, float mat[][4])
/* percentage render: keep track of min and max */
shb->size= (lar->bufsize*re->r.size)/100;
- if(lar->buffers>1) shb->size/= 2;
-
if(shb->size<512) shb->size= 512;
else if(shb->size > lar->bufsize) shb->size= lar->bufsize;
@@ -3282,6 +3397,7 @@ static GroupObject *add_render_lamp(Render *re, Object *ob)
LampRen *lar;
GroupObject *go;
float mat[4][4], angle, xn, yn;
+ float vec[3];
int c;
/* previewrender sets this to zero... prevent accidents */
@@ -3341,6 +3457,9 @@ static GroupObject *add_render_lamp(Render *re, Object *ob)
lar->r= lar->energy*la->r;
lar->g= lar->energy*la->g;
lar->b= lar->energy*la->b;
+ lar->shdwr= la->shdwr;
+ lar->shdwg= la->shdwg;
+ lar->shdwb= la->shdwb;
lar->k= la->k;
// area
@@ -3353,12 +3472,20 @@ static GroupObject *add_render_lamp(Render *re, Object *ob)
lar->area_sizez= la->area_sizez;
lar->area_shape= la->area_shape;
+
+ /* Annoying, lamp UI does this, but the UI might not have been used? - add here too.
+ * make sure this matches buttons_shading.c's logic */
+ if(ELEM4(la->type, LA_AREA, LA_SPOT, LA_SUN, LA_LOCAL) && (la->mode & LA_SHAD_RAY))
+ if (ELEM3(la->type, LA_SPOT, LA_SUN, LA_LOCAL))
+ if (la->ray_samp_method == LA_SAMP_CONSTANT) la->ray_samp_method = LA_SAMP_HALTON;
+
lar->ray_samp_method= la->ray_samp_method;
lar->ray_samp_type= la->ray_samp_type;
lar->adapt_thresh= la->adapt_thresh;
+ lar->sunsky = NULL;
- if( ELEM3(lar->type, LA_SPOT, LA_SUN, LA_LOCAL)) {
+ if( ELEM(lar->type, LA_SPOT, LA_LOCAL)) {
lar->ray_totsamp= lar->ray_samp*lar->ray_samp;
lar->area_shape = LA_AREA_SQUARE;
lar->area_sizey= lar->area_size;
@@ -3388,6 +3515,27 @@ static GroupObject *add_render_lamp(Render *re, Object *ob)
area_lamp_vectors(lar);
init_jitter_plane(lar); // subsamples
}
+ else if(lar->type==LA_SUN){
+ lar->ray_totsamp= lar->ray_samp*lar->ray_samp;
+ lar->area_shape = LA_AREA_SQUARE;
+ lar->area_sizey= lar->area_size;
+
+ if((la->sun_effect_type & LA_SUN_EFFECT_SKY) ||
+ (la->sun_effect_type & LA_SUN_EFFECT_AP)){
+ lar->sunsky = (struct SunSky*)MEM_callocN(sizeof(struct SunSky), "sunskyren");
+ lar->sunsky->effect_type = la->sun_effect_type;
+
+ VECCOPY(vec,ob->obmat[2]);
+ Normalize(vec);
+
+ InitSunSky(lar->sunsky, la->atm_turbidity, vec, la->horizon_brightness,
+ la->spread, la->sun_brightness, la->sun_size, la->backscattered_light,
+ la->skyblendfac, la->skyblendtype, la->sky_exposure, la->sky_colorspace);
+
+ InitAtmosphere(lar->sunsky, la->sun_intensity, 1.0, 1.0, la->atm_inscattering_factor, la->atm_extinction_factor,
+ la->atm_distance_factor);
+ }
+ }
else lar->ray_totsamp= 0;
#ifndef DISABLE_YAFRAY
@@ -3465,7 +3613,10 @@ static GroupObject *add_render_lamp(Render *re, Object *ob)
for(c=0; c<MAX_MTEX; c++) {
if(la->mtex[c] && la->mtex[c]->tex) {
- lar->mode |= LA_TEXTURE;
+ if (la->mtex[c]->mapto & LAMAP_COL)
+ lar->mode |= LA_TEXTURE;
+ if (la->mtex[c]->mapto & LAMAP_SHAD)
+ lar->mode |= LA_SHAD_TEX;
if(G.rendering) {
if(re->osa) {
@@ -3485,9 +3636,6 @@ static GroupObject *add_render_lamp(Render *re, Object *ob)
if(re->r.mode & R_SHADOW) {
- if ((lar->mode & LA_SHAD_RAY) && (lar->ray_samp_method == LA_SAMP_HAMMERSLEY)) {
- init_lamp_hammersley(lar);
- }
if(la->type==LA_AREA && (lar->mode & LA_SHAD_RAY) && (lar->ray_samp_method == LA_SAMP_CONSTANT)) {
init_jitter_plane(lar);
}
@@ -3501,16 +3649,24 @@ static GroupObject *add_render_lamp(Render *re, Object *ob)
/* this is the way used all over to check for shadow */
if(lar->shb || (lar->mode & LA_SHAD_RAY)) {
+ LampShadowSample *ls;
LampShadowSubSample *lss;
- int a, b, tot= re->r.threads*re->r.osa;
+ int a, b;
+
+ memset(re->shadowsamplenr, 0, sizeof(re->shadowsamplenr));
lar->shadsamp= MEM_mallocN(re->r.threads*sizeof(LampShadowSample), "lamp shadow sample");
- lss= lar->shadsamp[0].s;
+ ls= lar->shadsamp;
+
/* shadfacs actually mean light, let's put them to 1 to prevent unitialized accidents */
- for(a=0; a<tot; a++, lss++) {
- for(b=0; b<4; b++) {
+ for(a=0; a<re->r.threads; a++, ls++) {
+ lss= ls->s;
+ for(b=0; b<re->r.osa; b++, lss++) {
lss->samplenr= -1; /* used to detect whether we store or read */
- lss->shadfac[b]= 1.0f;
+ lss->shadfac[0]= 1.0f;
+ lss->shadfac[1]= 1.0f;
+ lss->shadfac[2]= 1.0f;
+ lss->shadfac[3]= 1.0f;
}
}
}
@@ -3611,13 +3767,18 @@ void init_render_world(Render *re)
if(re->osa)
while(re->wrld.aosamp*re->wrld.aosamp < re->osa)
re->wrld.aosamp++;
- if(!(re->r.mode & R_RAYTRACE))
+ if(!(re->r.mode & R_RAYTRACE) && (re->wrld.ao_gather_method == WO_AOGATHER_RAYTRACE))
re->wrld.mode &= ~WO_AMB_OCC;
}
else {
memset(&re->wrld, 0, sizeof(World));
- re->wrld.exp= 0.0;
- re->wrld.range= 1.0;
+ re->wrld.exp= 0.0f;
+ re->wrld.range= 1.0f;
+
+ /* for mist pass */
+ re->wrld.miststa= re->clipsta;
+ re->wrld.mistdist= re->clipend-re->clipsta;
+ re->wrld.misi= 1.0f;
}
re->wrld.linfac= 1.0 + pow((2.0*re->wrld.exp + 0.5), -10);
@@ -3679,7 +3840,7 @@ static void set_phong_threshold(ObjectRen *obr)
}
/* per face check if all samples should be taken.
- if raytrace, do always for raytraced material, or when material full_osa set */
+ if raytrace or multisample, do always for raytraced material, or when material full_osa set */
static void set_fullsample_flag(Render *re, ObjectRen *obr)
{
VlakRen *vlr;
@@ -3693,7 +3854,8 @@ static void set_fullsample_flag(Render *re, ObjectRen *obr)
for(a=obr->totvlak-1; a>=0; a--) {
vlr= RE_findOrAddVlak(obr, a);
- if(vlr->mat->mode & MA_FULL_OSA) vlr->flag |= R_FULL_OSA;
+ if(vlr->mat->mode & MA_FULL_OSA)
+ vlr->flag |= R_FULL_OSA;
else if(trace) {
if(vlr->mat->mode & MA_SHLESS);
else if(vlr->mat->mode & (MA_RAYTRANSP|MA_RAYMIRROR))
@@ -3705,6 +3867,57 @@ static void set_fullsample_flag(Render *re, ObjectRen *obr)
}
}
+/* split quads for pradictable baking
+ * dir 1 == (0,1,2) (0,2,3), 2 == (1,3,0) (1,2,3)
+ */
+static void split_quads(ObjectRen *obr, int dir)
+{
+ VlakRen *vlr, *vlr1;
+ int a;
+
+ for(a=obr->totvlak-1; a>=0; a--) {
+ vlr= RE_findOrAddVlak(obr, a);
+
+ /* test if rendering as a quad or triangle, skip wire */
+ if(vlr->v4 && (vlr->flag & R_STRAND)==0 && (vlr->mat->mode & MA_WIRE)==0) {
+
+ if(vlr->v4) {
+
+ vlr1= RE_vlakren_copy(obr, vlr);
+ vlr1->flag |= R_FACE_SPLIT;
+
+ if( dir==2 ) vlr->flag |= R_DIVIDE_24;
+ else vlr->flag &= ~R_DIVIDE_24;
+
+ /* new vertex pointers */
+ if (vlr->flag & R_DIVIDE_24) {
+ vlr1->v1= vlr->v2;
+ vlr1->v2= vlr->v3;
+ vlr1->v3= vlr->v4;
+
+ vlr->v3 = vlr->v4;
+
+ vlr1->flag |= R_DIVIDE_24;
+ }
+ else {
+ vlr1->v1= vlr->v1;
+ vlr1->v2= vlr->v3;
+ vlr1->v3= vlr->v4;
+
+ vlr1->flag &= ~R_DIVIDE_24;
+ }
+ vlr->v4 = vlr1->v4 = NULL;
+
+ /* new normals */
+ CalcNormFloat(vlr->v3->co, vlr->v2->co, vlr->v1->co, vlr->n);
+ CalcNormFloat(vlr1->v3->co, vlr1->v2->co, vlr1->v1->co, vlr1->n);
+ }
+ /* clear the flag when not divided */
+ else vlr->flag &= ~R_DIVIDE_24;
+ }
+ }
+}
+
static void check_non_flat_quads(ObjectRen *obr)
{
VlakRen *vlr, *vlr1;
@@ -3767,6 +3980,7 @@ static void check_non_flat_quads(ObjectRen *obr)
xn= nor[0]*vlr->n[0] + nor[1]*vlr->n[1] + nor[2]*vlr->n[2];
if(ABS(xn) < 0.999995 ) { // checked on noisy fractal grid
+
float d1, d2;
vlr1= RE_vlakren_copy(obr, vlr);
@@ -3778,10 +3992,10 @@ static void check_non_flat_quads(ObjectRen *obr)
CalcNormFloat(vlr->v2->co, vlr->v3->co, vlr->v4->co, nor);
d2= nor[0]*vlr->v2->n[0] + nor[1]*vlr->v2->n[1] + nor[2]*vlr->v2->n[2];
-
+
if( fabs(d1) < fabs(d2) ) vlr->flag |= R_DIVIDE_24;
else vlr->flag &= ~R_DIVIDE_24;
-
+
/* new vertex pointers */
if (vlr->flag & R_DIVIDE_24) {
vlr1->v1= vlr->v2;
@@ -3812,26 +4026,67 @@ static void check_non_flat_quads(ObjectRen *obr)
}
}
-static void finalize_render_object(Render *re, ObjectRen *obr, int only_verts)
+static void finalize_render_object(Render *re, ObjectRen *obr, int timeoffset)
{
Object *ob= obr->ob;
+ VertRen *ver= NULL;
+ StrandRen *strand= NULL;
+ StrandBound *sbound= NULL;
+ float min[3], max[3], smin[3], smax[3];
+ int a, b;
if(obr->totvert || obr->totvlak || obr->tothalo || obr->totstrand) {
/* the exception below is because displace code now is in init_render_mesh call,
I will look at means to have autosmooth enabled for all object types
and have it as general postprocess, like displace */
if(ob->type!=OB_MESH && test_for_displace(re, ob))
- do_displacement(re, obr);
+ do_displacement(re, obr, NULL, NULL);
- if(!only_verts) {
+ if(!timeoffset) {
/* phong normal interpolation can cause error in tracing
* (terminator problem) */
ob->smoothresh= 0.0;
if((re->r.mode & R_RAYTRACE) && (re->r.mode & R_SHADOW))
set_phong_threshold(obr);
-
- check_non_flat_quads(obr);
+
+ if (re->flag & R_BAKING && re->r.bake_quad_split != 0) {
+ /* Baking lets us define a quad split order */
+ split_quads(obr, re->r.bake_quad_split);
+ } else {
+ check_non_flat_quads(obr);
+ }
+
set_fullsample_flag(re, obr);
+
+ /* compute bounding boxes for clipping */
+ INIT_MINMAX(min, max);
+ for(a=0; a<obr->totvert; a++) {
+ if((a & 255)==0) ver= obr->vertnodes[a>>8].vert;
+ else ver++;
+
+ DO_MINMAX(ver->co, min, max);
+ }
+
+ if(obr->strandbuf) {
+ sbound= obr->strandbuf->bound;
+ for(b=0; b<obr->strandbuf->totbound; b++, sbound++) {
+ INIT_MINMAX(smin, smax);
+
+ for(a=sbound->start; a<sbound->end; a++) {
+ strand= RE_findOrAddStrand(obr, a);
+ strand_minmax(strand, smin, smax);
+ }
+
+ VECCOPY(sbound->boundbox[0], smin);
+ VECCOPY(sbound->boundbox[1], smax);
+
+ DO_MINMAX(smin, min, max);
+ DO_MINMAX(smax, min, max);
+ }
+ }
+
+ VECCOPY(obr->boundbox[0], min);
+ VECCOPY(obr->boundbox[1], max);
}
}
}
@@ -3845,7 +4100,128 @@ static int render_object_type(int type)
return ELEM5(type, OB_FONT, OB_CURVE, OB_SURF, OB_MESH, OB_MBALL);
}
-static void init_render_object_data(Render *re, ObjectRen *obr, int only_verts)
+static void find_dupli_instances(Render *re, ObjectRen *obr)
+{
+ ObjectInstanceRen *obi;
+ float imat[4][4], obmat[4][4], obimat[4][4], nmat[3][3];
+ int first = 1;
+
+ Mat4MulMat4(obmat, obr->obmat, re->viewmat);
+ Mat4Invert(imat, obmat);
+
+ /* for objects instanced by dupliverts/faces/particles, we go over the
+ * list of instances to find ones that instance obr, and setup their
+ * matrices and obr pointer */
+ for(obi=re->instancetable.last; obi; obi=obi->prev) {
+ if(!obi->obr && obi->ob == obr->ob && obi->psysindex == obr->psysindex) {
+ obi->obr= obr;
+
+ /* compute difference between object matrix and
+ * object matrix with dupli transform, in viewspace */
+ Mat4CpyMat4(obimat, obi->mat);
+ Mat4MulMat4(obi->mat, imat, obimat);
+
+ Mat3CpyMat4(nmat, obi->mat);
+ Mat3Inv(obi->nmat, nmat);
+ Mat3Transp(obi->nmat);
+
+ if(!first) {
+ re->totvert += obr->totvert;
+ re->totvlak += obr->totvlak;
+ re->tothalo += obr->tothalo;
+ re->totstrand += obr->totstrand;
+ }
+ else
+ first= 0;
+ }
+ }
+}
+
+static void assign_dupligroup_dupli(Render *re, ObjectInstanceRen *obi, ObjectRen *obr)
+{
+ float imat[4][4], obmat[4][4], obimat[4][4], nmat[3][3];
+
+ Mat4MulMat4(obmat, obr->obmat, re->viewmat);
+ Mat4Invert(imat, obmat);
+
+ obi->obr= obr;
+
+ /* compute difference between object matrix and
+ * object matrix with dupli transform, in viewspace */
+ Mat4CpyMat4(obimat, obi->mat);
+ Mat4MulMat4(obi->mat, imat, obimat);
+
+ Mat3CpyMat4(nmat, obi->mat);
+ Mat3Inv(obi->nmat, nmat);
+ Mat3Transp(obi->nmat);
+
+ re->totvert += obr->totvert;
+ re->totvlak += obr->totvlak;
+ re->tothalo += obr->tothalo;
+ re->totstrand += obr->totstrand;
+}
+
+static ObjectRen *find_dupligroup_dupli(Render *re, Object *ob, int psysindex)
+{
+ ObjectRen *obr;
+
+ /* if the object is itself instanced, we don't want to create an instance
+ * for it */
+ if(ob->transflag & OB_RENDER_DUPLI)
+ return NULL;
+
+ /* try to find an object that was already created so we can reuse it
+ * and save memory */
+ for(obr=re->objecttable.first; obr; obr=obr->next)
+ if(obr->ob == ob && obr->psysindex == psysindex && (obr->flag & R_INSTANCEABLE))
+ return obr;
+
+ return NULL;
+}
+
+static void set_dupli_tex_mat(Render *re, ObjectInstanceRen *obi, DupliObject *dob)
+{
+ /* For duplis we need to have a matrix that transform the coordinate back
+ * to it's original position, without the dupli transforms. We also check
+ * the matrix is actually needed, to save memory on lots of dupliverts for
+ * example */
+ static Object *lastob= NULL;
+ static int needtexmat= 0;
+
+ /* init */
+ if(!re) {
+ lastob= NULL;
+ needtexmat= 0;
+ return;
+ }
+
+ /* check if we actually need it */
+ if(lastob != dob->ob) {
+ Material ***material;
+ short a, *totmaterial;
+
+ lastob= dob->ob;
+ needtexmat= 0;
+
+ totmaterial= give_totcolp(dob->ob);
+ material= give_matarar(dob->ob);
+
+ if(totmaterial && material)
+ for(a= 0; a<*totmaterial; a++)
+ if((*material)[a] && (*material)[a]->texco & TEXCO_OBJECT)
+ needtexmat= 1;
+ }
+
+ if(needtexmat) {
+ float imat[4][4];
+
+ obi->duplitexmat= BLI_memarena_alloc(re->memArena, sizeof(float)*4*4);
+ Mat4Invert(imat, dob->mat);
+ MTC_Mat4MulSerie(obi->duplitexmat, re->viewmat, dob->omat, imat, re->viewinv, 0, 0, 0, 0);
+ }
+}
+
+static void init_render_object_data(Render *re, ObjectRen *obr, int timeoffset)
{
Object *ob= obr->ob;
ParticleSystem *psys;
@@ -3863,20 +4239,20 @@ static void init_render_object_data(Render *re, ObjectRen *obr, int only_verts)
for(psys=ob->particlesystem.first, i=0; i<obr->psysindex-1; i++)
psys= psys->next;
- render_new_particle_system(re, obr, psys);
+ render_new_particle_system(re, obr, psys, timeoffset);
}
else {
if ELEM(ob->type, OB_FONT, OB_CURVE)
- init_render_curve(re, obr, only_verts);
+ init_render_curve(re, obr, timeoffset);
else if(ob->type==OB_SURF)
init_render_surf(re, obr);
else if(ob->type==OB_MESH)
- init_render_mesh(re, obr, only_verts);
+ init_render_mesh(re, obr, timeoffset);
else if(ob->type==OB_MBALL)
init_render_mball(re, obr);
}
- finalize_render_object(re, obr, only_verts);
+ finalize_render_object(re, obr, timeoffset);
re->totvert += obr->totvert;
re->totvlak += obr->totvlak;
@@ -3884,11 +4260,14 @@ static void init_render_object_data(Render *re, ObjectRen *obr, int only_verts)
re->totstrand += obr->totstrand;
}
-static void add_render_object(Render *re, Object *ob, Object *par, int index, int only_verts)
+static void add_render_object(Render *re, Object *ob, Object *par, DupliObject *dob, int timeoffset, int vectorlay)
{
ObjectRen *obr;
+ ObjectInstanceRen *obi;
ParticleSystem *psys;
- int show_emitter, allow_render= 1, psysindex;
+ int show_emitter, allow_render= 1, index, psysindex;
+
+ index= (dob)? dob->index: 0;
/* the emitter has to be processed first (render levels of modifiers) */
/* so here we only check if the emitter should be rendered */
@@ -3896,7 +4275,7 @@ static void add_render_object(Render *re, Object *ob, Object *par, int index, in
show_emitter= 0;
for(psys=ob->particlesystem.first; psys; psys=psys->next) {
show_emitter += psys->part->draw & PART_DRAW_EMITTER;
- psys_render_set(ob, psys, re->viewmat, re->winmat, re->winx, re->winy);
+ psys_render_set(ob, psys, re->viewmat, re->winmat, re->winx, re->winy, timeoffset);
}
/* if no psys has "show emitter" selected don't render emitter */
@@ -3906,32 +4285,52 @@ static void add_render_object(Render *re, Object *ob, Object *par, int index, in
/* one render object for the data itself */
if(allow_render) {
- obr= RE_addRenderObject(re, ob, par, index, 0);
- init_render_object_data(re, obr, only_verts);
+ obr= RE_addRenderObject(re, ob, par, index, 0, ob->lay);
+ if((dob && !dob->animated) || (ob->transflag & OB_RENDER_DUPLI)) {
+ obr->flag |= R_INSTANCEABLE;
+ Mat4CpyMat4(obr->obmat, ob->obmat);
+ }
+ if(obr->lay & vectorlay)
+ obr->flag |= R_NEED_VECTORS;
+ init_render_object_data(re, obr, timeoffset);
/* only add instance for objects that have not been used for dupli */
- if(!(ob->transflag & OB_RENDER_DUPLI))
- RE_addRenderInstance(re, obr, ob, par, index, 0, NULL);
+ if(!(ob->transflag & OB_RENDER_DUPLI)) {
+ obi= RE_addRenderInstance(re, obr, ob, par, index, 0, NULL, ob->lay);
+ if(dob) set_dupli_tex_mat(re, obi, dob);
+ }
+ else
+ find_dupli_instances(re, obr);
}
/* and one render object per particle system */
if(ob->particlesystem.first) {
psysindex= 1;
for(psys=ob->particlesystem.first; psys; psys=psys->next, psysindex++) {
- obr= RE_addRenderObject(re, ob, par, index, psysindex);
- init_render_object_data(re, obr, only_verts);
+ obr= RE_addRenderObject(re, ob, par, index, psysindex, ob->lay);
+ if((dob && !dob->animated) || (ob->transflag & OB_RENDER_DUPLI)) {
+ obr->flag |= R_INSTANCEABLE;
+ Mat4CpyMat4(obr->obmat, ob->obmat);
+ }
+ if(obr->lay & vectorlay)
+ obr->flag |= R_NEED_VECTORS;
+ init_render_object_data(re, obr, timeoffset);
psys_render_restore(ob, psys);
/* only add instance for objects that have not been used for dupli */
- if(!(ob->transflag & OB_RENDER_DUPLI))
- RE_addRenderInstance(re, obr, ob, par, index, psysindex, NULL);
+ if(!(ob->transflag & OB_RENDER_DUPLI)) {
+ obi= RE_addRenderInstance(re, obr, ob, par, index, psysindex, NULL, ob->lay);
+ if(dob) set_dupli_tex_mat(re, obi, dob);
+ }
+ else
+ find_dupli_instances(re, obr);
}
}
}
/* par = pointer to duplicator parent, needed for object lookup table */
/* index = when duplicater copies same object (particle), the counter */
-static void init_render_object(Render *re, Object *ob, Object *par, int index, int only_verts)
+static void init_render_object(Render *re, Object *ob, Object *par, DupliObject *dob, int timeoffset, int vectorlay)
{
static double lasttime= 0.0;
double time;
@@ -3940,7 +4339,7 @@ static void init_render_object(Render *re, Object *ob, Object *par, int index, i
if(ob->type==OB_LAMP)
add_render_lamp(re, ob);
else if(render_object_type(ob->type))
- add_render_object(re, ob, par, index, only_verts);
+ add_render_object(re, ob, par, dob, timeoffset, vectorlay);
else {
MTC_Mat4MulMat4(mat, ob->obmat, re->viewmat);
MTC_Mat4Invert(ob->imat, mat);
@@ -3965,6 +4364,14 @@ void RE_Database_Free(Render *re)
{
Object *ob = NULL;
LampRen *lar;
+
+ /* statistics for debugging render memory usage */
+ if((G.f & G_DEBUG) && (G.rendering)) {
+ if((re->r.scemode & R_PREVIEWBUTS)==0) {
+ BKE_image_print_memlist();
+ MEM_printmemlist_stats();
+ }
+ }
/* FREE */
@@ -3972,7 +4379,7 @@ void RE_Database_Free(Render *re)
freeshadowbuf(lar);
if(lar->jitter) MEM_freeN(lar->jitter);
if(lar->shadsamp) MEM_freeN(lar->shadsamp);
- if(lar->qsa) free_lamp_qmcsampler(lar);
+ if(lar->sunsky) MEM_freeN(lar->sunsky);
curvemapping_free(lar->curfalloff);
}
@@ -4010,13 +4417,14 @@ void RE_Database_Free(Render *re)
re->wrld.aotables= NULL;
re->scene->world->aotables= NULL;
}
- if((re->r.mode & R_RAYTRACE) && (re->wrld.mode & WO_AMB_OCC) &&
- (re->wrld.ao_samp_method == WO_AOSAMP_HAMMERSLEY) && (re->qsa))
+ if(re->r.mode & R_RAYTRACE)
free_render_qmcsampler(re);
if(re->r.mode & R_RAYTRACE) freeraytree(re);
free_sss(re);
+ free_occ(re);
+ free_strand_surface(re);
re->totvlak=re->totvert=re->totstrand=re->totlamp=re->tothalo= 0;
re->i.convertdone= 0;
@@ -4045,16 +4453,15 @@ static int allow_render_object(Object *ob, int nolamps, int onlyselected, Object
for(psys=ob->particlesystem.first; psys; psys=psys->next){
part=psys->part;
- if((part->draw_as==PART_DRAW_OB && part->dup_ob) || (part->draw_as==PART_DRAW_GR && part->dup_group))
- if(part->draw & PART_DRAW_EMITTER)
- allow= 1;
+ if(part->draw & PART_DRAW_EMITTER)
+ allow= 1;
}
}
if(!allow)
return 0;
}
- else if(ob->transflag & OB_DUPLI)
+ else if((ob->transflag & OB_DUPLI) && !(ob->transflag & OB_DUPLIFRAMES))
return 0;
if(nolamps && (ob->type==OB_LAMP))
@@ -4066,19 +4473,128 @@ static int allow_render_object(Object *ob, int nolamps, int onlyselected, Object
return 1;
}
-static int allow_render_dupli_instance(Render *re, Object *ob, Object *obd)
+static int allow_render_dupli_instance(Render *re, DupliObject *dob, Object *obd)
{
+ ParticleSystem *psys;
+ Material *ma;
+ short a, *totmaterial;
+
+ /* don't allow objects with halos. we need to have
+ * all halo's to sort them globally in advance */
+ totmaterial= give_totcolp(obd);
+
+ if(totmaterial) {
+ for(a= 0; a<*totmaterial; a++) {
+ ma= give_current_material(obd, a);
+ if(ma && (ma->mode & MA_HALO))
+ return 0;
+ }
+ }
+
+ for(psys=obd->particlesystem.first; psys; psys=psys->next)
+ if(!ELEM5(psys->part->draw_as, PART_DRAW_BB, PART_DRAW_LINE, PART_DRAW_PATH, PART_DRAW_OB, PART_DRAW_GR))
+ return 0;
+
+ /* don't allow lamp, animated duplis, or radio render */
return (render_object_type(obd->type) &&
- (!(ob->transflag & OB_DUPLIGROUP)) &&
+ (!(dob->type == OB_DUPLIGROUP) || !dob->animated) &&
!(re->r.mode & R_RADIO));
}
-static void database_init_objects(Render *re, unsigned int lay, int nolamps, int onlyselected, Object *actob, int only_verts)
+static void dupli_render_particle_set(Render *re, Object *ob, int timeoffset, int level, int enable)
+{
+ /* ugly function, but we need to set particle systems to their render
+ * settings before calling object_duplilist, to get render level duplis */
+ Group *group;
+ GroupObject *go;
+ ParticleSystem *psys;
+ DerivedMesh *dm;
+
+ if(level >= MAX_DUPLI_RECUR)
+ return;
+
+ if(ob->transflag & OB_DUPLIPARTS) {
+ for(psys=ob->particlesystem.first; psys; psys=psys->next) {
+ if(ELEM(psys->part->draw_as, PART_DRAW_OB, PART_DRAW_GR)) {
+ if(enable)
+ psys_render_set(ob, psys, re->viewmat, re->winmat, re->winx, re->winy, timeoffset);
+ else
+ psys_render_restore(ob, psys);
+ }
+ }
+
+ if(level == 0 && enable) {
+ /* this is to make sure we get render level duplis in groups:
+ * the derivedmesh must be created before init_render_mesh,
+ * since object_duplilist does dupliparticles before that */
+ dm = mesh_create_derived_render(ob, CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL);
+ dm->release(dm);
+
+ for(psys=ob->particlesystem.first; psys; psys=psys->next)
+ psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated;
+ }
+ }
+
+ if(ob->dup_group==NULL) return;
+ group= ob->dup_group;
+
+ for(go= group->gobject.first; go; go= go->next)
+ dupli_render_particle_set(re, go->ob, timeoffset, level+1, enable);
+}
+
+static int get_vector_renderlayers(Scene *sce)
+{
+ SceneRenderLayer *srl;
+ int lay= 0;
+
+ for(srl= sce->r.layers.first; srl; srl= srl->next)
+ if(srl->passflag & SCE_PASS_VECTOR)
+ lay |= srl->lay;
+
+ return lay;
+}
+
+static void add_group_render_dupli_obs(Render *re, Group *group, int nolamps, int onlyselected, Object *actob, int timeoffset, int vectorlay, int level)
+{
+ GroupObject *go;
+ Object *ob;
+
+ /* simple preventing of too deep nested groups */
+ if(level>MAX_DUPLI_RECUR) return;
+
+ /* recursively go into dupligroups to find objects with OB_RENDER_DUPLI
+ * that were not created yet */
+ for(go= group->gobject.first; go; go= go->next) {
+ ob= go->ob;
+
+ if(ob->flag & OB_DONE) {
+ if(ob->transflag & OB_RENDER_DUPLI) {
+ if(allow_render_object(ob, nolamps, onlyselected, actob)) {
+ init_render_object(re, ob, NULL, 0, timeoffset, vectorlay);
+ ob->transflag &= ~OB_RENDER_DUPLI;
+
+ if(ob->dup_group)
+ add_group_render_dupli_obs(re, ob->dup_group, nolamps, onlyselected, actob, timeoffset, vectorlay, level+1);
+ }
+ }
+ }
+ }
+}
+
+static void database_init_objects(Render *re, unsigned int renderlay, int nolamps, int onlyselected, Object *actob, int timeoffset)
{
Base *base;
Object *ob;
+ Group *group;
+ ObjectInstanceRen *obi;
Scene *sce;
float mat[4][4];
+ int lay, vectorlay, redoimat= 0;
+
+ /* for duplis we need the Object texture mapping to work as if
+ * untransformed, set_dupli_tex_mat sets the matrix to allow that
+ * NULL is just for init */
+ set_dupli_tex_mat(NULL, NULL, NULL);
for(SETLOOPER(re->scene, base)) {
ob= base->object;
@@ -4092,76 +4608,149 @@ static void database_init_objects(Render *re, unsigned int lay, int nolamps, int
for(SETLOOPER(re->scene, base)) {
ob= base->object;
-
+
+ /* in the prev/next pass for making speed vectors, avoid creating
+ * objects that are not on a renderlayer with a vector pass, can
+ * save a lot of time in complex scenes */
+ vectorlay= get_vector_renderlayers(sce);
+ lay= (timeoffset)? renderlay & vectorlay: renderlay;
+
/* if the object has been restricted from rendering in the outliner, ignore it */
if(ob->restrictflag & OB_RESTRICT_RENDER) continue;
/* OB_DONE means the object itself got duplicated, so was already converted */
if(ob->flag & OB_DONE) {
- if(ob->transflag & OB_RENDER_DUPLI)
- if(allow_render_object(ob, nolamps, onlyselected, actob))
- init_render_object(re, ob, NULL, 0, only_verts);
+ /* OB_RENDER_DUPLI means instances for it were already created, now
+ * it still needs to create the ObjectRen containing the data */
+ if(ob->transflag & OB_RENDER_DUPLI) {
+ if(allow_render_object(ob, nolamps, onlyselected, actob)) {
+ init_render_object(re, ob, NULL, 0, timeoffset, vectorlay);
+ ob->transflag &= ~OB_RENDER_DUPLI;
+ }
+ }
}
else if((base->lay & lay) || (ob->type==OB_LAMP && (base->lay & re->scene->lay)) ) {
if((ob->transflag & OB_DUPLI) && (ob->type!=OB_MBALL)) {
DupliObject *dob;
ListBase *lb;
+ redoimat= 1;
+
+ /* create list of duplis generated by this object, particle
+ * system need to have render settings set for dupli particles */
+ dupli_render_particle_set(re, ob, timeoffset, 0, 1);
lb= object_duplilist(sce, ob);
+ dupli_render_particle_set(re, ob, timeoffset, 0, 0);
+
for(dob= lb->first; dob; dob= dob->next) {
Object *obd= dob->ob;
Mat4CpyMat4(obd->obmat, dob->mat);
/* group duplis need to set ob matrices correct, for deform. so no_draw is part handled */
- if(dob->no_draw)
+ if(!(obd->transflag & OB_RENDER_DUPLI) && dob->no_draw)
continue;
if(obd->restrictflag & OB_RESTRICT_RENDER)
continue;
-
+
if(obd->type==OB_MBALL)
continue;
if(!allow_render_object(obd, nolamps, onlyselected, actob))
continue;
- if(allow_render_dupli_instance(re, ob, obd)) {
+ if(allow_render_dupli_instance(re, dob, obd)) {
ParticleSystem *psys;
+ ObjectRen *obr = NULL;
int psysindex;
- float imat[4][4], mat[4][4];
-
- /* compute difference between object matrix and
- * object matrix with dupli transform, in viewspace */
- Mat4Invert(imat, dob->omat);
- MTC_Mat4MulSerie(mat, re->viewmat, dob->mat, imat, re->viewinv, 0, 0, 0, 0);
-
- RE_addRenderInstance(re, NULL, obd, ob, dob->index, 0, mat);
+ float mat[4][4];
+
+ /* instances instead of the actual object are added in two cases, either
+ * this is a duplivert/face/particle, or it is a non-animated object in
+ * a dupligroup that has already been created before */
+ if(dob->type != OB_DUPLIGROUP || (obr=find_dupligroup_dupli(re, obd, 0))) {
+ Mat4MulMat4(mat, dob->mat, re->viewmat);
+ obi= RE_addRenderInstance(re, NULL, obd, ob, dob->index, 0, mat, obd->lay);
+
+ /* fill in instance variables for texturing */
+ set_dupli_tex_mat(re, obi, dob);
+ if(dob->type != OB_DUPLIGROUP) {
+ VECCOPY(obi->dupliorco, dob->orco);
+ obi->dupliuv[0]= dob->uv[0];
+ obi->dupliuv[1]= dob->uv[1];
+ }
+ else {
+ /* for the second case, setup instance to point to the already
+ * created object, and possibly setup instances if this object
+ * itself was duplicated. for the first case find_dupli_instances
+ * will be called later. */
+ assign_dupligroup_dupli(re, obi, obr);
+ if(obd->transflag & OB_RENDER_DUPLI)
+ find_dupli_instances(re, obr);
+ }
+ }
+ else
+ /* can't instance, just create the object */
+ init_render_object(re, obd, ob, dob, timeoffset, vectorlay);
+ /* same logic for particles, each particle system has it's own object, so
+ * need to go over them separately */
psysindex= 1;
- for(psys=obd->particlesystem.first; psys; psys=psys->next)
- RE_addRenderInstance(re, NULL, obd, ob, dob->index, psysindex++, mat);
+ for(psys=obd->particlesystem.first; psys; psys=psys->next) {
+ if(dob->type != OB_DUPLIGROUP || (obr=find_dupligroup_dupli(re, ob, psysindex))) {
+ obi= RE_addRenderInstance(re, NULL, obd, ob, dob->index, psysindex++, mat, obd->lay);
+
+ set_dupli_tex_mat(re, obi, dob);
+ if(dob->type != OB_DUPLIGROUP) {
+ VECCOPY(obi->dupliorco, dob->orco);
+ obi->dupliuv[0]= dob->uv[0];
+ obi->dupliuv[1]= dob->uv[1];
+ }
+ else {
+ assign_dupligroup_dupli(re, obi, obr);
+ if(obd->transflag & OB_RENDER_DUPLI)
+ find_dupli_instances(re, obr);
+ }
+ }
+ }
- obd->flag |= OB_DONE;
- obd->transflag |= OB_RENDER_DUPLI;
+ if(dob->type != OB_DUPLIGROUP) {
+ obd->flag |= OB_DONE;
+ obd->transflag |= OB_RENDER_DUPLI;
+ }
}
else
- init_render_object(re, obd, ob, dob->index, only_verts);
+ init_render_object(re, obd, ob, dob, timeoffset, vectorlay);
if(re->test_break()) break;
}
free_object_duplilist(lb);
if(allow_render_object(ob, nolamps, onlyselected, actob))
- init_render_object(re, ob, NULL, 0, only_verts);
+ init_render_object(re, ob, NULL, 0, timeoffset, vectorlay);
}
else if(allow_render_object(ob, nolamps, onlyselected, actob))
- init_render_object(re, ob, NULL, 0, only_verts);
+ init_render_object(re, ob, NULL, 0, timeoffset, vectorlay);
}
if(re->test_break()) break;
}
+ /* objects in groups with OB_RENDER_DUPLI set still need to be created,
+ * since they may not be part of the scene */
+ for(group= G.main->group.first; group; group=group->id.next)
+ add_group_render_dupli_obs(re, group, nolamps, onlyselected, actob, timeoffset, renderlay, 0);
+
+ /* imat objects has to be done again, since groups can mess it up */
+ if(redoimat) {
+ for(SETLOOPER(re->scene, base)) {
+ ob= base->object;
+ MTC_Mat4MulMat4(mat, ob->obmat, re->viewmat);
+ MTC_Mat4Invert(ob->imat, mat);
+ }
+ }
+
if(!re->test_break())
RE_makeRenderInstances(re);
}
@@ -4202,14 +4791,16 @@ void RE_Database_FromScene(Render *re, Scene *scene, int use_camera_view)
Mat4Ortho(re->scene->camera->obmat);
Mat4Invert(mat, re->scene->camera->obmat);
RE_SetView(re, mat);
+ re->scene->camera->recalc= OB_RECALC_OB; /* force correct matrix for scaled cameras */
}
init_render_world(re); /* do first, because of ambient. also requires re->osa set correct */
- if(re->wrld.mode & WO_AMB_OCC) {
- if (re->wrld.ao_samp_method == WO_AOSAMP_HAMMERSLEY)
- init_render_hammersley(re);
- else if (re->wrld.ao_samp_method == WO_AOSAMP_CONSTANT)
- init_ao_sphere(&re->wrld);
+ if(re->r.mode & R_RAYTRACE) {
+ init_render_qmcsampler(re);
+
+ if(re->wrld.mode & WO_AMB_OCC)
+ if (re->wrld.ao_samp_method == WO_AOSAMP_CONSTANT)
+ init_ao_sphere(&re->wrld);
}
/* still bad... doing all */
@@ -4270,10 +4861,17 @@ void RE_Database_FromScene(Render *re, Scene *scene, int use_camera_view)
if(!re->test_break())
project_renderdata(re, projectverto, re->r.mode & R_PANORAMA, 0, 1);
+
+ /* Occlusion */
+ if((re->wrld.mode & WO_AMB_OCC) && !re->test_break())
+ if(re->wrld.ao_gather_method == WO_AOGATHER_APPROX)
+ if(re->r.renderer==R_INTERN)
+ if(re->r.mode & R_SHADOW)
+ make_occ_tree(re);
/* SSS */
if((re->r.mode & R_SSS) && !re->test_break())
- if (re->r.renderer==R_INTERN)
+ if(re->r.renderer==R_INTERN)
make_sss_tree(re);
}
@@ -4334,7 +4932,7 @@ static void database_fromscene_vectors(Render *re, Scene *scene, int timeoffset)
}
/* MAKE RENDER DATA */
- database_init_objects(re, lay, 0, 0, 0, 1);
+ database_init_objects(re, lay, 0, 0, 0, timeoffset);
if(!re->test_break())
project_renderdata(re, projectverto, re->r.mode & R_PANORAMA, 0, 1);
@@ -4429,14 +5027,49 @@ static void calculate_speedvector(float *vectors, int step, float winsq, float w
}
}
+static float *calculate_strandsurface_speedvectors(Render *re, ObjectInstanceRen *obi, StrandSurface *mesh)
+{
+ float winsq= re->winx*re->winy, winroot= sqrt(winsq), (*winspeed)[4];
+ float ho[4], prevho[4], nextho[4], winmat[4][4], vec[2];
+ int a;
+
+ if(mesh->co && mesh->prevco && mesh->nextco) {
+ if(obi->flag & R_TRANSFORMED)
+ Mat4MulMat4(winmat, obi->mat, re->winmat);
+ else
+ Mat4CpyMat4(winmat, re->winmat);
+
+ winspeed= MEM_callocN(sizeof(float)*4*mesh->totvert, "StrandSurfWin");
+
+ for(a=0; a<mesh->totvert; a++) {
+ projectvert(mesh->co[a], winmat, ho);
+
+ projectvert(mesh->prevco[a], winmat, prevho);
+ speedvector_project(NULL, vec, mesh->prevco[a], prevho);
+ calculate_speedvector(vec, 0, winsq, winroot, mesh->co[a], ho, winspeed[a]);
+
+ projectvert(mesh->nextco[a], winmat, nextho);
+ speedvector_project(NULL, vec, mesh->nextco[a], nextho);
+ calculate_speedvector(vec, 1, winsq, winroot, mesh->co[a], ho, winspeed[a]);
+ }
+
+ return (float*)winspeed;
+ }
+
+ return NULL;
+}
+
static void calculate_speedvectors(Render *re, ObjectInstanceRen *obi, float *vectors, int step)
{
ObjectRen *obr= obi->obr;
VertRen *ver= NULL;
StrandRen *strand= NULL;
- float *speed, ho[4], winmat[4][4];
+ StrandBuffer *strandbuf;
+ StrandSurface *mesh= NULL;
+ float *speed, (*winspeed)[4]=NULL, ho[4], winmat[4][4];
+ float *co1, *co2, *co3, *co4, w[4];
float winsq= re->winx*re->winy, winroot= sqrt(winsq);
- int a;
+ int a, *face, *index;
if(obi->flag & R_TRANSFORMED)
Mat4MulMat4(winmat, obi->mat, re->winmat);
@@ -4455,13 +5088,42 @@ static void calculate_speedvectors(Render *re, ObjectInstanceRen *obi, float *ve
}
if(obr->strandnodes) {
- for(a=0; a<obr->totstrand; a++, vectors+=2) {
- if((a & 255)==0) strand= obr->strandnodes[a>>8].strand;
- else strand++;
+ strandbuf= obr->strandbuf;
+ mesh= (strandbuf)? strandbuf->surface: NULL;
+
+ /* compute speed vectors at surface vertices */
+ if(mesh)
+ winspeed= (float(*)[4])calculate_strandsurface_speedvectors(re, obi, mesh);
+
+ if(winspeed) {
+ for(a=0; a<obr->totstrand; a++, vectors+=2) {
+ if((a & 255)==0) strand= obr->strandnodes[a>>8].strand;
+ else strand++;
+
+ index= RE_strandren_get_face(obr, strand, 0);
+ if(index && *index < mesh->totface) {
+ speed= RE_strandren_get_winspeed(obi, strand, 1);
+
+ /* interpolate speed vectors from strand surface */
+ face= mesh->face[*index];
+
+ co1= mesh->co[face[0]];
+ co2= mesh->co[face[1]];
+ co3= mesh->co[face[2]];
+ co4= (face[3])? mesh->co[face[3]]: NULL;
+
+ InterpWeightsQ3Dfl(co1, co2, co3, co4, strand->vert->co, w);
+
+ speed[0]= speed[1]= speed[2]= speed[3]= 0.0f;
+ QUATADDFAC(speed, speed, winspeed[face[0]], w[0]);
+ QUATADDFAC(speed, speed, winspeed[face[1]], w[1]);
+ QUATADDFAC(speed, speed, winspeed[face[2]], w[2]);
+ if(face[3])
+ QUATADDFAC(speed, speed, winspeed[face[3]], w[3]);
+ }
+ }
- speed= RE_strandren_get_winspeed(obi, strand, 1);
- projectvert(strand->vert->co, winmat, ho);
- calculate_speedvector(vectors, step, winsq, winroot, strand->vert->co, ho, speed);
+ MEM_freeN(winspeed);
}
}
}
@@ -4471,36 +5133,54 @@ static int load_fluidsimspeedvectors(Render *re, ObjectInstanceRen *obi, float *
ObjectRen *obr= obi->obr;
Object *fsob= obr->ob;
VertRen *ver= NULL;
- float *speed, div, zco[2];
+ float *speed, div, zco[2], avgvel[4] = {0.0, 0.0, 0.0, 0.0};
float zmulx= re->winx/2, zmuly= re->winy/2, len;
float winsq= re->winx*re->winy, winroot= sqrt(winsq);
int a, j;
float hoco[4], ho[4], fsvec[4], camco[4];
float mat[4][4], winmat[4][4];
float imat[4][4];
- MVert *vverts;
-
+ FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(fsob, eModifierType_Fluidsim);
+ FluidsimSettings *fss = fluidmd->fss;
+ float *velarray = NULL;
+
/* only one step needed */
if(step) return 1;
+ if(fluidmd)
+ fss = fluidmd->fss;
+ else
+ return 0;
+
Mat4CpyMat4(mat, re->viewmat);
MTC_Mat4Invert(imat, mat);
/* set first vertex OK */
- if( (!fsob->fluidsimSettings) || (!fsob->fluidsimSettings->meshSurfNormals) ) return 0;
- vverts = fsob->fluidsimSettings->meshSurfNormals;
- //fprintf(stderr, "GZ_VEL obj '%s', calc load_fluidsimspeedvectors\n",fsob->id.name); // NT DEBUG
-
- if( obr->totvert != fsob->fluidsimSettings->meshSurface->totvert ) {
+ if(!fss->meshSurfNormals) return 0;
+
+ if( obr->totvert != GET_INT_FROM_POINTER(fss->meshSurface) ) {
//fprintf(stderr, "load_fluidsimspeedvectors - modified fluidsim mesh, not using speed vectors (%d,%d)...\n", obr->totvert, fsob->fluidsimSettings->meshSurface->totvert); // DEBUG
return 0;
}
+
+ velarray = (float *)fss->meshSurfNormals;
if(obi->flag & R_TRANSFORMED)
Mat4MulMat4(winmat, obi->mat, re->winmat);
else
Mat4CpyMat4(winmat, re->winmat);
+ /* (bad) HACK calculate average velocity */
+ /* better solution would be fixing getVelocityAt() in intern/elbeem/intern/solver_util.cpp
+ so that also small drops/little water volumes return a velocity != 0.
+ But I had no luck in fixing that function - DG */
+ for(a=0; a<obr->totvert; a++) {
+ for(j=0;j<3;j++) avgvel[j] += velarray[3*a + j];
+
+ }
+ for(j=0;j<3;j++) avgvel[j] /= (float)(obr->totvert);
+
+
for(a=0; a<obr->totvert; a++, vectors+=2) {
if((a & 255)==0)
ver= obr->vertnodes[a>>8].vert;
@@ -4510,8 +5190,16 @@ static int load_fluidsimspeedvectors(Render *re, ObjectInstanceRen *obi, float *
// get fluid velocity
fsvec[3] = 0.;
//fsvec[0] = fsvec[1] = fsvec[2] = fsvec[3] = 0.; fsvec[2] = 2.; // NT fixed test
- for(j=0;j<3;j++) fsvec[j] = vverts[a].co[j];
-
+ for(j=0;j<3;j++) fsvec[j] = velarray[3*a + j];
+
+ /* (bad) HACK insert average velocity if none is there (see previous comment) */
+ if((fsvec[0] == 0.0) && (fsvec[1] == 0.0) && (fsvec[2] == 0.0))
+ {
+ fsvec[0] = avgvel[0];
+ fsvec[1] = avgvel[1];
+ fsvec[2] = avgvel[2];
+ }
+
// transform (=rotate) to cam space
camco[0]= imat[0][0]*fsvec[0] + imat[0][1]*fsvec[1] + imat[0][2]*fsvec[2];
camco[1]= imat[1][0]*fsvec[0] + imat[1][1]*fsvec[1] + imat[1][2]*fsvec[2];
@@ -4552,7 +5240,6 @@ static void copy_dbase_object_vectors(Render *re, ListBase *lb)
ObjectInstanceRen *obi, *obilb;
ObjectRen *obr;
VertRen *ver= NULL;
- StrandRen *strand= NULL;
float *vec, ho[4], winmat[4][4];
int a, totvector;
@@ -4563,7 +5250,7 @@ static void copy_dbase_object_vectors(Render *re, ListBase *lb)
memcpy(obilb, obi, sizeof(ObjectInstanceRen));
BLI_addtail(lb, obilb);
- obilb->totvector= totvector= obr->totvert + obr->totstrand;
+ obilb->totvector= totvector= obr->totvert;
if(totvector > 0) {
vec= obilb->vectors= MEM_mallocN(2*sizeof(float)*totvector, "vector array");
@@ -4580,14 +5267,6 @@ static void copy_dbase_object_vectors(Render *re, ListBase *lb)
projectvert(ver->co, winmat, ho);
speedvector_project(NULL, vec, ver->co, ho);
}
-
- for(a=0; a<obr->totstrand; a++, vec+=2) {
- if((a & 255)==0) strand= obr->strandnodes[a>>8].strand;
- else strand++;
-
- projectvert(strand->vert->co, winmat, ho);
- speedvector_project(NULL, vec, strand->vert->co, ho);
- }
}
}
}
@@ -4605,8 +5284,10 @@ static void free_dbase_object_vectors(ListBase *lb)
void RE_Database_FromScene_Vectors(Render *re, Scene *sce)
{
ObjectInstanceRen *obi, *oldobi;
+ StrandSurface *mesh;
ListBase *table;
ListBase oldtable= {NULL, NULL}, newtable= {NULL, NULL};
+ ListBase strandsurface;
int step;
re->i.infostr= "Calculating previous vectors";
@@ -4621,7 +5302,10 @@ void RE_Database_FromScene_Vectors(Render *re, Scene *sce)
copy_dbase_object_vectors(re, &oldtable);
/* free dbase and make the future one */
+ strandsurface= re->strandsurface;
+ memset(&re->strandsurface, 0, sizeof(ListBase));
RE_Database_Free(re);
+ re->strandsurface= strandsurface;
if(!re->test_break()) {
/* creates entire dbase */
@@ -4633,7 +5317,10 @@ void RE_Database_FromScene_Vectors(Render *re, Scene *sce)
copy_dbase_object_vectors(re, &newtable);
/* free dbase and make the real one */
+ strandsurface= re->strandsurface;
+ memset(&re->strandsurface, 0, sizeof(ListBase));
RE_Database_Free(re);
+ re->strandsurface= strandsurface;
if(!re->test_break())
RE_Database_FromScene(re, sce, 1);
@@ -4647,10 +5334,14 @@ void RE_Database_FromScene_Vectors(Render *re, Scene *sce)
table= &oldtable;
oldobi= table->first;
- for(obi= re->instancetable.first; obi && oldobi; obi= obi->next, oldobi= oldobi->next) {
+ for(obi= re->instancetable.first; obi && oldobi; obi= obi->next) {
int ok= 1;
+ FluidsimModifierData *fluidmd;
+
+ if(!(obi->obr->flag & R_NEED_VECTORS))
+ continue;
- obi->totvector= obi->obr->totvert + obi->obr->totstrand;
+ obi->totvector= obi->obr->totvert;
/* find matching object in old table */
if(oldobi->ob!=obi->ob || oldobi->par!=obi->par || oldobi->index!=obi->index || oldobi->psysindex!=obi->psysindex) {
@@ -4669,25 +5360,38 @@ void RE_Database_FromScene_Vectors(Render *re, Scene *sce)
}
// NT check for fluidsim special treatment
- if((obi->ob->fluidsimFlag & OB_FLUIDSIM_ENABLE) && (obi->ob->fluidsimSettings->type & OB_FLUIDSIM_DOMAIN)) {
+ fluidmd = (FluidsimModifierData *)modifiers_findByType(obi->ob, eModifierType_Fluidsim);
+ if(fluidmd && fluidmd->fss && (fluidmd->fss->type & OB_FLUIDSIM_DOMAIN)) {
// use preloaded per vertex simulation data , only does calculation for step=1
// NOTE/FIXME - velocities and meshes loaded unnecessarily often during the database_fromscene_vectors calls...
load_fluidsimspeedvectors(re, obi, oldobi->vectors, step);
- } else {
+ }
+ else {
/* check if both have same amounts of vertices */
- if(obi->totvector!=oldobi->totvector) {
+ if(obi->totvector==oldobi->totvector)
+ calculate_speedvectors(re, obi, oldobi->vectors, step);
+ else
printf("Warning: object %s has different amount of vertices or strands on other frame\n", obi->ob->id.name+2);
- continue;
- }
-
- calculate_speedvectors(re, obi, oldobi->vectors, step);
} // not fluidsim
+
+ oldobi= oldobi->next;
}
}
}
free_dbase_object_vectors(&oldtable);
free_dbase_object_vectors(&newtable);
+
+ for(mesh=re->strandsurface.first; mesh; mesh=mesh->next) {
+ if(mesh->prevco) {
+ MEM_freeN(mesh->prevco);
+ mesh->prevco= NULL;
+ }
+ if(mesh->nextco) {
+ MEM_freeN(mesh->nextco);
+ mesh->nextco= NULL;
+ }
+ }
re->i.infostr= NULL;
re->stats_draw(&re->i);
@@ -4705,6 +5409,8 @@ void RE_Database_FromScene_Vectors(Render *re, Scene *sce)
RE_BAKE_NORMALS:for baking, no lamps and only selected objects
RE_BAKE_AO: for baking, no lamps, but all objects
RE_BAKE_TEXTURE:for baking, no lamps, only selected objects
+ RE_BAKE_DISPLACEMENT:for baking, no lamps, only selected objects
+ RE_BAKE_SHADOW: for baking, only shadows, but all objects
*/
void RE_Database_Baking(Render *re, Scene *scene, int type, Object *actob)
{
@@ -4716,21 +5422,31 @@ void RE_Database_Baking(Render *re, Scene *scene, int type, Object *actob)
/* renderdata setup and exceptions */
re->r= scene->r;
- re->r.mode &= ~R_OSA;
+
+ RE_init_threadcount(re);
+
re->flag |= R_GLOB_NOPUNOFLIP;
+ re->flag |= R_BAKING;
re->excludeob= actob;
+ if(type == RE_BAKE_LIGHT)
+ re->flag |= R_SKIP_MULTIRES;
+ if(actob)
+ re->flag |= R_BAKE_TRACE;
if(type==RE_BAKE_NORMALS && re->r.bake_normal_space==R_BAKE_SPACE_TANGENT)
re->flag |= R_NEED_TANGENT;
- if(!actob && ELEM3(type, RE_BAKE_LIGHT, RE_BAKE_NORMALS, RE_BAKE_TEXTURE)) {
+ if(!actob && ELEM4(type, RE_BAKE_LIGHT, RE_BAKE_NORMALS, RE_BAKE_TEXTURE, RE_BAKE_DISPLACEMENT)) {
re->r.mode &= ~R_SHADOW;
re->r.mode &= ~R_RAYTRACE;
}
+ if(!actob && (type==RE_BAKE_SHADOW)) {
+ re->r.mode |= R_SHADOW;
+ }
+
/* setup render stuff */
- if(type!=RE_BAKE_LIGHT)
- re->memArena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
+ re->memArena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
re->totvlak=re->totvert=re->totstrand=re->totlamp=re->tothalo= 0;
re->lights.first= re->lights.last= NULL;
@@ -4752,11 +5468,12 @@ void RE_Database_Baking(Render *re, Scene *scene, int type, Object *actob)
}
init_render_world(re); /* do first, because of ambient. also requires re->osa set correct */
- if(re->wrld.mode & WO_AMB_OCC) {
- if (re->wrld.ao_samp_method == WO_AOSAMP_HAMMERSLEY)
- init_render_hammersley(re);
- else if (re->wrld.ao_samp_method == WO_AOSAMP_CONSTANT)
- init_ao_sphere(&re->wrld);
+ if(re->r.mode & R_RAYTRACE) {
+ init_render_qmcsampler(re);
+
+ if(re->wrld.mode & WO_AMB_OCC)
+ if (re->wrld.ao_samp_method == WO_AOSAMP_CONSTANT)
+ init_ao_sphere(&re->wrld);
}
/* still bad... doing all */
@@ -4765,8 +5482,8 @@ void RE_Database_Baking(Render *re, Scene *scene, int type, Object *actob)
set_node_shader_lamp_loop(shade_material_loop);
/* MAKE RENDER DATA */
- nolamps= !ELEM(type, RE_BAKE_LIGHT, RE_BAKE_ALL);
- onlyselected= ELEM(type, RE_BAKE_NORMALS, RE_BAKE_TEXTURE);
+ nolamps= !ELEM3(type, RE_BAKE_LIGHT, RE_BAKE_ALL, RE_BAKE_SHADOW);
+ onlyselected= ELEM3(type, RE_BAKE_NORMALS, RE_BAKE_TEXTURE, RE_BAKE_DISPLACEMENT);
database_init_objects(re, lay, nolamps, onlyselected, actob, 0);
@@ -4781,6 +5498,12 @@ void RE_Database_Baking(Render *re, Scene *scene, int type, Object *actob)
if(!re->test_break())
if(re->r.mode & R_RAYTRACE)
makeraytree(re);
+
+ /* occlusion */
+ if((re->wrld.mode & WO_AMB_OCC) && !re->test_break())
+ if(re->wrld.ao_gather_method == WO_AOGATHER_APPROX)
+ if(re->r.mode & R_SHADOW)
+ make_occ_tree(re);
}
/* ------------------------------------------------------------------------- */
@@ -4813,7 +5536,7 @@ void RE_make_sticky(void)
}
re= RE_NewRender("_make sticky_");
- RE_InitState(re, &G.scene->r, G.scene->r.xsch, G.scene->r.ysch, NULL);
+ RE_InitState(re, NULL, &G.scene->r, G.scene->r.xsch, G.scene->r.ysch, NULL);
/* use renderdata and camera to set viewplane */
RE_SetCamera(re, G.scene->camera);
diff --git a/source/blender/render/intern/source/envmap.c b/source/blender/render/intern/source/envmap.c
index b1b907aebb6..13fa9b17b71 100644
--- a/source/blender/render/intern/source/envmap.c
+++ b/source/blender/render/intern/source/envmap.c
@@ -127,7 +127,7 @@ static Render *envmap_render_copy(Render *re, EnvMap *env)
envre->r.size= 100;
envre->r.yasp= envre->r.xasp= 1;
- RE_InitState(envre, &envre->r, cuberes, cuberes, NULL);
+ RE_InitState(envre, NULL, &envre->r, cuberes, cuberes, NULL);
envre->scene= re->scene; /* unsure about this... */
/* view stuff in env render */
@@ -150,14 +150,15 @@ static Render *envmap_render_copy(Render *re, EnvMap *env)
envre->tothalo= re->tothalo;
envre->totstrand= re->totstrand;
envre->totlamp= re->totlamp;
+ envre->sortedhalos= re->sortedhalos;
envre->lights= re->lights;
envre->objecttable= re->objecttable;
- envre->strandbuckets= re->strandbuckets;
envre->customdata_names= re->customdata_names;
envre->raytree= re->raytree;
envre->totinstance= re->totinstance;
envre->instancetable= re->instancetable;
envre->objectinstance= re->objectinstance;
+ envre->qmcsamplers= re->qmcsamplers;
return envre;
}
@@ -171,13 +172,14 @@ static void envmap_free_render_copy(Render *envre)
envre->totstrand= 0;
envre->totlamp= 0;
envre->totinstance= 0;
+ envre->sortedhalos= NULL;
envre->lights.first= envre->lights.last= NULL;
envre->objecttable.first= envre->objecttable.last= NULL;
- envre->strandbuckets= NULL;
envre->customdata_names.first= envre->customdata_names.last= NULL;
envre->raytree= NULL;
envre->instancetable.first= envre->instancetable.last= NULL;
envre->objectinstance= NULL;
+ envre->qmcsamplers= NULL;
RE_FreeRender(envre);
}
@@ -223,7 +225,7 @@ static void env_rotate_scene(Render *re, float mat[][4], int mode)
ObjectInstanceRen *obi;
LampRen *lar = NULL;
HaloRen *har = NULL;
- float imat[3][3], pmat[4][4], smat[4][4], tmat[4][4], cmat[3][3];
+ float imat[3][3], pmat[4][4], smat[4][4], tmat[4][4], cmat[3][3], tmpmat[4][4];
int a;
if(mode==0) {
@@ -237,15 +239,18 @@ static void env_rotate_scene(Render *re, float mat[][4], int mode)
for(obi=re->instancetable.first; obi; obi=obi->next) {
/* append or set matrix depending on dupli */
- if(obi->flag & R_DUPLI_TRANSFORMED)
- Mat4MulMat4(obi->mat, tmat, obi->mat);
+ if(obi->flag & R_DUPLI_TRANSFORMED) {
+ Mat4CpyMat4(tmpmat, obi->mat);
+ Mat4MulMat4(obi->mat, tmpmat, tmat);
+ }
else if(mode==1)
Mat4CpyMat4(obi->mat, tmat);
else
Mat4One(obi->mat);
Mat3CpyMat4(cmat, obi->mat);
- Mat3Inv(obi->imat, cmat);
+ Mat3Inv(obi->nmat, cmat);
+ Mat3Transp(obi->nmat);
/* indicate the renderer has to use transform matrices */
if(mode==0)
@@ -313,12 +318,13 @@ static void env_layerflags(Render *re, unsigned int notlay)
notlay= ~notlay;
for(obr=re->objecttable.first; obr; obr=obr->next) {
- for(a=0; a<obr->totvlak; a++) {
- if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak;
- else vlr++;
+ if((obr->lay & notlay)==0) {
+ for(a=0; a<obr->totvlak; a++) {
+ if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak;
+ else vlr++;
- if((vlr->lay & notlay)==0)
vlr->flag |= R_HIDDEN;
+ }
}
}
}
@@ -433,12 +439,19 @@ static void render_envmap(Render *re, EnvMap *env)
if(re->test_break()==0) {
RenderLayer *rl= envre->result->layers.first;
+ int y;
+ char *alpha;
ibuf= IMB_allocImBuf(envre->rectx, envre->recty, 24, IB_rect, 0);
ibuf->rect_float= rl->rectf;
IMB_rect_from_float(ibuf);
ibuf->rect_float= NULL;
-
+
+ /* envmap renders without alpha */
+ alpha= ((char *)ibuf->rect)+3;
+ for(y= ibuf->x*ibuf->y - 1; y>=0; y--, alpha+=4)
+ *alpha= 255;
+
env->cube[part]= ibuf;
}
@@ -715,7 +728,7 @@ int envmaptex(Tex *tex, float *texvec, float *dxt, float *dyt, int osatex, TexRe
fac= (texres->ta+texr1.ta+texr2.ta);
if(fac!=0.0) {
fac= 1.0/fac;
-
+
texres->tr= fac*(texres->ta*texres->tr + texr1.ta*texr1.tr + texr2.ta*texr2.tr );
texres->tg= fac*(texres->ta*texres->tg + texr1.ta*texr1.tg + texr2.ta*texr2.tg );
texres->tb= fac*(texres->ta*texres->tb + texr1.ta*texr1.tb + texr2.ta*texr2.tb );
diff --git a/source/blender/render/intern/source/imagetexture.c b/source/blender/render/intern/source/imagetexture.c
index 23b5e597070..b9a2acb8b1c 100644
--- a/source/blender/render/intern/source/imagetexture.c
+++ b/source/blender/render/intern/source/imagetexture.c
@@ -32,6 +32,7 @@
#include <string.h>
#include <fcntl.h>
#include <math.h>
+#include <float.h>
#ifndef WIN32
#include <unistd.h>
#else
@@ -93,10 +94,10 @@ static void ibuf_get_color(float *col, struct ImBuf *ibuf, int x, int y)
else {
char *rect = (char *)( ibuf->rect+ ofs);
- col[0] = ((float)rect[0])/255.0f;
- col[1] = ((float)rect[1])/255.0f;
- col[2] = ((float)rect[2])/255.0f;
- col[3] = ((float)rect[3])/255.0f;
+ col[0] = ((float)rect[0])*(1.0f/255.0f);
+ col[1] = ((float)rect[1])*(1.0f/255.0f);
+ col[2] = ((float)rect[2])*(1.0f/255.0f);
+ col[3] = ((float)rect[3])*(1.0f/255.0f);
}
}
@@ -245,7 +246,7 @@ int imagewrap(Tex *tex, Image *ima, ImBuf *ibuf, float *texvec, TexResult *texre
if(tex->flag & TEX_NEGALPHA) texres->ta= 1.0f-texres->ta;
/* de-premul, this is being premulled in shade_input_do_shade() */
- if(texres->ta!=1.0f && texres->ta!=0.0f) {
+ if(texres->ta!=1.0f && texres->ta>FLT_EPSILON) {
fx= 1.0f/texres->ta;
texres->tr*= fx;
texres->tg*= fx;
@@ -576,10 +577,10 @@ static void boxsample(ImBuf *ibuf, float minx, float miny, float maxx, float max
if(texres->talpha==0) texres->ta= 1.0;
if(alphaclip!=1.0) {
- /* this is for later investigation, premul or not? */
- /* texres->tr*= alphaclip; */
- /* texres->tg*= alphaclip; */
- /* texres->tb*= alphaclip; */
+ /* premul it all */
+ texres->tr*= alphaclip;
+ texres->tg*= alphaclip;
+ texres->tb*= alphaclip;
texres->ta*= alphaclip;
}
}
@@ -615,6 +616,7 @@ void ibuf_sample(ImBuf *ibuf, float fx, float fy, float dx, float dy, float *res
return;
}
+ memset(&texres, 0, sizeof(texres));
boxsample(ibuf, fx, fy, fx+dx, fy+dy, &texres, 0, 1);
result[0]= texres.tr;
result[1]= texres.tg;
@@ -699,10 +701,22 @@ int imagewraposa(Tex *tex, Image *ima, ImBuf *ibuf, float *texvec, float *dxt, f
maxy= MAX3(dxt[1],dyt[1],dxt[1]+dyt[1] );
/* tex_sharper has been removed */
- minx= tex->filtersize*(maxx-minx)/2.0f;
- miny= tex->filtersize*(maxy-miny)/2.0f;
+ minx= (maxx-minx)/2.0f;
+ miny= (maxy-miny)/2.0f;
- if(tex->filtersize!=1.0f) {
+ if(tex->imaflag & TEX_FILTER_MIN) {
+ /* make sure the filtersize is minimal in pixels (normal, ref map can have miniature pixel dx/dy) */
+ float addval= (0.5f * tex->filtersize) / (float) MIN2(ibuf->x, ibuf->y);
+
+ if(addval > minx)
+ minx= addval;
+ if(addval > miny)
+ miny= addval;
+ }
+ else if(tex->filtersize!=1.0f) {
+ minx*= tex->filtersize;
+ miny*= tex->filtersize;
+
dxt[0]*= tex->filtersize;
dxt[1]*= tex->filtersize;
dyt[0]*= tex->filtersize;
@@ -977,7 +991,7 @@ int imagewraposa(Tex *tex, Image *ima, ImBuf *ibuf, float *texvec, float *dxt, f
}
/* de-premul, this is being premulled in shade_input_do_shade() */
- if(texres->ta!=1.0f && texres->ta!=0.0f) {
+ if(texres->ta!=1.0f && texres->ta>FLT_EPSILON) {
fx= 1.0f/texres->ta;
texres->tr*= fx;
texres->tg*= fx;
diff --git a/source/blender/render/intern/source/initrender.c b/source/blender/render/intern/source/initrender.c
index 3ea8c6edffa..40c0edb6e5f 100644
--- a/source/blender/render/intern/source/initrender.c
+++ b/source/blender/render/intern/source/initrender.c
@@ -257,7 +257,7 @@ void make_sample_tables(Render *re)
{
static int firsttime= 1;
SampleTables *st;
- float flweight[32], fmask[256];
+ float flweight[32];
float weight[32], totw, val, *fpx1, *fpx2, *fpy1, *fpy2, *m3, *m4;
int i, j, a;
@@ -300,11 +300,6 @@ void make_sample_tables(Render *re)
st->centLut[a]= -0.45+((float)a)/16.0;
}
- val= 1.0/((float)re->osa);
- for(a=0; a<256; a++) {
- fmask[a]= ((float)st->cmask[a])*val;
- }
-
/* calculate totw */
totw= 0.0;
for(j= -1; j<2; j++) {
@@ -459,7 +454,10 @@ void RE_SetCamera(Render *re, Object *camera)
if(cam->type==CAM_ORTHO) re->r.mode |= R_ORTHO;
- /* solve this too... all time depending stuff is in convertblender.c? */
+ /* solve this too... all time depending stuff is in convertblender.c?
+ * Need to update the camera early because it's used for projection matrices
+ * and other stuff BEFORE the animation update loop is done
+ * */
if(cam->ipo) {
calc_ipo(cam->ipo, frame_to_float(re->r.cfra));
execute_ipo(&cam->id, cam->ipo);
@@ -603,24 +601,20 @@ void initparts(Render *re)
/* mininum part size, but for exr tile saving it was checked already */
if(!(re->r.scemode & R_EXR_TILE_FILE)) {
if(re->r.mode & R_PANORAMA) {
- if(re->rectx/xparts < 8)
+ if(ceil(re->rectx/(float)xparts) < 8)
xparts= 1 + re->rectx/8;
}
else
- if(re->rectx/xparts < 64)
+ if(ceil(re->rectx/(float)xparts) < 64)
xparts= 1 + re->rectx/64;
- if(re->recty/yparts < 64)
+ if(ceil(re->recty/(float)yparts) < 64)
yparts= 1 + re->recty/64;
}
/* part size */
- partx= re->rectx/xparts;
- party= re->recty/yparts;
-
- /* if remainder pixel, add one, then parts are more equal in size for large panoramas */
- if(re->rectx % partx)
- partx++;
+ partx= ceil(re->rectx/(float)xparts);
+ party= ceil(re->recty/(float)yparts);
re->xparts= xparts;
re->yparts= yparts;
diff --git a/source/blender/render/intern/source/occlusion.c b/source/blender/render/intern/source/occlusion.c
new file mode 100644
index 00000000000..d2d2cf3fb77
--- /dev/null
+++ b/source/blender/render/intern/source/occlusion.c
@@ -0,0 +1,1763 @@
+/*
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2008 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Brecht Van Lommel.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_material_types.h"
+
+#include "BLI_arithb.h"
+#include "BLI_blenlib.h"
+#include "BLI_memarena.h"
+#include "BLI_threads.h"
+
+#include "BKE_global.h"
+#include "BKE_scene.h"
+#include "BKE_utildefines.h"
+
+#include "RE_shader_ext.h"
+
+/* local includes */
+#include "occlusion.h"
+#include "render_types.h"
+#include "rendercore.h"
+#include "renderdatabase.h"
+#include "pixelshading.h"
+#include "shading.h"
+#include "zbuf.h"
+
+/* ------------------------- Declarations --------------------------- */
+
+#define INVALID_INDEX ((int)(~0))
+#define INVPI 0.31830988618379069f
+#define TOTCHILD 8
+#define CACHE_STEP 3
+
+typedef struct OcclusionCacheSample {
+ float co[3], n[3], col[3], intensity, dist2;
+ int x, y, filled;
+} OcclusionCacheSample;
+
+typedef struct OcclusionCache {
+ OcclusionCacheSample *sample;
+ int x, y, w, h, step;
+} OcclusionCache;
+
+typedef struct OccFace {
+ int obi;
+ int facenr;
+} OccFace;
+
+typedef struct OccNode {
+ float co[3], area;
+ float sh[9], dco;
+ float occlusion;
+ int childflag;
+ union {
+ //OccFace face;
+ int face;
+ struct OccNode *node;
+ } child[TOTCHILD];
+} OccNode;
+
+typedef struct OcclusionTree {
+ MemArena *arena;
+
+ float (*co)[3]; /* temporary during build */
+
+ OccFace *face; /* instance and face indices */
+ float *occlusion; /* occlusion for faces */
+
+ OccNode *root;
+
+ OccNode **stack[BLENDER_MAX_THREADS];
+ int maxdepth;
+
+ int totface;
+
+ float error;
+ float distfac;
+
+ int dothreadedbuild;
+ int totbuildthread;
+
+ OcclusionCache *cache;
+} OcclusionTree;
+
+typedef struct OcclusionThread {
+ Render *re;
+ StrandSurface *mesh;
+ float (*facecol)[3];
+ int begin, end;
+ int thread;
+} OcclusionThread;
+
+typedef struct OcclusionBuildThread {
+ OcclusionTree *tree;
+ int begin, end, depth;
+ OccNode *node;
+} OcclusionBuildThread;
+
+/* ------------------------- Shading --------------------------- */
+
+extern Render R; // meh
+
+#if 0
+static void occ_shade(ShadeSample *ssamp, ObjectInstanceRen *obi, VlakRen *vlr, float *rad)
+{
+ ShadeInput *shi= ssamp->shi;
+ ShadeResult *shr= ssamp->shr;
+ float l, u, v, *v1, *v2, *v3;
+
+ /* init */
+ if(vlr->v4) {
+ shi->u= u= 0.5f;
+ shi->v= v= 0.5f;
+ }
+ else {
+ shi->u= u= 1.0f/3.0f;
+ shi->v= v= 1.0f/3.0f;
+ }
+
+ /* setup render coordinates */
+ v1= vlr->v1->co;
+ v2= vlr->v2->co;
+ v3= vlr->v3->co;
+
+ /* renderco */
+ l= 1.0f-u-v;
+
+ shi->co[0]= l*v3[0]+u*v1[0]+v*v2[0];
+ shi->co[1]= l*v3[1]+u*v1[1]+v*v2[1];
+ shi->co[2]= l*v3[2]+u*v1[2]+v*v2[2];
+
+ shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 2);
+
+ /* set up view vector */
+ VECCOPY(shi->view, shi->co);
+ Normalize(shi->view);
+
+ /* cache for shadow */
+ shi->samplenr++;
+
+ shi->xs= 0; // TODO
+ shi->ys= 0;
+
+ shade_input_set_normals(shi);
+
+ /* no normal flip */
+ if(shi->flippednor)
+ shade_input_flip_normals(shi);
+
+ /* not a pretty solution, but fixes common cases */
+ if(shi->obr->ob && shi->obr->ob->transflag & OB_NEG_SCALE) {
+ VecMulf(shi->vn, -1.0f);
+ VecMulf(shi->vno, -1.0f);
+ }
+
+ /* init material vars */
+ // note, keep this synced with render_types.h
+ memcpy(&shi->r, &shi->mat->r, 23*sizeof(float));
+ shi->har= shi->mat->har;
+
+ /* render */
+ shade_input_set_shade_texco(shi);
+ shade_material_loop(shi, shr); /* todo: nodes */
+
+ VECCOPY(rad, shr->combined);
+}
+
+static void occ_build_shade(Render *re, OcclusionTree *tree)
+{
+ ShadeSample ssamp;
+ ObjectInstanceRen *obi;
+ VlakRen *vlr;
+ int a;
+
+ R= *re;
+
+ /* setup shade sample with correct passes */
+ memset(&ssamp, 0, sizeof(ShadeSample));
+ ssamp.shi[0].lay= re->scene->lay;
+ ssamp.shi[0].passflag= SCE_PASS_DIFFUSE|SCE_PASS_RGBA;
+ ssamp.shi[0].combinedflag= ~(SCE_PASS_SPEC);
+ ssamp.tot= 1;
+
+ for(a=0; a<tree->totface; a++) {
+ obi= &R.objectinstance[tree->face[a].obi];
+ vlr= RE_findOrAddVlak(obi->obr, tree->face[a].vlr);
+
+ occ_shade(&ssamp, obi, vlr, tree->rad[a]);
+ }
+}
+#endif
+
+/* ------------------------- Spherical Harmonics --------------------------- */
+
+/* Use 2nd order SH => 9 coefficients, stored in this order:
+ 0 = (0,0),
+ 1 = (1,-1), 2 = (1,0), 3 = (1,1),
+ 4 = (2,-2), 5 = (2,-1), 6 = (2,0), 7 = (2,1), 8 = (2,2) */
+
+static void sh_copy(float *shresult, float *sh)
+{
+ memcpy(shresult, sh, sizeof(float)*9);
+}
+
+static void sh_mul(float *sh, float f)
+{
+ int i;
+
+ for(i=0; i<9; i++)
+ sh[i] *= f;
+}
+
+static void sh_add(float *shresult, float *sh1, float *sh2)
+{
+ int i;
+
+ for(i=0; i<9; i++)
+ shresult[i]= sh1[i] + sh2[i];
+}
+
+static void sh_from_disc(float *n, float area, float *shresult)
+{
+ /* See formula (3) in:
+ "An Efficient Representation for Irradiance Environment Maps" */
+ float sh[9], x, y, z;
+
+ x= n[0];
+ y= n[1];
+ z= n[2];
+
+ sh[0]= 0.282095f;
+
+ sh[1]= 0.488603f*y;
+ sh[2]= 0.488603f*z;
+ sh[3]= 0.488603f*x;
+
+ sh[4]= 1.092548f*x*y;
+ sh[5]= 1.092548f*y*z;
+ sh[6]= 0.315392f*(3.0f*z*z - 1.0f);
+ sh[7]= 1.092548f*x*z;
+ sh[8]= 0.546274f*(x*x - y*y);
+
+ sh_mul(sh, area);
+ sh_copy(shresult, sh);
+}
+
+static float sh_eval(float *sh, float *v)
+{
+ /* See formula (13) in:
+ "An Efficient Representation for Irradiance Environment Maps" */
+ static const float c1 = 0.429043f, c2 = 0.511664f, c3 = 0.743125f;
+ static const float c4 = 0.886227f, c5 = 0.247708f;
+ float x, y, z, sum;
+
+ x= v[0];
+ y= v[1];
+ z= v[2];
+
+ sum= c1*sh[8]*(x*x - y*y);
+ sum += c3*sh[6]*z*z;
+ sum += c4*sh[0];
+ sum += -c5*sh[6];
+ sum += 2.0f*c1*(sh[4]*x*y + sh[7]*x*z + sh[5]*y*z);
+ sum += 2.0f*c2*(sh[3]*x + sh[1]*y + sh[2]*z);
+
+ return sum;
+}
+
+/* ------------------------------ Building --------------------------------- */
+
+static void occ_face(const OccFace *face, float *co, float *normal, float *area)
+{
+ ObjectInstanceRen *obi;
+ VlakRen *vlr;
+ float v1[3], v2[3], v3[3], v4[3];
+
+ obi= &R.objectinstance[face->obi];
+ vlr= RE_findOrAddVlak(obi->obr, face->facenr);
+
+ if(co) {
+ if(vlr->v4)
+ VecLerpf(co, vlr->v1->co, vlr->v3->co, 0.5f);
+ else
+ CalcCent3f(co, vlr->v1->co, vlr->v2->co, vlr->v3->co);
+
+ if(obi->flag & R_TRANSFORMED)
+ Mat4MulVecfl(obi->mat, co);
+ }
+
+ if(normal) {
+ normal[0]= -vlr->n[0];
+ normal[1]= -vlr->n[1];
+ normal[2]= -vlr->n[2];
+
+ if(obi->flag & R_TRANSFORMED)
+ Mat3MulVecfl(obi->nmat, normal);
+ }
+
+ if(area) {
+ VECCOPY(v1, vlr->v1->co);
+ VECCOPY(v2, vlr->v2->co);
+ VECCOPY(v3, vlr->v3->co);
+ if(vlr->v4) VECCOPY(v4, vlr->v4->co);
+
+ if(obi->flag & R_TRANSFORMED) {
+ Mat4MulVecfl(obi->mat, v1);
+ Mat4MulVecfl(obi->mat, v2);
+ Mat4MulVecfl(obi->mat, v3);
+ if(vlr->v4) Mat4MulVecfl(obi->mat, v4);
+ }
+
+ /* todo: correct area for instances */
+ if(vlr->v4)
+ *area= AreaQ3Dfl(v1, v2, v3, v4);
+ else
+ *area= AreaT3Dfl(v1, v2, v3);
+ }
+}
+
+static void occ_sum_occlusion(OcclusionTree *tree, OccNode *node)
+{
+ OccNode *child;
+ float occ, area, totarea;
+ int a, b;
+
+ occ= 0.0f;
+ totarea= 0.0f;
+
+ for(b=0; b<TOTCHILD; b++) {
+ if(node->childflag & (1<<b)) {
+ a= node->child[b].face;
+ occ_face(&tree->face[a], 0, 0, &area);
+ occ += area*tree->occlusion[a];
+ totarea += area;
+ }
+ else if(node->child[b].node) {
+ child= node->child[b].node;
+ occ_sum_occlusion(tree, child);
+
+ occ += child->area*child->occlusion;
+ totarea += child->area;
+ }
+ }
+
+ if(totarea != 0.0f)
+ occ /= totarea;
+
+ node->occlusion= occ;
+}
+
+static int occ_find_bbox_axis(OcclusionTree *tree, int begin, int end, float *min, float *max)
+{
+ float len, maxlen= -1.0f;
+ int a, axis = 0;
+
+ INIT_MINMAX(min, max);
+
+ for(a=begin; a<end; a++)
+ DO_MINMAX(tree->co[a], min, max)
+
+ for(a=0; a<3; a++) {
+ len= max[a] - min[a];
+
+ if(len > maxlen) {
+ maxlen= len;
+ axis= a;
+ }
+ }
+
+ return axis;
+}
+
+static void occ_node_from_face(OccFace *face, OccNode *node)
+{
+ float n[3];
+
+ occ_face(face, node->co, n, &node->area);
+ node->dco= 0.0f;
+ sh_from_disc(n, node->area, node->sh);
+}
+
+static void occ_build_dco(OcclusionTree *tree, OccNode *node, float *co, float *dco)
+{
+ OccNode *child;
+ float dist, d[3], nco[3];
+ int b;
+
+ for(b=0; b<TOTCHILD; b++) {
+ if(node->childflag & (1<<b)) {
+ occ_face(tree->face+node->child[b].face, nco, 0, 0);
+ }
+ else if(node->child[b].node) {
+ child= node->child[b].node;
+ occ_build_dco(tree, child, co, dco);
+ VECCOPY(nco, child->co);
+ }
+
+ VECSUB(d, nco, co);
+ dist= INPR(d, d);
+ if(dist > *dco)
+ *dco= dist;
+ }
+}
+
+static void occ_build_split(OcclusionTree *tree, int begin, int end, int *split)
+{
+ float min[3], max[3], mid;
+ int axis, a, enda;
+
+ /* split in middle of boundbox. this seems faster than median split
+ * on complex scenes, possibly since it avoids two distant faces to
+ * be in the same node better? */
+ axis= occ_find_bbox_axis(tree, begin, end, min, max);
+ mid= 0.5f*(min[axis]+max[axis]);
+
+ a= begin;
+ enda= end;
+ while(a<enda) {
+ if(tree->co[a][axis] > mid) {
+ enda--;
+ SWAP(OccFace, tree->face[a], tree->face[enda]);
+ SWAP(float, tree->co[a][0], tree->co[enda][0]);
+ SWAP(float, tree->co[a][1], tree->co[enda][1]);
+ SWAP(float, tree->co[a][2], tree->co[enda][2]);
+ }
+ else
+ a++;
+ }
+
+ *split= enda;
+}
+
+static void occ_build_8_split(OcclusionTree *tree, int begin, int end, int *offset, int *count)
+{
+ /* split faces into eight groups */
+ int b, splitx, splity[2], splitz[4];
+
+ occ_build_split(tree, begin, end, &splitx);
+
+ /* force split if none found, to deal with degenerate geometry */
+ if(splitx == begin || splitx == end)
+ splitx= (begin+end)/2;
+
+ occ_build_split(tree, begin, splitx, &splity[0]);
+ occ_build_split(tree, splitx, end, &splity[1]);
+
+ occ_build_split(tree, begin, splity[0], &splitz[0]);
+ occ_build_split(tree, splity[0], splitx, &splitz[1]);
+ occ_build_split(tree, splitx, splity[1], &splitz[2]);
+ occ_build_split(tree, splity[1], end, &splitz[3]);
+
+ offset[0]= begin;
+ offset[1]= splitz[0];
+ offset[2]= splity[0];
+ offset[3]= splitz[1];
+ offset[4]= splitx;
+ offset[5]= splitz[2];
+ offset[6]= splity[1];
+ offset[7]= splitz[3];
+
+ for(b=0; b<7; b++)
+ count[b]= offset[b+1] - offset[b];
+ count[7]= end - offset[7];
+}
+
+static void occ_build_recursive(OcclusionTree *tree, OccNode *node, int begin, int end, int depth);
+
+static void *exec_occ_build(void *data)
+{
+ OcclusionBuildThread *othread= (OcclusionBuildThread*)data;
+
+ occ_build_recursive(othread->tree, othread->node, othread->begin, othread->end, othread->depth);
+
+ return 0;
+}
+
+static void occ_build_recursive(OcclusionTree *tree, OccNode *node, int begin, int end, int depth)
+{
+ ListBase threads;
+ OcclusionBuildThread othreads[BLENDER_MAX_THREADS];
+ OccNode *child, tmpnode;
+ OccFace *face;
+ int a, b, totthread=0, offset[TOTCHILD], count[TOTCHILD];
+
+ /* keep track of maximum depth for stack */
+ if(depth > tree->maxdepth)
+ tree->maxdepth= depth;
+
+ /* add a new node */
+ node->occlusion= 1.0f;
+
+ /* leaf node with only children */
+ if(end - begin <= TOTCHILD) {
+ for(a=begin, b=0; a<end; a++, b++) {
+ face= &tree->face[a];
+ node->child[b].face= a;
+ node->childflag |= (1<<b);
+ }
+ }
+ else {
+ /* order faces */
+ occ_build_8_split(tree, begin, end, offset, count);
+
+ if(depth == 1 && tree->dothreadedbuild)
+ BLI_init_threads(&threads, exec_occ_build, tree->totbuildthread);
+
+ for(b=0; b<TOTCHILD; b++) {
+ if(count[b] == 0) {
+ node->child[b].node= NULL;
+ }
+ else if(count[b] == 1) {
+ face= &tree->face[offset[b]];
+ node->child[b].face= offset[b];
+ node->childflag |= (1<<b);
+ }
+ else {
+ if(tree->dothreadedbuild)
+ BLI_lock_thread(LOCK_CUSTOM1);
+
+ child= BLI_memarena_alloc(tree->arena, sizeof(OccNode));
+ node->child[b].node= child;
+
+ if(tree->dothreadedbuild)
+ BLI_unlock_thread(LOCK_CUSTOM1);
+
+ if(depth == 1 && tree->dothreadedbuild) {
+ othreads[totthread].tree= tree;
+ othreads[totthread].node= child;
+ othreads[totthread].begin= offset[b];
+ othreads[totthread].end= offset[b]+count[b];
+ othreads[totthread].depth= depth+1;
+ BLI_insert_thread(&threads, &othreads[totthread]);
+ totthread++;
+ }
+ else
+ occ_build_recursive(tree, child, offset[b], offset[b]+count[b], depth+1);
+ }
+ }
+
+ if(depth == 1 && tree->dothreadedbuild)
+ BLI_end_threads(&threads);
+ }
+
+ /* combine area, position and sh */
+ for(b=0; b<TOTCHILD; b++) {
+ if(node->childflag & (1<<b)) {
+ child= &tmpnode;
+ occ_node_from_face(tree->face+node->child[b].face, &tmpnode);
+ }
+ else {
+ child= node->child[b].node;
+ }
+
+ if(child) {
+ node->area += child->area;
+ sh_add(node->sh, node->sh, child->sh);
+ VECADDFAC(node->co, node->co, child->co, child->area);
+ }
+ }
+
+ if(node->area != 0.0f)
+ VecMulf(node->co, 1.0f/node->area);
+
+ /* compute maximum distance from center */
+ node->dco= 0.0f;
+ occ_build_dco(tree, node, node->co, &node->dco);
+}
+
+static void occ_build_sh_normalize(OccNode *node)
+{
+ /* normalize spherical harmonics to not include area, so
+ * we can clamp the dot product and then mutliply by area */
+ int b;
+
+ if(node->area != 0.0f)
+ sh_mul(node->sh, 1.0f/node->area);
+
+ for(b=0; b<TOTCHILD; b++) {
+ if(node->childflag & (1<<b));
+ else if(node->child[b].node)
+ occ_build_sh_normalize(node->child[b].node);
+ }
+}
+
+static OcclusionTree *occ_tree_build(Render *re)
+{
+ OcclusionTree *tree;
+ ObjectInstanceRen *obi;
+ ObjectRen *obr;
+ VlakRen *vlr= NULL;
+ int a, b, c, totface;
+
+ /* count */
+ totface= 0;
+ for(obi=re->instancetable.first; obi; obi=obi->next) {
+ obr= obi->obr;
+ for(a=0; a<obr->totvlak; a++) {
+ if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak;
+ else vlr++;
+
+ if(vlr->mat->mode & MA_TRACEBLE)
+ totface++;
+ }
+ }
+
+ if(totface == 0)
+ return NULL;
+
+ tree= MEM_callocN(sizeof(OcclusionTree), "OcclusionTree");
+ tree->totface= totface;
+
+ /* parameters */
+ tree->error= get_render_aosss_error(&re->r, re->wrld.ao_approx_error);
+ tree->distfac= (re->wrld.aomode & WO_AODIST)? re->wrld.aodistfac: 0.0f;
+
+ /* allocation */
+ tree->arena= BLI_memarena_new(0x8000 * sizeof(OccNode));
+ BLI_memarena_use_calloc(tree->arena);
+
+ if(re->wrld.aomode & WO_AOCACHE)
+ tree->cache= MEM_callocN(sizeof(OcclusionCache)*BLENDER_MAX_THREADS, "OcclusionCache");
+
+ tree->face= MEM_callocN(sizeof(OccFace)*totface, "OcclusionFace");
+ tree->co= MEM_callocN(sizeof(float)*3*totface, "OcclusionCo");
+ tree->occlusion= MEM_callocN(sizeof(float)*totface, "OcclusionOcclusion");
+
+ /* make array of face pointers */
+ for(b=0, c=0, obi=re->instancetable.first; obi; obi=obi->next, c++) {
+ obr= obi->obr;
+ for(a=0; a<obr->totvlak; a++) {
+ if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak;
+ else vlr++;
+
+ if(vlr->mat->mode & MA_TRACEBLE) {
+ tree->face[b].obi= c;
+ tree->face[b].facenr= a;
+ tree->occlusion[b]= 1.0f;
+ occ_face(&tree->face[b], tree->co[b], NULL, NULL);
+ b++;
+ }
+ }
+ }
+
+ /* threads */
+ tree->totbuildthread= (re->r.threads > 1 && totface > 10000)? 8: 1;
+ tree->dothreadedbuild= (tree->totbuildthread > 1);
+
+ /* recurse */
+ tree->root= BLI_memarena_alloc(tree->arena, sizeof(OccNode));
+ occ_build_recursive(tree, tree->root, 0, totface, 1);
+
+#if 0
+ if(tree->doindirect) {
+ occ_build_shade(re, tree);
+ occ_sum_occlusion(tree, tree->root);
+ }
+#endif
+
+ MEM_freeN(tree->co);
+ tree->co= NULL;
+
+ occ_build_sh_normalize(tree->root);
+
+ for(a=0; a<BLENDER_MAX_THREADS; a++)
+ tree->stack[a]= MEM_callocN(sizeof(OccNode)*TOTCHILD*(tree->maxdepth+1), "OccStack");
+
+ return tree;
+}
+
+static void occ_free_tree(OcclusionTree *tree)
+{
+ int a;
+
+ if(tree) {
+ if(tree->arena) BLI_memarena_free(tree->arena);
+ for(a=0; a<BLENDER_MAX_THREADS; a++)
+ if(tree->stack[a])
+ MEM_freeN(tree->stack[a]);
+ if(tree->occlusion) MEM_freeN(tree->occlusion);
+ if(tree->face) MEM_freeN(tree->face);
+ if(tree->cache) MEM_freeN(tree->cache);
+ MEM_freeN(tree);
+ }
+}
+
+/* ------------------------- Traversal --------------------------- */
+
+static float occ_solid_angle(OccNode *node, float *v, float d2, float invd2, float *receivenormal)
+{
+ float dotreceive, dotemit;
+ float ev[3];
+
+ ev[0]= -v[0]*invd2;
+ ev[1]= -v[1]*invd2;
+ ev[2]= -v[2]*invd2;
+ dotemit= sh_eval(node->sh, ev);
+ dotreceive= INPR(receivenormal, v)*invd2;
+
+ CLAMP(dotemit, 0.0f, 1.0f);
+ CLAMP(dotreceive, 0.0f, 1.0f);
+
+ return ((node->area*dotemit*dotreceive)/(d2 + node->area*INVPI))*INVPI;
+}
+
+static void VecAddDir(float *result, float *v1, float *v2, float fac)
+{
+ result[0]= v1[0] + fac*(v2[0] - v1[0]);
+ result[1]= v1[1] + fac*(v2[1] - v1[1]);
+ result[2]= v1[2] + fac*(v2[2] - v1[2]);
+}
+
+static int occ_visible_quad(float *p, float *n, float *v0, float *v1, float *v2, float *q0, float *q1, float *q2, float *q3)
+{
+ static const float epsilon = 1e-6f;
+ float c, sd[3];
+
+ c= INPR(n, p);
+
+ /* signed distances from the vertices to the plane. */
+ sd[0]= INPR(n, v0) - c;
+ sd[1]= INPR(n, v1) - c;
+ sd[2]= INPR(n, v2) - c;
+
+ if(fabs(sd[0]) < epsilon) sd[0] = 0.0f;
+ if(fabs(sd[1]) < epsilon) sd[1] = 0.0f;
+ if(fabs(sd[2]) < epsilon) sd[2] = 0.0f;
+
+ if(sd[0] > 0) {
+ if(sd[1] > 0) {
+ if(sd[2] > 0) {
+ // +++
+ VECCOPY(q0, v0);
+ VECCOPY(q1, v1);
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ else if(sd[2] < 0) {
+ // ++-
+ VECCOPY(q0, v0);
+ VECCOPY(q1, v1);
+ VecAddDir(q2, v1, v2, (sd[1]/(sd[1]-sd[2])));
+ VecAddDir(q3, v0, v2, (sd[0]/(sd[0]-sd[2])));
+ }
+ else {
+ // ++0
+ VECCOPY(q0, v0);
+ VECCOPY(q1, v1);
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ }
+ else if(sd[1] < 0) {
+ if(sd[2] > 0) {
+ // +-+
+ VECCOPY(q0, v0);
+ VecAddDir(q1, v0, v1, (sd[0]/(sd[0]-sd[1])));
+ VecAddDir(q2, v1, v2, (sd[1]/(sd[1]-sd[2])));
+ VECCOPY(q3, v2);
+ }
+ else if(sd[2] < 0) {
+ // +--
+ VECCOPY(q0, v0);
+ VecAddDir(q1, v0, v1, (sd[0]/(sd[0]-sd[1])));
+ VecAddDir(q2, v0, v2, (sd[0]/(sd[0]-sd[2])));
+ VECCOPY(q3, q2);
+ }
+ else {
+ // +-0
+ VECCOPY(q0, v0);
+ VecAddDir(q1, v0, v1, (sd[0]/(sd[0]-sd[1])));
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ }
+ else {
+ if(sd[2] > 0) {
+ // +0+
+ VECCOPY(q0, v0);
+ VECCOPY(q1, v1);
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ else if(sd[2] < 0) {
+ // +0-
+ VECCOPY(q0, v0);
+ VECCOPY(q1, v1);
+ VecAddDir(q2, v0, v2, (sd[0]/(sd[0]-sd[2])));
+ VECCOPY(q3, q2);
+ }
+ else {
+ // +00
+ VECCOPY(q0, v0);
+ VECCOPY(q1, v1);
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ }
+ }
+ else if(sd[0] < 0) {
+ if(sd[1] > 0) {
+ if(sd[2] > 0) {
+ // -++
+ VecAddDir(q0, v0, v1, (sd[0]/(sd[0]-sd[1])));
+ VECCOPY(q1, v1);
+ VECCOPY(q2, v2);
+ VecAddDir(q3, v0, v2, (sd[0]/(sd[0]-sd[2])));
+ }
+ else if(sd[2] < 0) {
+ // -+-
+ VecAddDir(q0, v0, v1, (sd[0]/(sd[0]-sd[1])));
+ VECCOPY(q1, v1);
+ VecAddDir(q2, v1, v2, (sd[1]/(sd[1]-sd[2])));
+ VECCOPY(q3, q2);
+ }
+ else {
+ // -+0
+ VecAddDir(q0, v0, v1, (sd[0]/(sd[0]-sd[1])));
+ VECCOPY(q1, v1);
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ }
+ else if(sd[1] < 0) {
+ if(sd[2] > 0) {
+ // --+
+ VecAddDir(q0, v0, v2, (sd[0]/(sd[0]-sd[2])));
+ VecAddDir(q1, v1, v2, (sd[1]/(sd[1]-sd[2])));
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ else if(sd[2] < 0) {
+ // ---
+ return 0;
+ }
+ else {
+ // --0
+ return 0;
+ }
+ }
+ else {
+ if(sd[2] > 0) {
+ // -0+
+ VecAddDir(q0, v0, v2, (sd[0]/(sd[0]-sd[2])));
+ VECCOPY(q1, v1);
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ else if(sd[2] < 0) {
+ // -0-
+ return 0;
+ }
+ else {
+ // -00
+ return 0;
+ }
+ }
+ }
+ else {
+ if(sd[1] > 0) {
+ if(sd[2] > 0) {
+ // 0++
+ VECCOPY(q0, v0);
+ VECCOPY(q1, v1);
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ else if(sd[2] < 0) {
+ // 0+-
+ VECCOPY(q0, v0);
+ VECCOPY(q1, v1);
+ VecAddDir(q2, v1, v2, (sd[1]/(sd[1]-sd[2])));
+ VECCOPY(q3, q2);
+ }
+ else {
+ // 0+0
+ VECCOPY(q0, v0);
+ VECCOPY(q1, v1);
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ }
+ else if(sd[1] < 0) {
+ if(sd[2] > 0) {
+ // 0-+
+ VECCOPY(q0, v0);
+ VecAddDir(q1, v1, v2, (sd[1]/(sd[1]-sd[2])));
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ else if(sd[2] < 0) {
+ // 0--
+ return 0;
+ }
+ else {
+ // 0-0
+ return 0;
+ }
+ }
+ else {
+ if(sd[2] > 0) {
+ // 00+
+ VECCOPY(q0, v0);
+ VECCOPY(q1, v1);
+ VECCOPY(q2, v2);
+ VECCOPY(q3, q2);
+ }
+ else if(sd[2] < 0) {
+ // 00-
+ return 0;
+ }
+ else {
+ // 000
+ return 0;
+ }
+ }
+ }
+
+ return 1;
+}
+
+/* altivec optimization, this works, but is unused */
+
+#if 0
+#include <Accelerate/Accelerate.h>
+
+typedef union {
+ vFloat v;
+ float f[4];
+} vFloatResult;
+
+static vFloat vec_splat_float(float val)
+{
+ return (vFloat){val, val, val, val};
+}
+
+static float occ_quad_form_factor(float *p, float *n, float *q0, float *q1, float *q2, float *q3)
+{
+ vFloat vcos, rlen, vrx, vry, vrz, vsrx, vsry, vsrz, gx, gy, gz, vangle;
+ vUInt8 rotate = (vUInt8){4,5,6,7,8,9,10,11,12,13,14,15,0,1,2,3};
+ vFloatResult vresult;
+ float result;
+
+ /* compute r* */
+ vrx = (vFloat){q0[0], q1[0], q2[0], q3[0]} - vec_splat_float(p[0]);
+ vry = (vFloat){q0[1], q1[1], q2[1], q3[1]} - vec_splat_float(p[1]);
+ vrz = (vFloat){q0[2], q1[2], q2[2], q3[2]} - vec_splat_float(p[2]);
+
+ /* normalize r* */
+ rlen = vec_rsqrte(vrx*vrx + vry*vry + vrz*vrz + vec_splat_float(1e-16f));
+ vrx = vrx*rlen;
+ vry = vry*rlen;
+ vrz = vrz*rlen;
+
+ /* rotate r* for cross and dot */
+ vsrx= vec_perm(vrx, vrx, rotate);
+ vsry= vec_perm(vry, vry, rotate);
+ vsrz= vec_perm(vrz, vrz, rotate);
+
+ /* cross product */
+ gx = vsry*vrz - vsrz*vry;
+ gy = vsrz*vrx - vsrx*vrz;
+ gz = vsrx*vry - vsry*vrx;
+
+ /* normalize */
+ rlen = vec_rsqrte(gx*gx + gy*gy + gz*gz + vec_splat_float(1e-16f));
+ gx = gx*rlen;
+ gy = gy*rlen;
+ gz = gz*rlen;
+
+ /* angle */
+ vcos = vrx*vsrx + vry*vsry + vrz*vsrz;
+ vcos= vec_max(vec_min(vcos, vec_splat_float(1.0f)), vec_splat_float(-1.0f));
+ vangle= vacosf(vcos);
+
+ /* dot */
+ vresult.v = (vec_splat_float(n[0])*gx +
+ vec_splat_float(n[1])*gy +
+ vec_splat_float(n[2])*gz)*vangle;
+
+ result= (vresult.f[0] + vresult.f[1] + vresult.f[2] + vresult.f[3])*(0.5f/(float)M_PI);
+ result= MAX2(result, 0.0f);
+
+ return result;
+}
+
+#endif
+
+/* SSE optimization, acos code doesn't work */
+
+#if 0
+
+#include <xmmintrin.h>
+
+static __m128 sse_approx_acos(__m128 x)
+{
+ /* needs a better approximation than taylor expansion of acos, since that
+ * gives big erros for near 1.0 values, sqrt(2*x)*acos(1-x) should work
+ * better, see http://www.tom.womack.net/projects/sse-fast-arctrig.html */
+
+ return _mm_set_ps1(1.0f);
+}
+
+static float occ_quad_form_factor(float *p, float *n, float *q0, float *q1, float *q2, float *q3)
+{
+ float r0[3], r1[3], r2[3], r3[3], g0[3], g1[3], g2[3], g3[3];
+ float a1, a2, a3, a4, dot1, dot2, dot3, dot4, result;
+ float fresult[4] __attribute__((aligned(16)));
+ __m128 qx, qy, qz, rx, ry, rz, rlen, srx, sry, srz, gx, gy, gz, glen, rcos, angle, aresult;
+
+ /* compute r */
+ qx = _mm_set_ps(q3[0], q2[0], q1[0], q0[0]);
+ qy = _mm_set_ps(q3[1], q2[1], q1[1], q0[1]);
+ qz = _mm_set_ps(q3[2], q2[2], q1[2], q0[2]);
+
+ rx = qx - _mm_set_ps1(p[0]);
+ ry = qy - _mm_set_ps1(p[1]);
+ rz = qz - _mm_set_ps1(p[2]);
+
+ /* normalize r */
+ rlen = _mm_rsqrt_ps(rx*rx + ry*ry + rz*rz + _mm_set_ps1(1e-16f));
+ rx = rx*rlen;
+ ry = ry*rlen;
+ rz = rz*rlen;
+
+ /* cross product */
+ srx = _mm_shuffle_ps(rx, rx, _MM_SHUFFLE(0,3,2,1));
+ sry = _mm_shuffle_ps(ry, ry, _MM_SHUFFLE(0,3,2,1));
+ srz = _mm_shuffle_ps(rz, rz, _MM_SHUFFLE(0,3,2,1));
+
+ gx = sry*rz - srz*ry;
+ gy = srz*rx - srx*rz;
+ gz = srx*ry - sry*rx;
+
+ /* normalize g */
+ glen = _mm_rsqrt_ps(gx*gx + gy*gy + gz*gz + _mm_set_ps1(1e-16f));
+ gx = gx*glen;
+ gy = gy*glen;
+ gz = gz*glen;
+
+ /* compute angle */
+ rcos = rx*srx + ry*sry + rz*srz;
+ rcos= _mm_max_ps(_mm_min_ps(rcos, _mm_set_ps1(1.0f)), _mm_set_ps1(-1.0f));
+
+ angle = sse_approx_cos(rcos);
+ aresult = (_mm_set_ps1(n[0])*gx + _mm_set_ps1(n[1])*gy + _mm_set_ps1(n[2])*gz)*angle;
+
+ /* sum together */
+ result= (fresult[0] + fresult[1] + fresult[2] + fresult[3])*(0.5f/(float)M_PI);
+ result= MAX2(result, 0.0f);
+
+ return result;
+}
+
+#endif
+
+static float saacosf(float fac)
+{
+ if(fac<= -1.0f) return (float)M_PI;
+ else if(fac>=1.0f) return 0.0f;
+ else return acos(fac); /* acosf(fac) */
+}
+
+static void normalizef(float *n)
+{
+ float d;
+
+ d= INPR(n, n);
+
+ if(d > 1.0e-35F) {
+ d= 1.0f/sqrt(d); /* sqrtf(d) */
+
+ n[0] *= d;
+ n[1] *= d;
+ n[2] *= d;
+ }
+}
+
+static float occ_quad_form_factor(float *p, float *n, float *q0, float *q1, float *q2, float *q3)
+{
+ float r0[3], r1[3], r2[3], r3[3], g0[3], g1[3], g2[3], g3[3];
+ float a1, a2, a3, a4, dot1, dot2, dot3, dot4, result;
+
+ VECSUB(r0, q0, p);
+ VECSUB(r1, q1, p);
+ VECSUB(r2, q2, p);
+ VECSUB(r3, q3, p);
+
+ normalizef(r0);
+ normalizef(r1);
+ normalizef(r2);
+ normalizef(r3);
+
+ Crossf(g0, r1, r0); normalizef(g0);
+ Crossf(g1, r2, r1); normalizef(g1);
+ Crossf(g2, r3, r2); normalizef(g2);
+ Crossf(g3, r0, r3); normalizef(g3);
+
+ a1= saacosf(INPR(r0, r1));
+ a2= saacosf(INPR(r1, r2));
+ a3= saacosf(INPR(r2, r3));
+ a4= saacosf(INPR(r3, r0));
+
+ dot1= INPR(n, g0);
+ dot2= INPR(n, g1);
+ dot3= INPR(n, g2);
+ dot4= INPR(n, g3);
+
+ result= (a1*dot1 + a2*dot2 + a3*dot3 + a4*dot4)*0.5f/(float)M_PI;
+ result= MAX2(result, 0.0f);
+
+ return result;
+}
+
+static float occ_form_factor(OccFace *face, float *p, float *n)
+{
+ ObjectInstanceRen *obi;
+ VlakRen *vlr;
+ float v1[3], v2[3], v3[3], v4[3], q0[3], q1[3], q2[3], q3[3], contrib= 0.0f;
+
+ obi= &R.objectinstance[face->obi];
+ vlr= RE_findOrAddVlak(obi->obr, face->facenr);
+
+ VECCOPY(v1, vlr->v1->co);
+ VECCOPY(v2, vlr->v2->co);
+ VECCOPY(v3, vlr->v3->co);
+
+ if(obi->flag & R_TRANSFORMED) {
+ Mat4MulVecfl(obi->mat, v1);
+ Mat4MulVecfl(obi->mat, v2);
+ Mat4MulVecfl(obi->mat, v3);
+ }
+
+ if(occ_visible_quad(p, n, v1, v2, v3, q0, q1, q2, q3))
+ contrib += occ_quad_form_factor(p, n, q0, q1, q2, q3);
+
+ if(vlr->v4) {
+ VECCOPY(v4, vlr->v4->co);
+ if(obi->flag & R_TRANSFORMED)
+ Mat4MulVecfl(obi->mat, v4);
+
+ if(occ_visible_quad(p, n, v1, v3, v4, q0, q1, q2, q3))
+ contrib += occ_quad_form_factor(p, n, q0, q1, q2, q3);
+ }
+
+ return contrib;
+}
+
+static void occ_lookup(OcclusionTree *tree, int thread, OccFace *exclude, float *pp, float *pn, float *occ, float *bentn)
+{
+ OccNode *node, **stack;
+ OccFace *face;
+ float resultocc, v[3], p[3], n[3], co[3], invd2;
+ float distfac, fac, error, d2, weight, emitarea;
+ int b, totstack;
+
+ /* init variables */
+ VECCOPY(p, pp);
+ VECCOPY(n, pn);
+ VECADDFAC(p, p, n, 1e-4f);
+
+ if(bentn)
+ VECCOPY(bentn, n);
+
+ error= tree->error;
+ distfac= tree->distfac;
+
+ resultocc= 0.0f;
+
+ /* init stack */
+ stack= tree->stack[thread];
+ stack[0]= tree->root;
+ totstack= 1;
+
+ while(totstack) {
+ /* pop point off the stack */
+ node= stack[--totstack];
+
+ VECSUB(v, node->co, p);
+ d2= INPR(v, v) + 1e-16f;
+ emitarea= MAX2(node->area, node->dco);
+
+ if(d2*error > emitarea) {
+ if(distfac != 0.0f) {
+ fac= 1.0f/(1.0f + distfac*d2);
+ if(fac < 0.01f)
+ continue;
+ }
+ else
+ fac= 1.0f;
+
+ /* accumulate occlusion from spherical harmonics */
+ invd2 = 1.0f/sqrt(d2);
+ weight= occ_solid_angle(node, v, d2, invd2, n);
+ weight *= node->occlusion;
+
+ if(bentn) {
+ bentn[0] -= weight*invd2*v[0];
+ bentn[1] -= weight*invd2*v[1];
+ bentn[2] -= weight*invd2*v[2];
+ }
+
+ resultocc += weight*fac;
+ }
+ else {
+ /* traverse into children */
+ for(b=0; b<TOTCHILD; b++) {
+ if(node->childflag & (1<<b)) {
+ face= tree->face+node->child[b].face;
+
+ /* accumulate occlusion with face form factor */
+ if(!exclude || !(face->obi == exclude->obi && face->facenr == exclude->facenr)) {
+ if(bentn || distfac != 0.0f) {
+ occ_face(face, co, NULL, NULL);
+ VECSUB(v, co, p);
+ d2= INPR(v, v) + 1e-16f;
+
+ fac= (distfac == 0.0f)? 1.0f: 1.0f/(1.0f + distfac*d2);
+ if(fac < 0.01f)
+ continue;
+ }
+ else
+ fac= 1.0f;
+
+ weight= occ_form_factor(face, p, n);
+ weight *= tree->occlusion[node->child[b].face];
+
+ if(bentn) {
+ invd2= 1.0f/sqrt(d2);
+ bentn[0] -= weight*invd2*v[0];
+ bentn[1] -= weight*invd2*v[1];
+ bentn[2] -= weight*invd2*v[2];
+ }
+
+ resultocc += weight*fac;
+ }
+ }
+ else if(node->child[b].node) {
+ /* push child on the stack */
+ stack[totstack++]= node->child[b].node;
+ }
+ }
+ }
+ }
+
+ if(occ) *occ= resultocc;
+ if(bentn) Normalize(bentn);
+}
+
+static void occ_compute_passes(Render *re, OcclusionTree *tree, int totpass)
+{
+ float *occ, co[3], n[3];
+ int pass, i;
+
+ occ= MEM_callocN(sizeof(float)*tree->totface, "OcclusionPassOcc");
+
+ for(pass=0; pass<totpass; pass++) {
+ for(i=0; i<tree->totface; i++) {
+ occ_face(&tree->face[i], co, n, NULL);
+ VecMulf(n, -1.0f);
+ VECADDFAC(co, co, n, 1e-8f);
+
+ occ_lookup(tree, 0, &tree->face[i], co, n, &occ[i], NULL);
+ if(re->test_break())
+ break;
+ }
+
+ if(re->test_break())
+ break;
+
+ for(i=0; i<tree->totface; i++) {
+ tree->occlusion[i] -= occ[i]; //MAX2(1.0f-occ[i], 0.0f);
+ if(tree->occlusion[i] < 0.0f)
+ tree->occlusion[i]= 0.0f;
+ }
+
+ occ_sum_occlusion(tree, tree->root);
+ }
+
+ MEM_freeN(occ);
+}
+
+static void sample_occ_tree(Render *re, OcclusionTree *tree, OccFace *exclude, float *co, float *n, int thread, int onlyshadow, float *skycol)
+{
+ float nn[3], bn[3], fac, occ, occlusion, correction;
+ int aocolor;
+
+ aocolor= re->wrld.aocolor;
+ if(onlyshadow)
+ aocolor= WO_AOPLAIN;
+
+ VECCOPY(nn, n);
+ VecMulf(nn, -1.0f);
+
+ occ_lookup(tree, thread, exclude, co, nn, &occ, (aocolor)? bn: NULL);
+
+ correction= re->wrld.ao_approx_correction;
+
+ occlusion= (1.0f-correction)*(1.0f-occ);
+ CLAMP(occlusion, 0.0f, 1.0f);
+ if(correction != 0.0f)
+ occlusion += correction*exp(-occ);
+
+ if(aocolor) {
+ /* sky shading using bent normal */
+ if(ELEM(aocolor, WO_AOSKYCOL, WO_AOSKYTEX)) {
+ fac= 0.5*(1.0f+bn[0]*re->grvec[0]+ bn[1]*re->grvec[1]+ bn[2]*re->grvec[2]);
+ skycol[0]= (1.0f-fac)*re->wrld.horr + fac*re->wrld.zenr;
+ skycol[1]= (1.0f-fac)*re->wrld.horg + fac*re->wrld.zeng;
+ skycol[2]= (1.0f-fac)*re->wrld.horb + fac*re->wrld.zenb;
+ }
+#if 0
+ else { /* WO_AOSKYTEX */
+ float dxyview[3];
+ bn[0]= -bn[0];
+ bn[1]= -bn[1];
+ bn[2]= -bn[2];
+ dxyview[0]= 1.0f;
+ dxyview[1]= 1.0f;
+ dxyview[2]= 0.0f;
+ shadeSkyView(skycol, co, bn, dxyview);
+ }
+#endif
+
+ VecMulf(skycol, occlusion);
+ }
+ else {
+ skycol[0]= occlusion;
+ skycol[1]= occlusion;
+ skycol[2]= occlusion;
+ }
+}
+
+/* ---------------------------- Caching ------------------------------- */
+
+static OcclusionCacheSample *find_occ_sample(OcclusionCache *cache, int x, int y)
+{
+ x -= cache->x;
+ y -= cache->y;
+
+ x /= cache->step;
+ y /= cache->step;
+ x *= cache->step;
+ y *= cache->step;
+
+ if(x < 0 || x >= cache->w || y < 0 || y >= cache->h)
+ return NULL;
+ else
+ return &cache->sample[y*cache->w + x];
+}
+
+static int sample_occ_cache(OcclusionTree *tree, float *co, float *n, int x, int y, int thread, float *col)
+{
+ OcclusionCache *cache;
+ OcclusionCacheSample *samples[4], *sample;
+ float wn[4], wz[4], wb[4], tx, ty, w, totw, mino, maxo;
+ float d[3], dist2;
+ int i, x1, y1, x2, y2;
+
+ if(!tree->cache)
+ return 0;
+
+ /* first try to find a sample in the same pixel */
+ cache= &tree->cache[thread];
+
+ if(cache->sample && cache->step) {
+ sample= &cache->sample[(y-cache->y)*cache->w + (x-cache->x)];
+ if(sample->filled) {
+ VECSUB(d, sample->co, co);
+ dist2= INPR(d, d);
+ if(dist2 < 0.5f*sample->dist2 && INPR(sample->n, n) > 0.98f) {
+ VECCOPY(col, sample->col);
+ return 1;
+ }
+ }
+ }
+ else
+ return 0;
+
+ /* try to interpolate between 4 neighbouring pixels */
+ samples[0]= find_occ_sample(cache, x, y);
+ samples[1]= find_occ_sample(cache, x+cache->step, y);
+ samples[2]= find_occ_sample(cache, x, y+cache->step);
+ samples[3]= find_occ_sample(cache, x+cache->step, y+cache->step);
+
+ for(i=0; i<4; i++)
+ if(!samples[i] || !samples[i]->filled)
+ return 0;
+
+ /* require intensities not being too different */
+ mino= MIN4(samples[0]->intensity, samples[1]->intensity, samples[2]->intensity, samples[3]->intensity);
+ maxo= MAX4(samples[0]->intensity, samples[1]->intensity, samples[2]->intensity, samples[3]->intensity);
+
+ if(maxo - mino > 0.05f)
+ return 0;
+
+ /* compute weighted interpolation between samples */
+ col[0]= col[1]= col[2]= 0.0f;
+ totw= 0.0f;
+
+ x1= samples[0]->x;
+ y1= samples[0]->y;
+ x2= samples[3]->x;
+ y2= samples[3]->y;
+
+ tx= (float)(x2 - x)/(float)(x2 - x1);
+ ty= (float)(y2 - y)/(float)(y2 - y1);
+
+ wb[3]= (1.0f-tx)*(1.0f-ty);
+ wb[2]= (tx)*(1.0f-ty);
+ wb[1]= (1.0f-tx)*(ty);
+ wb[0]= tx*ty;
+
+ for(i=0; i<4; i++) {
+ VECSUB(d, samples[i]->co, co);
+ dist2= INPR(d, d);
+
+ wz[i]= 1.0f; //(samples[i]->dist2/(1e-4f + dist2));
+ wn[i]= pow(INPR(samples[i]->n, n), 32.0f);
+
+ w= wb[i]*wn[i]*wz[i];
+
+ totw += w;
+ col[0] += w*samples[i]->col[0];
+ col[1] += w*samples[i]->col[1];
+ col[2] += w*samples[i]->col[2];
+ }
+
+ if(totw >= 0.9f) {
+ totw= 1.0f/totw;
+ col[0] *= totw;
+ col[1] *= totw;
+ col[2] *= totw;
+ return 1;
+ }
+
+ return 0;
+}
+
+static void sample_occ_surface(ShadeInput *shi)
+{
+ StrandRen *strand= shi->strand;
+ StrandSurface *mesh= strand->buffer->surface;
+ int *face, *index = RE_strandren_get_face(shi->obr, strand, 0);
+ float w[4], *co1, *co2, *co3, *co4;
+
+ if(mesh && mesh->face && mesh->co && mesh->col && index) {
+ face= mesh->face[*index];
+
+ co1= mesh->co[face[0]];
+ co2= mesh->co[face[1]];
+ co3= mesh->co[face[2]];
+ co4= (face[3])? mesh->co[face[3]]: NULL;
+
+ InterpWeightsQ3Dfl(co1, co2, co3, co4, strand->vert->co, w);
+
+ shi->ao[0]= shi->ao[1]= shi->ao[2]= 0.0f;
+ VECADDFAC(shi->ao, shi->ao, mesh->col[face[0]], w[0]);
+ VECADDFAC(shi->ao, shi->ao, mesh->col[face[1]], w[1]);
+ VECADDFAC(shi->ao, shi->ao, mesh->col[face[2]], w[2]);
+ if(face[3])
+ VECADDFAC(shi->ao, shi->ao, mesh->col[face[3]], w[3]);
+ }
+ else {
+ shi->ao[0]= 1.0f;
+ shi->ao[1]= 1.0f;
+ shi->ao[2]= 1.0f;
+ }
+}
+
+/* ------------------------- External Functions --------------------------- */
+
+static void *exec_strandsurface_sample(void *data)
+{
+ OcclusionThread *othread= (OcclusionThread*)data;
+ Render *re= othread->re;
+ StrandSurface *mesh= othread->mesh;
+ float col[3], co[3], n[3], *co1, *co2, *co3, *co4;
+ int a, *face;
+
+ for(a=othread->begin; a<othread->end; a++) {
+ face= mesh->face[a];
+ co1= mesh->co[face[0]];
+ co2= mesh->co[face[1]];
+ co3= mesh->co[face[2]];
+
+ if(face[3]) {
+ co4= mesh->co[face[3]];
+
+ VecLerpf(co, co1, co3, 0.5f);
+ CalcNormFloat4(co1, co2, co3, co4, n);
+ }
+ else {
+ CalcCent3f(co, co1, co2, co3);
+ CalcNormFloat(co1, co2, co3, n);
+ }
+ VecMulf(n, -1.0f);
+
+ sample_occ_tree(re, re->occlusiontree, NULL, co, n, othread->thread, 0, col);
+ VECCOPY(othread->facecol[a], col);
+ }
+
+ return 0;
+}
+
+void make_occ_tree(Render *re)
+{
+ OcclusionThread othreads[BLENDER_MAX_THREADS];
+ StrandSurface *mesh;
+ ListBase threads;
+ float col[3], (*facecol)[3];
+ int a, totface, totthread, *face, *count;
+
+ /* ugly, needed for occ_face */
+ R= *re;
+
+ re->i.infostr= "Occlusion preprocessing";
+ re->stats_draw(&re->i);
+
+ re->occlusiontree= occ_tree_build(re);
+
+ if(re->occlusiontree) {
+ if(re->wrld.ao_approx_passes)
+ occ_compute_passes(re, re->occlusiontree, re->wrld.ao_approx_passes);
+
+ for(mesh=re->strandsurface.first; mesh; mesh=mesh->next) {
+ if(!mesh->face || !mesh->co || !mesh->col)
+ continue;
+
+ count= MEM_callocN(sizeof(int)*mesh->totvert, "OcclusionCount");
+ facecol= MEM_callocN(sizeof(float)*3*mesh->totface, "StrandSurfFaceCol");
+
+ totthread= (mesh->totface > 10000)? re->r.threads: 1;
+ totface= mesh->totface/totthread;
+ for(a=0; a<totthread; a++) {
+ othreads[a].re= re;
+ othreads[a].facecol= facecol;
+ othreads[a].thread= a;
+ othreads[a].mesh= mesh;
+ othreads[a].begin= a*totface;
+ othreads[a].end= (a == totthread-1)? mesh->totface: (a+1)*totface;
+ }
+
+ if(totthread == 1) {
+ exec_strandsurface_sample(&othreads[0]);
+ }
+ else {
+ BLI_init_threads(&threads, exec_strandsurface_sample, totthread);
+
+ for(a=0; a<totthread; a++)
+ BLI_insert_thread(&threads, &othreads[a]);
+
+ BLI_end_threads(&threads);
+ }
+
+ for(a=0; a<mesh->totface; a++) {
+ face= mesh->face[a];
+
+ VECCOPY(col, facecol[a]);
+ VECADD(mesh->col[face[0]], mesh->col[face[0]], col);
+ count[face[0]]++;
+ VECADD(mesh->col[face[1]], mesh->col[face[1]], col);
+ count[face[1]]++;
+ VECADD(mesh->col[face[2]], mesh->col[face[2]], col);
+ count[face[2]]++;
+
+ if(face[3]) {
+ VECADD(mesh->col[face[3]], mesh->col[face[3]], col);
+ count[face[3]]++;
+ }
+ }
+
+ for(a=0; a<mesh->totvert; a++)
+ if(count[a])
+ VecMulf(mesh->col[a], 1.0f/count[a]);
+
+ MEM_freeN(count);
+ MEM_freeN(facecol);
+ }
+ }
+}
+
+void free_occ(Render *re)
+{
+ if(re->occlusiontree) {
+ occ_free_tree(re->occlusiontree);
+ re->occlusiontree = NULL;
+ }
+}
+
+void sample_occ(Render *re, ShadeInput *shi)
+{
+ OcclusionTree *tree= re->occlusiontree;
+ OcclusionCache *cache;
+ OcclusionCacheSample *sample;
+ OccFace exclude;
+ int onlyshadow;
+
+ if(tree) {
+ if(shi->strand) {
+ sample_occ_surface(shi);
+ }
+ /* try to get result from the cache if possible */
+ else if(!sample_occ_cache(tree, shi->co, shi->vno, shi->xs, shi->ys, shi->thread, shi->ao)) {
+ /* no luck, let's sample the occlusion */
+ exclude.obi= shi->obi - re->objectinstance;
+ exclude.facenr= shi->vlr->index;
+ onlyshadow= (shi->mat->mode & MA_ONLYSHADOW);
+ sample_occ_tree(re, tree, &exclude, shi->co, shi->vno, shi->thread, onlyshadow, shi->ao);
+
+ /* fill result into sample, each time */
+ if(tree->cache) {
+ cache= &tree->cache[shi->thread];
+
+ if(cache->sample && cache->step) {
+ sample= &cache->sample[(shi->ys-cache->y)*cache->w + (shi->xs-cache->x)];
+ VECCOPY(sample->co, shi->co);
+ VECCOPY(sample->n, shi->vno);
+ VECCOPY(sample->col, shi->ao);
+ sample->intensity= MAX3(sample->col[0], sample->col[1], sample->col[2]);
+ sample->dist2= INPR(shi->dxco, shi->dxco) + INPR(shi->dyco, shi->dyco);
+ sample->filled= 1;
+ }
+ }
+ }
+ }
+ else {
+ shi->ao[0]= 1.0f;
+ shi->ao[1]= 1.0f;
+ shi->ao[2]= 1.0f;
+ }
+}
+
+void cache_occ_samples(Render *re, RenderPart *pa, ShadeSample *ssamp)
+{
+ OcclusionTree *tree= re->occlusiontree;
+ PixStr ps;
+ OcclusionCache *cache;
+ OcclusionCacheSample *sample;
+ OccFace exclude;
+ ShadeInput *shi;
+ intptr_t *rd=NULL;
+ int *ro=NULL, *rp=NULL, *rz=NULL, onlyshadow;
+ int x, y, step = CACHE_STEP;
+
+ if(!tree->cache)
+ return;
+
+ cache= &tree->cache[pa->thread];
+ cache->w= pa->rectx;
+ cache->h= pa->recty;
+ cache->x= pa->disprect.xmin;
+ cache->y= pa->disprect.ymin;
+ cache->step= step;
+ cache->sample= MEM_callocN(sizeof(OcclusionCacheSample)*cache->w*cache->h, "OcclusionCacheSample");
+ sample= cache->sample;
+
+ if(re->osa) {
+ rd= pa->rectdaps;
+ }
+ else {
+ /* fake pixel struct for non-osa */
+ ps.next= NULL;
+ ps.mask= 0xFFFF;
+
+ ro= pa->recto;
+ rp= pa->rectp;
+ rz= pa->rectz;
+ }
+
+ /* compute a sample at every step pixels */
+ for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++) {
+ for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, sample++, rd++, ro++, rp++, rz++) {
+ if(!(((x - pa->disprect.xmin + step) % step) == 0 || x == pa->disprect.xmax-1))
+ continue;
+ if(!(((y - pa->disprect.ymin + step) % step) == 0 || y == pa->disprect.ymax-1))
+ continue;
+
+ if(re->osa) {
+ if(!*rd) continue;
+
+ shade_samples_fill_with_ps(ssamp, (PixStr *)(*rd), x, y);
+ }
+ else {
+ if(!*rp) continue;
+
+ ps.obi= *ro;
+ ps.facenr= *rp;
+ ps.z= *rz;
+ shade_samples_fill_with_ps(ssamp, &ps, x, y);
+ }
+
+ shi= ssamp->shi;
+ if(shi->vlr) {
+ onlyshadow= (shi->mat->mode & MA_ONLYSHADOW);
+ exclude.obi= shi->obi - re->objectinstance;
+ exclude.facenr= shi->vlr->index;
+ sample_occ_tree(re, tree, &exclude, shi->co, shi->vno, shi->thread, onlyshadow, shi->ao);
+
+ VECCOPY(sample->co, shi->co);
+ VECCOPY(sample->n, shi->vno);
+ VECCOPY(sample->col, shi->ao);
+ sample->intensity= MAX3(sample->col[0], sample->col[1], sample->col[2]);
+ sample->dist2= INPR(shi->dxco, shi->dxco) + INPR(shi->dyco, shi->dyco);
+ sample->x= shi->xs;
+ sample->y= shi->ys;
+ sample->filled= 1;
+ }
+
+ if(re->test_break())
+ break;
+ }
+ }
+}
+
+void free_occ_samples(Render *re, RenderPart *pa)
+{
+ OcclusionTree *tree= re->occlusiontree;
+ OcclusionCache *cache;
+
+ if(tree->cache) {
+ cache= &tree->cache[pa->thread];
+
+ if(cache->sample)
+ MEM_freeN(cache->sample);
+
+ cache->w= 0;
+ cache->h= 0;
+ cache->step= 0;
+ }
+}
+
diff --git a/source/blender/render/intern/source/pipeline.c b/source/blender/render/intern/source/pipeline.c
index 5315552310a..2d7d954b70d 100644
--- a/source/blender/render/intern/source/pipeline.c
+++ b/source/blender/render/intern/source/pipeline.c
@@ -38,6 +38,7 @@
#include "DNA_scene_types.h"
#include "DNA_userdef_types.h"
+#include "BKE_utildefines.h"
#include "BKE_global.h"
#include "BKE_image.h"
#include "BKE_main.h"
@@ -76,6 +77,7 @@
#include "envmap.h"
#include "initrender.h"
#include "shadbuf.h"
+#include "pixelblending.h"
#include "zbuf.h"
@@ -114,7 +116,7 @@ static struct ListBase RenderList= {NULL, NULL};
Render R;
/* commandline thread override */
-static int commandline_threads= 0;
+static int commandline_threads= -1;
/* ********* alloc and free ******** */
@@ -135,30 +137,27 @@ static void print_error(char *str) {printf("ERROR: %s\n", str);}
static void stats_background(RenderStats *rs)
{
- extern unsigned long mem_in_use;
+ uintptr_t mem_in_use= MEM_get_memory_in_use();
float megs_used_memory= mem_in_use/(1024.0*1024.0);
char str[400], *spos= str;
- if(rs->convertdone) {
-
- spos+= sprintf(spos, "Fra:%d Mem:%.2fM ", G.scene->r.cfra, megs_used_memory);
-
- if(rs->curfield)
- spos+= sprintf(spos, "Field %d ", rs->curfield);
- if(rs->curblur)
- spos+= sprintf(spos, "Blur %d ", rs->curblur);
-
- if(rs->infostr) {
- spos+= sprintf(spos, "| %s", rs->infostr);
- }
- else {
- if(rs->tothalo)
- spos+= sprintf(spos, "Sce: %s Ve:%d Fa:%d Ha:%d La:%d", G.scene->id.name+2, rs->totvert, rs->totface, rs->tothalo, rs->totlamp);
- else
- spos+= sprintf(spos, "Sce: %s Ve:%d Fa:%d La:%d", G.scene->id.name+2, rs->totvert, rs->totface, rs->totlamp);
- }
- printf(str); printf("\n");
- }
+ spos+= sprintf(spos, "Fra:%d Mem:%.2fM ", G.scene->r.cfra, megs_used_memory);
+
+ if(rs->curfield)
+ spos+= sprintf(spos, "Field %d ", rs->curfield);
+ if(rs->curblur)
+ spos+= sprintf(spos, "Blur %d ", rs->curblur);
+
+ if(rs->infostr) {
+ spos+= sprintf(spos, "| %s", rs->infostr);
+ }
+ else {
+ if(rs->tothalo)
+ spos+= sprintf(spos, "Sce: %s Ve:%d Fa:%d Ha:%d La:%d", G.scene->id.name+2, rs->totvert, rs->totface, rs->tothalo, rs->totlamp);
+ else
+ spos+= sprintf(spos, "Sce: %s Ve:%d Fa:%d La:%d", G.scene->id.name+2, rs->totvert, rs->totface, rs->totlamp);
+ }
+ printf(str); printf("\n");
}
void RE_FreeRenderResult(RenderResult *res)
@@ -193,6 +192,22 @@ void RE_FreeRenderResult(RenderResult *res)
MEM_freeN(res);
}
+/* version that's compatible with fullsample buffers */
+static void free_render_result(ListBase *lb, RenderResult *rr)
+{
+ RenderResult *rrnext;
+
+ for(; rr; rr= rrnext) {
+ rrnext= rr->next;
+
+ if(lb && lb->first)
+ BLI_remlink(lb, rr);
+
+ RE_FreeRenderResult(rr);
+ }
+}
+
+
/* all layers except the active one get temporally pushed away */
static void push_render_result(Render *re)
{
@@ -329,6 +344,10 @@ static char *get_pass_name(int passtype, int channel)
if(channel==-1) return "IndexOB";
return "IndexOB.X";
}
+ if(passtype == SCE_PASS_MIST) {
+ if(channel==-1) return "Mist";
+ return "Mist.Z";
+ }
return "Unknown";
}
@@ -377,23 +396,25 @@ static int passtype_from_name(char *str)
if(strcmp(str, "IndexOB")==0)
return SCE_PASS_INDEXOB;
+ if(strcmp(str, "Mist")==0)
+ return SCE_PASS_MIST;
+
return 0;
}
-
-
-static void render_unique_exr_name(Render *re, char *str)
+static void render_unique_exr_name(Render *re, char *str, int sample)
{
char di[FILE_MAX], name[FILE_MAXFILE], fi[FILE_MAXFILE];
BLI_strncpy(di, G.sce, FILE_MAX);
BLI_splitdirstring(di, fi);
- sprintf(name, "%s_%s.exr", fi, re->scene->id.name+2);
- if(G.background)
- BLI_make_file_string("/", str, "/tmp/", name);
+
+ if(sample==0)
+ sprintf(name, "%s_%s.exr", fi, re->scene->id.name+2);
else
- BLI_make_file_string("/", str, U.tempdir, name);
-
+ sprintf(name, "%s_%s%d.exr", fi, re->scene->id.name+2, sample);
+
+ BLI_make_file_string("/", str, btempdir, name);
}
static void render_layer_add_pass(RenderResult *rr, RenderLayer *rl, int channels, int passtype)
@@ -412,17 +433,22 @@ static void render_layer_add_pass(RenderResult *rr, RenderLayer *rl, int channel
IMB_exr_add_channel(rr->exrhandle, rl->name, get_pass_name(passtype, a), 0, 0, NULL);
}
else {
+ float *rect;
+ int x;
+
+ rpass->rect= MEM_mapallocN(sizeof(float)*rectsize, typestr);
+
if(passtype==SCE_PASS_VECTOR) {
- float *rect;
- int x;
-
/* initialize to max speed */
- rect= rpass->rect= MEM_mapallocN(sizeof(float)*rectsize, typestr);
+ rect= rpass->rect;
for(x= rectsize-1; x>=0; x--)
rect[x]= PASS_VECTOR_MAX;
}
- else
- rpass->rect= MEM_mapallocN(sizeof(float)*rectsize, typestr);
+ else if(passtype==SCE_PASS_Z) {
+ rect= rpass->rect;
+ for(x= rectsize-1; x>=0; x--)
+ rect[x]= 10e10;
+ }
}
}
@@ -496,6 +522,7 @@ static RenderResult *new_render_result(Render *re, rcti *partrct, int crop, int
strcpy(rl->name, srl->name);
rl->lay= srl->lay;
+ rl->lay_zmask= srl->lay_zmask;
rl->layflag= srl->layflag;
rl->passflag= srl->passflag;
rl->pass_xor= srl->pass_xor;
@@ -525,22 +552,20 @@ static RenderResult *new_render_result(Render *re, rcti *partrct, int crop, int
render_layer_add_pass(rr, rl, 3, SCE_PASS_DIFFUSE);
if(srl->passflag & SCE_PASS_SPEC)
render_layer_add_pass(rr, rl, 3, SCE_PASS_SPEC);
- if(re->r.mode & R_SHADOW)
- if(srl->passflag & SCE_PASS_SHADOW)
- render_layer_add_pass(rr, rl, 3, SCE_PASS_SHADOW);
- if(re->r.mode & R_RAYTRACE) {
- if(srl->passflag & SCE_PASS_AO)
- render_layer_add_pass(rr, rl, 3, SCE_PASS_AO);
- if(srl->passflag & SCE_PASS_REFLECT)
- render_layer_add_pass(rr, rl, 3, SCE_PASS_REFLECT);
- if(srl->passflag & SCE_PASS_REFRACT)
- render_layer_add_pass(rr, rl, 3, SCE_PASS_REFRACT);
- }
- if(re->r.mode & R_RADIO)
- if(srl->passflag & SCE_PASS_RADIO)
- render_layer_add_pass(rr, rl, 3, SCE_PASS_RADIO);
+ if(srl->passflag & SCE_PASS_AO)
+ render_layer_add_pass(rr, rl, 3, SCE_PASS_AO);
+ if(srl->passflag & SCE_PASS_SHADOW)
+ render_layer_add_pass(rr, rl, 3, SCE_PASS_SHADOW);
+ if(srl->passflag & SCE_PASS_REFLECT)
+ render_layer_add_pass(rr, rl, 3, SCE_PASS_REFLECT);
+ if(srl->passflag & SCE_PASS_REFRACT)
+ render_layer_add_pass(rr, rl, 3, SCE_PASS_REFRACT);
+ if(srl->passflag & SCE_PASS_RADIO)
+ render_layer_add_pass(rr, rl, 3, SCE_PASS_RADIO);
if(srl->passflag & SCE_PASS_INDEXOB)
render_layer_add_pass(rr, rl, 1, SCE_PASS_INDEXOB);
+ if(srl->passflag & SCE_PASS_MIST)
+ render_layer_add_pass(rr, rl, 1, SCE_PASS_MIST);
}
/* sss, previewrender and envmap don't do layers, so we make a default one */
@@ -575,14 +600,13 @@ static RenderResult *new_render_result(Render *re, rcti *partrct, int crop, int
static int render_scene_needs_vector(Render *re)
{
- if((re->r.scemode & R_DOCOMP) || re->r.imtype==R_MULTILAYER) {
- SceneRenderLayer *srl;
+ SceneRenderLayer *srl;
- for(srl= re->scene->r.layers.first; srl; srl= srl->next)
- if(!(srl->layflag & SCE_LAY_DISABLE))
- if(srl->passflag & SCE_PASS_VECTOR)
- return 1;
- }
+ for(srl= re->scene->r.layers.first; srl; srl= srl->next)
+ if(!(srl->layflag & SCE_LAY_DISABLE))
+ if(srl->passflag & SCE_PASS_VECTOR)
+ return 1;
+
return 0;
}
@@ -640,9 +664,8 @@ static void merge_render_result(RenderResult *rr, RenderResult *rrpart)
}
-static void save_render_result_tile(Render *re, RenderPart *pa)
+static void save_render_result_tile(RenderResult *rr, RenderResult *rrpart)
{
- RenderResult *rrpart= pa->result;
RenderLayer *rlp;
RenderPass *rpassp;
int offs, partx, party;
@@ -662,23 +685,23 @@ static void save_render_result_tile(Render *re, RenderPart *pa)
if(rlp->rectf) {
int a, xstride= 4;
for(a=0; a<xstride; a++)
- IMB_exr_set_channel(re->result->exrhandle, rlp->name, get_pass_name(SCE_PASS_COMBINED, a),
- xstride, xstride*pa->rectx, rlp->rectf+a + xstride*offs);
+ IMB_exr_set_channel(rr->exrhandle, rlp->name, get_pass_name(SCE_PASS_COMBINED, a),
+ xstride, xstride*rrpart->rectx, rlp->rectf+a + xstride*offs);
}
/* passes are allocated in sync */
for(rpassp= rlp->passes.first; rpassp; rpassp= rpassp->next) {
int a, xstride= rpassp->channels;
for(a=0; a<xstride; a++)
- IMB_exr_set_channel(re->result->exrhandle, rlp->name, get_pass_name(rpassp->passtype, a),
- xstride, xstride*pa->rectx, rpassp->rect+a + xstride*offs);
+ IMB_exr_set_channel(rr->exrhandle, rlp->name, get_pass_name(rpassp->passtype, a),
+ xstride, xstride*rrpart->rectx, rpassp->rect+a + xstride*offs);
}
}
party= rrpart->tilerect.ymin + rrpart->crop;
partx= rrpart->tilerect.xmin + rrpart->crop;
- IMB_exrtile_write_channels(re->result->exrhandle, partx, party);
+ IMB_exrtile_write_channels(rr->exrhandle, partx, party, 0);
BLI_unlock_thread(LOCK_IMAGE);
@@ -687,14 +710,17 @@ static void save_render_result_tile(Render *re, RenderPart *pa)
static void save_empty_result_tiles(Render *re)
{
RenderPart *pa;
+ RenderResult *rr;
- IMB_exrtile_clear_channels(re->result->exrhandle);
+ for(rr= re->result; rr; rr= rr->next) {
+ IMB_exrtile_clear_channels(rr->exrhandle);
- for(pa= re->parts.first; pa; pa= pa->next) {
- if(pa->ready==0) {
- int party= pa->disprect.ymin - re->disprect.ymin + pa->crop;
- int partx= pa->disprect.xmin - re->disprect.xmin + pa->crop;
- IMB_exrtile_write_channels(re->result->exrhandle, partx, party);
+ for(pa= re->parts.first; pa; pa= pa->next) {
+ if(pa->ready==0) {
+ int party= pa->disprect.ymin - re->disprect.ymin + pa->crop;
+ int partx= pa->disprect.xmin - re->disprect.xmin + pa->crop;
+ IMB_exrtile_write_channels(rr->exrhandle, partx, party, 0);
+ }
}
}
}
@@ -722,6 +748,8 @@ void RE_WriteRenderResult(RenderResult *rr, char *filename, int compress)
RenderLayer *rl;
RenderPass *rpass;
void *exrhandle= IMB_exr_get_handle();
+
+ BLI_make_existing_file(filename);
/* composite result */
if(rr->rectf) {
@@ -821,7 +849,7 @@ static void renderresult_add_names(RenderResult *rr)
/* only for temp buffer files, makes exact copy of render result */
-static void read_render_result(Render *re)
+static void read_render_result(Render *re, int sample)
{
RenderLayer *rl;
RenderPass *rpass;
@@ -832,14 +860,16 @@ static void read_render_result(Render *re)
RE_FreeRenderResult(re->result);
re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
- render_unique_exr_name(re, str);
+ render_unique_exr_name(re, str, sample);
if(IMB_exr_begin_read(exrhandle, str, &rectx, &recty)==0) {
IMB_exr_close(exrhandle);
printf("cannot read: %s\n", str);
return;
}
- if(rectx!=re->result->rectx || recty!=re->result->recty) {
+ printf("read exr tmp file: %s\n", str);
+
+ if(re->result == NULL || rectx!=re->result->rectx || recty!=re->result->recty) {
printf("error in reading render result\n");
}
else {
@@ -930,7 +960,6 @@ void RE_GetResultImage(Render *re, RenderResult *rr)
}
}
-#define FTOCHAR(val) val<=0.0f?0: (val>=1.0f?255: (char)(255.0f*val))
/* caller is responsible for allocating rect in correct size! */
void RE_ResultGet32(Render *re, unsigned int *rect)
{
@@ -962,6 +991,7 @@ RenderStats *RE_GetStats(Render *re)
return &re->i;
}
+/* Note, when rendering from a scene, ALWAYS use G.scene->id.name, else compositing wont work */
Render *RE_NewRender(const char *name)
{
Render *re;
@@ -1022,7 +1052,7 @@ void RE_FreeAllRender(void)
/* what doesn't change during entire render sequence */
/* disprect is optional, if NULL it assumes full window render */
-void RE_InitState(Render *re, RenderData *rd, int winx, int winy, rcti *disprect)
+void RE_InitState(Render *re, Render *source, RenderData *rd, int winx, int winy, rcti *disprect)
{
re->ok= TRUE; /* maybe flag */
@@ -1045,18 +1075,36 @@ void RE_InitState(Render *re, RenderData *rd, int winx, int winy, rcti *disprect
}
if(re->rectx < 2 || re->recty < 2 || (BKE_imtype_is_movie(rd->imtype) &&
-(re->rectx < 16 || re->recty < 16) )) {
+ (re->rectx < 16 || re->recty < 16) )) {
re->error("Image too small");
re->ok= 0;
}
else {
- /* check state variables, osa? */
- if(re->r.mode & (R_OSA)) {
- re->osa= re->r.osa;
- if(re->osa>16) re->osa= 16;
- }
- else re->osa= 0;
+#ifndef WITH_OPENEXR
+ /* can't do this without openexr support */
+ re->r.scemode &= ~R_EXR_TILE_FILE;
+#endif
+
+ if(!(re->r.scemode & R_EXR_TILE_FILE))
+ re->r.scemode &= ~R_FULL_SAMPLE; /* clear, so we can use this flag for test both */
+ /* fullsample wants uniform osa levels */
+ if(source && (re->r.scemode & R_FULL_SAMPLE)) {
+ /* but, if source has no full sample we disable it */
+ if((source->r.scemode & R_FULL_SAMPLE)==0)
+ re->r.scemode &= ~R_FULL_SAMPLE;
+ else
+ re->r.osa= re->osa= source->osa;
+ }
+ else {
+ /* check state variables, osa? */
+ if(re->r.mode & (R_OSA)) {
+ re->osa= re->r.osa;
+ if(re->osa>16) re->osa= 16;
+ }
+ else re->osa= 0;
+ }
+
/* always call, checks for gamma, gamma tables and jitter too */
make_sample_tables(re);
@@ -1069,11 +1117,11 @@ void RE_InitState(Render *re, RenderData *rd, int winx, int winy, rcti *disprect
/* we clip faces with a minimum of 2 pixel boundary outside of image border. see zbuf.c */
re->clipcrop= 1.0f + 2.0f/(float)(re->winx>re->winy?re->winy:re->winx);
- if(commandline_threads>0 && commandline_threads<=BLENDER_MAX_THREADS)
- re->r.threads= commandline_threads;
+ RE_init_threadcount(re);
}
}
+/* part of external api, not called for regular render pipeline */
void RE_SetDispRect (struct Render *re, rcti *disprect)
{
re->disprect= *disprect;
@@ -1174,13 +1222,36 @@ static int render_display_draw_enabled(Render *re)
return 1;
}
+/* allocate osa new results for samples */
+static RenderResult *new_full_sample_buffers(Render *re, ListBase *lb, rcti *partrct, int crop)
+{
+ int a;
+
+ if(re->osa==0)
+ return new_render_result(re, partrct, crop, RR_USEMEM);
+
+ for(a=0; a<re->osa; a++) {
+ RenderResult *rr= new_render_result(re, partrct, crop, RR_USEMEM);
+ BLI_addtail(lb, rr);
+ rr->sample_nr= a;
+ }
+
+ return lb->first;
+}
+
+
+/* the main thread call, renders an entire part */
static void *do_part_thread(void *pa_v)
{
RenderPart *pa= pa_v;
/* need to return nicely all parts on esc */
if(R.test_break()==0) {
- pa->result= new_render_result(&R, &pa->disprect, pa->crop, RR_USEMEM);
+
+ if(!R.sss_points && (R.r.scemode & R_FULL_SAMPLE))
+ pa->result= new_full_sample_buffers(&R, &pa->fullresult, &pa->disprect, pa->crop);
+ else
+ pa->result= new_render_result(&R, &pa->disprect, pa->crop, RR_USEMEM);
if(R.sss_points)
zbufshade_sss_tile(pa);
@@ -1190,8 +1261,13 @@ static void *do_part_thread(void *pa_v)
zbufshade_tile(pa);
/* merge too on break! */
- if(R.result->exrhandle)
- save_render_result_tile(&R, pa);
+ if(R.result->exrhandle) {
+ RenderResult *rr, *rrpart;
+
+ for(rr= R.result, rrpart= pa->result; rr && rrpart; rr= rr->next, rrpart= rrpart->next)
+ save_render_result_tile(rr, rrpart);
+
+ }
else if(render_display_draw_enabled(&R))
merge_render_result(R.result, pa->result);
}
@@ -1365,33 +1441,54 @@ static void print_part_stats(Render *re, RenderPart *pa)
re->i.infostr= NULL;
}
+/* make osa new results for samples */
+static RenderResult *new_full_sample_buffers_exr(Render *re)
+{
+ int a;
+
+ for(a=0; a<re->osa; a++) {
+ RenderResult *rr= new_render_result(re, &re->disprect, 0, 1);
+ BLI_addtail(&re->fullresult, rr);
+ rr->sample_nr= a;
+ }
+
+ return re->fullresult.first;
+}
+
static void threaded_tile_processor(Render *re)
{
ListBase threads;
RenderPart *pa, *nextpa;
- RenderResult *rr;
rctf viewplane= re->viewplane;
int rendering=1, counter= 1, drawtimer=0, hasdrawn, minx=0;
- /* first step; the entire render result, or prepare exr buffer saving */
+ /* first step; free the entire render result, make new, and/or prepare exr buffer saving */
RE_FreeRenderResult(re->result);
- rr= re->result= new_render_result(re, &re->disprect, 0, re->r.scemode & R_EXR_TILE_FILE);
- if(rr==NULL)
+ if(re->sss_points)
+ re->result= new_render_result(re, &re->disprect, 0, 0);
+ else if(re->r.scemode & R_FULL_SAMPLE)
+ re->result= new_full_sample_buffers_exr(re);
+ else
+ re->result= new_render_result(re, &re->disprect, 0, re->r.scemode & R_EXR_TILE_FILE);
+
+ if(re->result==NULL)
return;
+
/* warning; no return here without closing exr file */
-// if(re->re->test_break())
-// return;
initparts(re);
- if(rr->exrhandle) {
+ if(re->result->exrhandle) {
+ RenderResult *rr;
char str[FILE_MAX];
- render_unique_exr_name(re, str);
+ for(rr= re->result; rr; rr= rr->next) {
+ render_unique_exr_name(re, str, rr->sample_nr);
- printf("write exr tmp file, %dx%d, %s\n", rr->rectx, rr->recty, str);
- IMB_exrtile_begin_write(rr->exrhandle, str, rr->rectx, rr->recty, rr->rectx/re->xparts, rr->recty/re->yparts);
+ printf("write exr tmp file, %dx%d, %s\n", rr->rectx, rr->recty, str);
+ IMB_exrtile_begin_write(rr->exrhandle, str, 0, rr->rectx, rr->recty, re->partx, re->party);
+ }
}
BLI_init_threads(&threads, do_part_thread, re->r.threads);
@@ -1446,7 +1543,7 @@ static void threaded_tile_processor(Render *re)
re->display_draw(pa->result, NULL);
print_part_stats(re, pa);
- RE_FreeRenderResult(pa->result);
+ free_render_result(&pa->fullresult, pa->result);
pa->result= NULL;
re->i.partsdone++;
hasdrawn= 1;
@@ -1470,11 +1567,20 @@ static void threaded_tile_processor(Render *re)
}
- if(rr->exrhandle) {
+ if(re->result->exrhandle) {
+ RenderResult *rr;
+
save_empty_result_tiles(re);
- IMB_exr_close(rr->exrhandle);
- rr->exrhandle= NULL;
- read_render_result(re);
+
+ for(rr= re->result; rr; rr= rr->next) {
+ IMB_exr_close(rr->exrhandle);
+ rr->exrhandle= NULL;
+ }
+
+ free_render_result(&re->fullresult, re->result);
+ re->result= NULL;
+
+ read_render_result(re, 0);
}
/* unset threadsafety */
@@ -1492,14 +1598,16 @@ void RE_TileProcessor(Render *re, int firsttile, int threaded)
re->i.partsdone= firsttile;
- re->i.starttime= PIL_check_seconds_timer();
+ if(!re->sss_points)
+ re->i.starttime= PIL_check_seconds_timer();
if(threaded)
threaded_tile_processor(re);
else
render_tile_processor(re, firsttile);
- re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
+ if(!re->sss_points)
+ re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
re->stats_draw(&re->i);
}
@@ -1722,7 +1830,8 @@ static void load_backbuffer(Render *re)
char name[256];
strcpy(name, re->r.backbuf);
- BLI_convertstringcode(name, G.sce, re->r.cfra);
+ BLI_convertstringcode(name, G.sce);
+ BLI_convertstringframe(name, re->r.cfra);
if(re->backbuf) {
re->backbuf->id.us--;
@@ -1778,6 +1887,7 @@ static void do_render_fields_blur_3d(Render *re)
re->result->tilerect= re->disprect;
/* this copying sequence could become function? */
+ /* weak is: it chances disprect from border */
re->disprect.xmin= re->disprect.ymin= 0;
re->disprect.xmax= re->winx;
re->disprect.ymax= re->winy;
@@ -1807,14 +1917,18 @@ static void do_render_fields_blur_3d(Render *re)
static void render_scene(Render *re, Scene *sce, int cfra)
{
Render *resc= RE_NewRender(sce->id.name);
+ int winx= re->winx, winy= re->winy;
sce->r.cfra= cfra;
- /* initial setup */
- RE_InitState(resc, &sce->r, re->winx, re->winy, &re->disprect);
+ /* exception: scene uses own size (unfinished code) */
+ if(0) {
+ winx= (sce->r.size*sce->r.xsch)/100;
+ winy= (sce->r.size*sce->r.ysch)/100;
+ }
- /* this to enable this scene to create speed vectors */
- resc->r.scemode |= R_DOCOMP;
+ /* initial setup */
+ RE_InitState(resc, re, &sce->r, winx, winy, &re->disprect);
/* still unsure entity this... */
resc->scene= sce;
@@ -1830,10 +1944,15 @@ static void render_scene(Render *re, Scene *sce, int cfra)
do_render_fields_blur_3d(resc);
}
-static void ntree_render_scenes(Render *re)
+static void tag_scenes_for_render(Render *re)
{
bNode *node;
- int cfra= re->scene->r.cfra;
+ Scene *sce;
+
+ for(sce= G.main->scene.first; sce; sce= sce->id.next)
+ sce->id.flag &= ~LIB_DOIT;
+
+ re->scene->id.flag |= LIB_DOIT;
if(re->scene->nodetree==NULL) return;
@@ -1843,12 +1962,21 @@ static void ntree_render_scenes(Render *re)
if(node->id) {
if(node->id != (ID *)re->scene)
node->id->flag |= LIB_DOIT;
- else
- node->id->flag &= ~LIB_DOIT;
}
}
}
+}
+
+static void ntree_render_scenes(Render *re)
+{
+ bNode *node;
+ int cfra= re->scene->r.cfra;
+
+ if(re->scene->nodetree==NULL) return;
+
+ tag_scenes_for_render(re);
+
/* now foreach render-result node tagged we do a full render */
/* results are stored in a way compisitor will find it */
for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
@@ -1894,6 +2022,115 @@ static void render_composit_stats(char *str)
R.i.infostr= NULL;
}
+
+/* reads all buffers, calls optional composite, merges in first result->rectf */
+static void do_merge_fullsample(Render *re, bNodeTree *ntree)
+{
+ float *rectf, filt[3][3];
+ int sample;
+
+ /* filtmask needs it */
+ R= *re;
+
+ /* we accumulate in here */
+ rectf= MEM_mapallocN(re->rectx*re->recty*sizeof(float)*4, "fullsample rgba");
+
+ for(sample=0; sample<re->r.osa; sample++) {
+ RenderResult rres;
+ int x, y, mask;
+
+ /* set all involved renders on the samplebuffers (first was done by render itself) */
+ /* also function below assumes this */
+ if(sample) {
+ Render *re1;
+
+ tag_scenes_for_render(re);
+ for(re1= RenderList.first; re1; re1= re1->next) {
+ if(re1->scene->id.flag & LIB_DOIT)
+ if(re1->r.scemode & R_FULL_SAMPLE)
+ read_render_result(re1, sample);
+ }
+ }
+
+ /* composite */
+ if(ntree) {
+ ntreeCompositTagRender(re->scene);
+ ntreeCompositTagAnimated(ntree);
+
+ ntreeCompositExecTree(ntree, &re->r, G.background==0);
+ }
+
+ /* ensure we get either composited result or the active layer */
+ RE_GetResultImage(re, &rres);
+
+ /* accumulate with filter, and clip */
+ mask= (1<<sample);
+ mask_array(mask, filt);
+
+ for(y=0; y<re->recty; y++) {
+ float *rf= rectf + 4*y*re->rectx;
+ float *col= rres.rectf + 4*y*re->rectx;
+
+ for(x=0; x<re->rectx; x++, rf+=4, col+=4) {
+ if(col[0]<0.0f) col[0]=0.0f; else if(col[0] > 1.0f) col[0]= 1.0f;
+ if(col[1]<0.0f) col[1]=0.0f; else if(col[1] > 1.0f) col[1]= 1.0f;
+ if(col[2]<0.0f) col[2]=0.0f; else if(col[2] > 1.0f) col[2]= 1.0f;
+
+ add_filt_fmask_coord(filt, col, rf, re->rectx, re->recty, x, y);
+ }
+ }
+
+ /* show stuff */
+ if(sample!=re->osa-1) {
+ /* weak... the display callback wants an active renderlayer pointer... */
+ re->result->renlay= render_get_active_layer(re, re->result);
+ re->display_draw(re->result, NULL);
+ }
+
+ if(re->test_break())
+ break;
+ }
+
+ if(re->result->rectf)
+ MEM_freeN(re->result->rectf);
+ re->result->rectf= rectf;
+}
+
+void RE_MergeFullSample(Render *re, Scene *sce, bNodeTree *ntree)
+{
+ Scene *scene;
+ bNode *node;
+
+ /* first call RE_ReadRenderResult on every renderlayer scene. this creates Render structs */
+
+ /* tag scenes unread */
+ for(scene= G.main->scene.first; scene; scene= scene->id.next)
+ scene->id.flag |= LIB_DOIT;
+
+ for(node= ntree->nodes.first; node; node= node->next) {
+ if(node->type==CMP_NODE_R_LAYERS) {
+ Scene *nodescene= (Scene *)node->id;
+
+ if(nodescene==NULL) nodescene= sce;
+ if(nodescene->id.flag & LIB_DOIT) {
+ nodescene->r.mode |= R_OSA; /* render struct needs tables */
+ RE_ReadRenderResult(sce, nodescene);
+ nodescene->id.flag &= ~LIB_DOIT;
+ }
+ }
+ }
+
+ /* own render result should be read/allocated */
+ if(G.scene->id.flag & LIB_DOIT)
+ RE_ReadRenderResult(G.scene, G.scene);
+
+ /* and now we can draw (result is there) */
+ re->display_init(re->result);
+ re->display_clear(re->result);
+
+ do_merge_fullsample(re, ntree);
+}
+
/* returns fully composited render-result on given time step (in RenderData) */
static void do_render_composite_fields_blur_3d(Render *re)
{
@@ -1913,25 +2150,36 @@ static void do_render_composite_fields_blur_3d(Render *re)
if(re->r.scemode & R_SINGLE_LAYER)
pop_render_result(re);
- if(!re->test_break() && ntree) {
- ntreeCompositTagRender(re->scene);
- ntreeCompositTagAnimated(ntree);
+ if(!re->test_break()) {
- if(re->r.scemode & R_DOCOMP) {
- /* checks if there are render-result nodes that need scene */
- if((re->r.scemode & R_SINGLE_LAYER)==0)
- ntree_render_scenes(re);
-
- if(!re->test_break()) {
- ntree->stats_draw= render_composit_stats;
- ntree->test_break= re->test_break;
- /* in case it was never initialized */
- R.stats_draw= re->stats_draw;
+ if(ntree) {
+ ntreeCompositTagRender(re->scene);
+ ntreeCompositTagAnimated(ntree);
+ }
+
+ if(1 || !(re->r.scemode & R_COMP_RERENDER)) {
+ if(ntree && re->r.scemode & R_DOCOMP) {
+ /* checks if there are render-result nodes that need scene */
+ if((re->r.scemode & R_SINGLE_LAYER)==0)
+ ntree_render_scenes(re);
- ntreeCompositExecTree(ntree, &re->r, G.background==0);
- ntree->stats_draw= NULL;
- ntree->test_break= NULL;
+ if(!re->test_break()) {
+ ntree->stats_draw= render_composit_stats;
+ ntree->test_break= re->test_break;
+ /* in case it was never initialized */
+ R.stats_draw= re->stats_draw;
+
+ if(re->r.scemode & R_FULL_SAMPLE)
+ do_merge_fullsample(re, ntree);
+ else
+ ntreeCompositExecTree(ntree, &re->r, G.background==0);
+
+ ntree->stats_draw= NULL;
+ ntree->test_break= NULL;
+ }
}
+ else if(re->r.scemode & R_FULL_SAMPLE)
+ do_merge_fullsample(re, NULL);
}
}
@@ -2008,7 +2256,7 @@ static void renderresult_stampinfo()
RenderResult rres;
/* this is the basic trick to get the displayed float or char rect from render result */
RE_GetResultImage(RE_GetRender(G.scene->id.name), &rres);
- BKE_stamp_buf((unsigned char *)rres.rect32, rres.rectf, rres.rectx, rres.recty);
+ BKE_stamp_buf((unsigned char *)rres.rect32, rres.rectf, rres.rectx, rres.recty, 4);
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
@@ -2086,14 +2334,26 @@ static int is_rendering_allowed(Render *re)
if(re->r.scemode & R_EXR_TILE_FILE) {
char str[FILE_MAX];
- render_unique_exr_name(re, str);
+ render_unique_exr_name(re, str, 0);
if (BLI_is_writable(str)==0) {
re->error("Can not save render buffers, check the temp default path");
return 0;
}
+ /* no osa + fullsample won't work... */
+ if(re->osa==0)
+ re->r.scemode &= ~R_FULL_SAMPLE;
+
+ /* no fullsample and edge */
+ if((re->r.scemode & R_FULL_SAMPLE) && (re->r.mode & R_EDGE)) {
+ re->error("Full Sample doesn't support Edge Enhance");
+ return 0;
+ }
+
}
+ else
+ re->r.scemode &= ~R_FULL_SAMPLE; /* clear to be sure */
if(re->r.scemode & R_DOCOMP) {
if(re->scene->use_nodes) {
@@ -2152,7 +2412,7 @@ static int is_rendering_allowed(Render *re)
}
/* evaluating scene options for general Blender render */
-static int render_initialize_from_scene(Render *re, Scene *scene)
+static int render_initialize_from_scene(Render *re, Scene *scene, int anim)
{
int winx, winy;
rcti disprect;
@@ -2178,31 +2438,27 @@ static int render_initialize_from_scene(Render *re, Scene *scene)
disprect.ymax= winy;
}
- if(scene->r.scemode & R_EXR_TILE_FILE) {
- int partx= winx/scene->r.xparts, party= winy/scene->r.yparts;
-
- /* stupid exr tiles dont like different sizes */
- if(winx != partx*scene->r.xparts || winy != party*scene->r.yparts) {
- re->error("Sorry... exr tile saving only allowed with equally sized parts");
- return 0;
- }
- if((scene->r.mode & R_FIELDS) && (party & 1)) {
- re->error("Sorry... exr tile saving only allowed with equally sized parts");
- return 0;
- }
+ re->scene= scene;
+
+ /* not too nice, but it survives anim-border render */
+ if(anim) {
+ re->disprect= disprect;
+ return 1;
}
+ /* check all scenes involved */
+ tag_scenes_for_render(re);
+
if(scene->r.scemode & R_SINGLE_LAYER)
push_render_result(re);
- RE_InitState(re, &scene->r, winx, winy, &disprect);
+ RE_InitState(re, NULL, &scene->r, winx, winy, &disprect);
if(!re->ok) /* if an error was printed, abort */
return 0;
/* initstate makes new result, have to send changed tags around */
ntreeCompositTagRender(re->scene);
- re->scene= scene;
if(!is_rendering_allowed(re))
return 0;
@@ -2221,7 +2477,7 @@ void RE_BlenderFrame(Render *re, Scene *scene, int frame)
scene->r.cfra= frame;
- if(render_initialize_from_scene(re, scene)) {
+ if(render_initialize_from_scene(re, scene, 0)) {
do_render_all_options(re);
}
@@ -2301,13 +2557,15 @@ static void do_write_image_or_movie(Render *re, Scene *scene, bMovieHandle *mh)
}
/* saves images to disk */
-void RE_BlenderAnim(Render *re, Scene *scene, int sfra, int efra)
+void RE_BlenderAnim(Render *re, Scene *scene, int sfra, int efra, int tfra)
{
bMovieHandle *mh= BKE_get_movie_handle(scene->r.imtype);
+ unsigned int lay;
int cfrao= scene->r.cfra;
+ int nfra;
- /* do not call for each frame, it initializes & pops output window */
- if(!render_initialize_from_scene(re, scene))
+ /* do not fully call for each frame, it initializes & pops output window */
+ if(!render_initialize_from_scene(re, scene, 0))
return;
/* ugly global still... is to prevent renderwin events and signal subsurfs etc to make full resol */
@@ -2333,17 +2591,58 @@ void RE_BlenderAnim(Render *re, Scene *scene, int sfra, int efra)
}
}
} else {
- for(scene->r.cfra= sfra;
- scene->r.cfra<=efra; scene->r.cfra++) {
+ for(nfra= sfra, scene->r.cfra= sfra; scene->r.cfra<=efra; scene->r.cfra++) {
+ char name[FILE_MAX];
+
+ /* only border now, todo: camera lens. (ton) */
+ render_initialize_from_scene(re, scene, 1);
+
+ if(nfra!=scene->r.cfra) {
+ /*
+ * Skip this frame, but update for physics and particles system.
+ * From convertblender.c:
+ * in localview, lamps are using normal layers, objects only local bits.
+ */
+ if(scene->lay & 0xFF000000)
+ lay= scene->lay & 0xFF000000;
+ else
+ lay= scene->lay;
+
+ scene_update_for_newframe(scene, lay);
+ continue;
+ }
+ else
+ nfra+= tfra;
+
+ if (scene->r.mode & (R_NO_OVERWRITE | R_TOUCH) ) {
+ BKE_makepicstring(name, scene->r.pic, scene->r.cfra, scene->r.imtype);
+ }
+
+ if (scene->r.mode & R_NO_OVERWRITE && BLI_exist(name)) {
+ printf("skipping existing frame \"%s\"\n", name);
+ continue;
+ }
+ if (scene->r.mode & R_TOUCH && !BLI_exist(name)) {
+ BLI_make_existing_file(name); /* makes the dir if its not there */
+ BLI_touch(name);
+ }
+
re->r.cfra= scene->r.cfra; /* weak.... */
-
+
do_render_all_options(re);
-
+
if(re->test_break() == 0) {
do_write_image_or_movie(re, scene, mh);
}
- if(G.afbreek==1) break;
+ if(G.afbreek==1) {
+ /* remove touched file */
+ if (scene->r.mode & R_TOUCH && BLI_exist(name) && BLI_filepathsize(name) == 0) {
+ BLI_delete(name, 0, 0);
+ }
+
+ break;
+ }
}
}
@@ -2359,7 +2658,7 @@ void RE_BlenderAnim(Render *re, Scene *scene, int sfra, int efra)
/* note; repeated win/disprect calc... solve that nicer, also in compo */
-/* only temp file! */
+/* only the temp file! */
void RE_ReadRenderResult(Scene *scene, Scene *scenode)
{
Render *re;
@@ -2387,17 +2686,32 @@ void RE_ReadRenderResult(Scene *scene, Scene *scenode)
if(scenode)
scene= scenode;
- re= RE_NewRender(scene->id.name);
- RE_InitState(re, &scene->r, winx, winy, &disprect);
+ /* get render: it can be called from UI with draw callbacks */
+ re= RE_GetRender(scene->id.name);
+ if(re==NULL)
+ re= RE_NewRender(scene->id.name);
+ RE_InitState(re, NULL, &scene->r, winx, winy, &disprect);
re->scene= scene;
- read_render_result(re);
+ read_render_result(re, 0);
}
void RE_set_max_threads(int threads)
{
- if(threads>0 && threads<=BLENDER_MAX_THREADS)
+ if (threads==0) {
+ commandline_threads = BLI_system_thread_count();
+ } else if(threads>=1 && threads<=BLENDER_MAX_THREADS) {
commandline_threads= threads;
- else
+ } else {
printf("Error, threads has to be in range 1-%d\n", BLENDER_MAX_THREADS);
+ }
+}
+
+void RE_init_threadcount(Render *re)
+{
+ if(commandline_threads >= 1) { /* only set as an arg in background mode */
+ re->r.threads= MIN2(commandline_threads, BLENDER_MAX_THREADS);
+ } else if ((re->r.mode & R_FIXED_THREADS)==0 || commandline_threads == 0) { /* Automatic threads */
+ re->r.threads = BLI_system_thread_count();
+ }
}
diff --git a/source/blender/render/intern/source/pixelblending.c b/source/blender/render/intern/source/pixelblending.c
index 119cceaf3c2..0e453d461ab 100644
--- a/source/blender/render/intern/source/pixelblending.c
+++ b/source/blender/render/intern/source/pixelblending.c
@@ -31,6 +31,7 @@
*/
#include <math.h>
+#include <string.h>
/* global includes */
#include "BLI_arithb.h"
@@ -91,15 +92,6 @@ void addAlphaOverFloat(float *dest, float *source)
void addAlphaUnderFloat(float *dest, float *source)
{
float mul;
-
- if( (-RE_EMPTY_COLOR_FLOAT < dest[3])
- && (dest[3] < RE_EMPTY_COLOR_FLOAT) ) {
- dest[0] = source[0];
- dest[1] = source[1];
- dest[2] = source[2];
- dest[3] = source[3];
- return;
- }
mul= 1.0 - dest[3];
@@ -212,6 +204,121 @@ void add_filt_fmask(unsigned int mask, float *col, float *rowbuf, int row_w)
}
}
+
+void mask_array(unsigned int mask, float filt[][3])
+{
+ float **fmask1= R.samples->fmask1, **fmask2=R.samples->fmask2;
+ unsigned int maskand= (mask & 255);
+ unsigned int maskshift= (mask >>8);
+ int a, j;
+
+ for(j=2; j>=0; j--) {
+
+ a= j;
+
+ filt[2][2-j]= *(fmask1[a] +maskand) + *(fmask2[a] +maskshift);
+
+ a+=3;
+
+ filt[1][2-j]= *(fmask1[a] +maskand) + *(fmask2[a] +maskshift);
+
+ a+=3;
+
+ filt[0][2-j]= *(fmask1[a] +maskand) + *(fmask2[a] +maskshift);
+ }
+}
+
+
+/*
+
+index ordering, scanline based:
+
+ --- --- ---
+| 2,0 | 2,1 | 2,2 |
+ --- --- ---
+| 1,0 | 1,1 | 1,2 |
+ --- --- ---
+| 0,0 | 0,1 | 0,2 |
+ --- --- ---
+*/
+
+void add_filt_fmask_coord(float filt[][3], float *col, float *rowbuf, int row_w, int col_h, int x, int y)
+{
+ float *fpoin[3][3];
+ float val, r, g, b, al, lfilt[3][3];
+
+ r= col[0];
+ g= col[1];
+ b= col[2];
+ al= col[3];
+
+ memcpy(lfilt, filt, sizeof(lfilt));
+
+ fpoin[0][1]= rowbuf-4*row_w;
+ fpoin[1][1]= rowbuf;
+ fpoin[2][1]= rowbuf+4*row_w;
+
+ fpoin[0][0]= fpoin[0][1] - 4;
+ fpoin[1][0]= fpoin[1][1] - 4;
+ fpoin[2][0]= fpoin[2][1] - 4;
+
+ fpoin[0][2]= fpoin[0][1] + 4;
+ fpoin[1][2]= fpoin[1][1] + 4;
+ fpoin[2][2]= fpoin[2][1] + 4;
+
+ if(y==0) {
+ fpoin[0][0]= fpoin[1][0];
+ fpoin[0][1]= fpoin[1][1];
+ fpoin[0][2]= fpoin[1][2];
+ /* filter needs the opposite value yes! */
+ lfilt[0][0]= filt[2][0];
+ lfilt[0][1]= filt[2][1];
+ lfilt[0][2]= filt[2][2];
+ }
+ else if(y==col_h-1) {
+ fpoin[2][0]= fpoin[1][0];
+ fpoin[2][1]= fpoin[1][1];
+ fpoin[2][2]= fpoin[1][2];
+
+ lfilt[2][0]= filt[0][0];
+ lfilt[2][1]= filt[0][1];
+ lfilt[2][2]= filt[0][2];
+ }
+
+ if(x==0) {
+ fpoin[2][0]= fpoin[2][1];
+ fpoin[1][0]= fpoin[1][1];
+ fpoin[0][0]= fpoin[0][1];
+
+ lfilt[2][0]= filt[2][2];
+ lfilt[1][0]= filt[1][2];
+ lfilt[0][0]= filt[0][2];
+ }
+ else if(x==row_w-1) {
+ fpoin[2][2]= fpoin[2][1];
+ fpoin[1][2]= fpoin[1][1];
+ fpoin[0][2]= fpoin[0][1];
+
+ lfilt[2][2]= filt[2][0];
+ lfilt[1][2]= filt[1][0];
+ lfilt[0][2]= filt[0][0];
+ }
+
+
+ /* loop unroll */
+#define MASKFILT(i, j) val= lfilt[i][j]; if(val!=0.0f) {float *fp= fpoin[i][j]; fp[0]+= val*r; fp[1]+= val*g; fp[2]+= val*b; fp[3]+= val*al; }
+
+ MASKFILT(0, 0)
+ MASKFILT(0, 1)
+ MASKFILT(0, 2)
+ MASKFILT(1, 0)
+ MASKFILT(1, 1)
+ MASKFILT(1, 2)
+ MASKFILT(2, 0)
+ MASKFILT(2, 1)
+ MASKFILT(2, 2)
+}
+
void add_filt_fmask_pixsize(unsigned int mask, float *in, float *rowbuf, int row_w, int pixsize)
{
/* calc the value of mask */
diff --git a/source/blender/render/intern/source/pixelshading.c b/source/blender/render/intern/source/pixelshading.c
index cffed99c738..60723963af9 100644
--- a/source/blender/render/intern/source/pixelshading.c
+++ b/source/blender/render/intern/source/pixelshading.c
@@ -24,7 +24,9 @@
* ***** END GPL LICENSE BLOCK *****
*/
+#include <float.h>
#include <math.h>
+#include <string.h>
#include "BLI_arithb.h"
/* External modules: */
@@ -43,6 +45,7 @@
#include "BKE_image.h"
#include "BKE_global.h"
+#include "BKE_material.h"
#include "BKE_texture.h"
#include "BKE_utildefines.h"
@@ -55,6 +58,7 @@
#include "rendercore.h"
#include "shadbuf.h"
#include "pixelshading.h"
+#include "sunsky.h"
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* defined in pipeline.c, is hardcopy of active dynamic allocated Render */
@@ -130,9 +134,15 @@ static void render_lighting_halo(HaloRen *har, float *colf)
if(lar->mode & LA_TEXTURE) {
ShadeInput shi;
+
+ /* Warning, This is not that nice, and possibly a bit slow,
+ however some variables were not initialized properly in, unless using shade_input_initialize(...), we need to do a memset */
+ memset(&shi, 0, sizeof(ShadeInput));
+ /* end warning! - Campbell */
+
VECCOPY(shi.co, rco);
shi.osatex= 0;
- do_lamp_tex(lar, lv, &shi, lacol);
+ do_lamp_tex(lar, lv, &shi, lacol, LA_TEXTURE);
}
if(lar->type==LA_SPOT) {
@@ -175,7 +185,7 @@ static void render_lighting_halo(HaloRen *har, float *colf)
inp= vn[0]*lv[0] + vn[1]*lv[1] + vn[2]*lv[2];
if(inp>0.0) {
/* testshadowbuf==0.0 : 100% shadow */
- shadfac = testshadowbuf(lar->shb, rco, dco, dco, inp);
+ shadfac = testshadowbuf(&R, lar->shb, rco, dco, dco, inp, 0.0f);
if( shadfac>0.0 ) {
shadfac*= inp*soft*lar->energy;
ir -= shadfac;
@@ -212,7 +222,7 @@ static void render_lighting_halo(HaloRen *har, float *colf)
if(i> -0.41) { /* heuristic valua! */
shadfac= 1.0;
if(lar->shb) {
- shadfac = testshadowbuf(lar->shb, rco, dco, dco, inp);
+ shadfac = testshadowbuf(&R, lar->shb, rco, dco, dco, inp, 0.0f);
if(shadfac==0.0) continue;
i*= shadfac;
}
@@ -236,8 +246,36 @@ static void render_lighting_halo(HaloRen *har, float *colf)
}
+/**
+ * Converts a halo z-buffer value to distance from the camera's near plane
+ * @param z The z-buffer value to convert
+ * @return a distance from the camera's near plane in blender units
+ */
+static float haloZtoDist(int z)
+{
+ float zco = 0;
-void shadeHaloFloat(HaloRen *har, float *col, int zz,
+ if(z >= 0x7FFFFF)
+ return 10e10;
+ else {
+ zco = (float)z/(float)0x7FFFFF;
+ if(R.r.mode & R_ORTHO)
+ return (R.winmat[3][2] - zco*R.winmat[3][3])/(R.winmat[2][2]);
+ else
+ return (R.winmat[3][2])/(R.winmat[2][2] - R.winmat[2][3]*zco);
+ }
+}
+
+/**
+ * @param col (float[4]) Store the rgb color here (with alpha)
+ * The alpha is used to blend the color to the background
+ * color_new = (1-alpha)*color_background + color
+ * @param zz The current zbuffer value at the place of this pixel
+ * @param dist Distance of the pixel from the center of the halo squared. Given in pixels
+ * @param xn The x coordinate of the pixel relaticve to the center of the halo. given in pixels
+ * @param yn The y coordinate of the pixel relaticve to the center of the halo. given in pixels
+ */
+int shadeHaloFloat(HaloRen *har, float *col, int zz,
float dist, float xn, float yn, short flarec)
{
/* fill in col */
@@ -256,12 +294,40 @@ void shadeHaloFloat(HaloRen *har, float *col, int zz,
}
else alpha= har->alfa;
- if(alpha==0.0) {
- col[0] = 0.0;
- col[1] = 0.0;
- col[2] = 0.0;
- col[3] = 0.0;
- return;
+ if(alpha==0.0)
+ return 0;
+
+ /* soften the halo if it intersects geometry */
+ if(har->mat && har->mat->mode & MA_HALO_SOFT) {
+ float segment_length, halo_depth, distance_from_z, visible_depth, soften;
+
+ /* calculate halo depth */
+ segment_length= har->hasize*sasqrt(1.0f - dist/(har->rad*har->rad));
+ halo_depth= 2.0f*segment_length;
+
+ if(halo_depth < FLT_EPSILON)
+ return 0;
+
+ /* calculate how much of this depth is visible */
+ distance_from_z = haloZtoDist(zz) - haloZtoDist(har->zs);
+ visible_depth = halo_depth;
+ if(distance_from_z < segment_length) {
+ soften= (segment_length + distance_from_z)/halo_depth;
+
+ /* apply softening to alpha */
+ if(soften < 1.0f)
+ alpha *= soften;
+ if(alpha <= 0.0f)
+ return 0;
+ }
+ }
+ else {
+ /* not a soft halo. use the old softening code */
+ /* halo being intersected? */
+ if(har->zs> zz-har->zd) {
+ t= ((float)(zz-har->zs))/(float)har->zd;
+ alpha*= sqrt(sqrt(t));
+ }
}
radist= sqrt(dist);
@@ -359,21 +425,10 @@ void shadeHaloFloat(HaloRen *har, float *col, int zz,
if(ster<1.0) dist*= sqrt(ster);
}
}
-
- /* halo being intersected? */
- if(har->zs> zz-har->zd) {
- t= ((float)(zz-har->zs))/(float)har->zd;
- alpha*= sqrt(sqrt(t));
- }
/* disputable optimize... (ton) */
- if(dist<=0.00001) {
- col[0] = 0.0;
- col[1] = 0.0;
- col[2] = 0.0;
- col[3] = 0.0;
- return;
- }
+ if(dist<=0.00001)
+ return 0;
dist*= alpha;
ringf*= dist;
@@ -434,6 +489,8 @@ void shadeHaloFloat(HaloRen *har, float *col, int zz,
/* alpha requires clip, gives black dots */
if(col[3] > 1.0f)
col[3]= 1.0f;
+
+ return 1;
}
/* ------------------------------------------------------------------------- */
@@ -512,13 +569,48 @@ void shadeSkyView(float *colf, float *rco, float *view, float *dxyview)
}
}
+/* shade sky according to sun lamps, all parameters are like shadeSkyView except sunsky*/
+void shadeSunView(float *colf, float *view)
+{
+ GroupObject *go;
+ LampRen *lar;
+ float sview[3];
+ int do_init= 1;
+
+ for(go=R.lights.first; go; go= go->next) {
+ lar= go->lampren;
+ if(lar->type==LA_SUN && lar->sunsky && (lar->sunsky->effect_type & LA_SUN_EFFECT_SKY)){
+ float sun_collector[3];
+ float colorxyz[3];
+
+ if(do_init) {
+
+ VECCOPY(sview, view);
+ Normalize(sview);
+ MTC_Mat3MulVecfl(R.imat, sview);
+ if (sview[2] < 0.0)
+ sview[2] = 0.0;
+ Normalize(sview);
+ do_init= 0;
+ }
+
+ GetSkyXYZRadiancef(lar->sunsky, sview, colorxyz);
+ xyz_to_rgb(colorxyz[0], colorxyz[1], colorxyz[2], &sun_collector[0], &sun_collector[1], &sun_collector[2],
+ lar->sunsky->sky_colorspace);
+
+ ramp_blend(lar->sunsky->skyblendtype, colf, colf+1, colf+2, lar->sunsky->skyblendfac, sun_collector);
+ }
+ }
+}
+
+
/*
Stuff the sky color into the collector.
*/
void shadeSkyPixel(float *collector, float fx, float fy)
{
float view[3], dxyview[2];
-
+
/*
The rules for sky:
1. Draw an image, if a background image was provided. Stop
@@ -530,7 +622,6 @@ void shadeSkyPixel(float *collector, float fx, float fy)
/* 1. Do a backbuffer image: */
if(R.r.bufflag & 1) {
fillBackgroundImage(collector, fx, fy);
- return;
}
else if((R.wrld.skytype & (WO_SKYBLEND+WO_SKYTEX))==0) {
/* 2. solid color */
@@ -565,7 +656,20 @@ void shadeSkyPixel(float *collector, float fx, float fy)
shadeSkyView(collector, NULL, view, dxyview);
collector[3] = 0.0f;
}
+
+ calc_view_vector(view, fx, fy);
+ shadeSunView(collector, view);
}
+/* aerial perspective */
+void shadeAtmPixel(struct SunSky *sunsky, float *collector, float fx, float fy, float distance)
+{
+ float view[3];
+
+ calc_view_vector(view, fx, fy);
+ Normalize(view);
+ /*MTC_Mat3MulVecfl(R.imat, view);*/
+ AtmospherePixleShader(sunsky, view, distance, collector);
+}
/* eof */
diff --git a/source/blender/render/intern/source/rayshade.c b/source/blender/render/intern/source/rayshade.c
index 69e90a7537c..f822d41bb85 100644
--- a/source/blender/render/intern/source/rayshade.c
+++ b/source/blender/render/intern/source/rayshade.c
@@ -40,8 +40,9 @@
#include "BKE_utildefines.h"
#include "BLI_arithb.h"
-#include "BLI_rand.h"
+#include "BLI_blenlib.h"
#include "BLI_jitter.h"
+#include "BLI_rand.h"
#include "PIL_time.h"
@@ -77,15 +78,21 @@ static void vlr_face_coords(RayFace *face, float **v1, float **v2, float **v3, f
*v4 = (vlr->v4)? vlr->v4->co: NULL;
}
-static int vlr_check_intersect(Isect *is, RayFace *face)
+static int vlr_check_intersect(Isect *is, int ob, RayFace *face)
{
+ ObjectInstanceRen *obi= RAY_OBJECT_GET((Render*)is->userdata, ob);
VlakRen *vlr = (VlakRen*)face;
+ /* for baking selected to active non-traceable materials might still
+ * be in the raytree */
+ if(!(vlr->mat->mode & MA_TRACEBLE))
+ return 0;
+
/* I know... cpu cycle waste, might do smarter once */
if(is->mode==RE_RAY_MIRROR)
return !(vlr->mat->mode & MA_ONLYCAST);
else
- return (is->lay & vlr->lay);
+ return (is->lay & obi->lay);
}
static float *vlr_get_transform(void *userdata, int i)
@@ -110,7 +117,7 @@ void makeraytree(Render *re)
VlakRen *vlr= NULL;
float min[3], max[3], co1[3], co2[3], co3[3], co4[3];
double lasttime= PIL_check_seconds_timer();
- int v, totface = 0;
+ int v, totv = 0, totface = 0;
INIT_MINMAX(min, max);
@@ -124,7 +131,8 @@ void makeraytree(Render *re)
for(v=0;v<obr->totvlak;v++) {
if((v & 255)==0) vlr= obr->vlaknodes[v>>8].vlak;
else vlr++;
- if(vlr->mat->mode & MA_TRACEBLE) {
+ /* baking selected to active needs non-traceable too */
+ if((re->flag & R_BAKE_TRACE) || (vlr->mat->mode & MA_TRACEBLE)) {
if((vlr->mat->mode & MA_WIRE)==0) {
VECCOPY(co1, vlr->v1->co);
VECCOPY(co2, vlr->v2->co);
@@ -167,7 +175,7 @@ void makeraytree(Render *re)
if(re->excludeob && obr->ob == re->excludeob)
continue;
- for(v=0; v<obr->totvlak; v++) {
+ for(v=0; v<obr->totvlak; v++, totv++) {
if((v & 255)==0) {
double time= PIL_check_seconds_timer();
@@ -176,7 +184,7 @@ void makeraytree(Render *re)
break;
if(time-lasttime>1.0f) {
char str[32];
- sprintf(str, "Filling Octree: %d", v);
+ sprintf(str, "Filling Octree: %d", totv);
re->i.infostr= str;
re->stats_draw(&re->i);
re->i.infostr= NULL;
@@ -185,7 +193,7 @@ void makeraytree(Render *re)
}
else vlr++;
- if(vlr->mat->mode & MA_TRACEBLE)
+ if((re->flag & R_BAKE_TRACE) || (vlr->mat->mode & MA_TRACEBLE))
if((vlr->mat->mode & MA_WIRE)==0)
RE_ray_tree_add_face(re->raytree, RAY_OBJECT_SET(re, obi), vlr);
}
@@ -255,7 +263,12 @@ static void shade_ray(Isect *is, ShadeInput *shi, ShadeResult *shr)
shade_input_set_shade_texco(shi);
if(is->mode==RE_RAY_SHADOW_TRA)
- shade_color(shi, shr);
+ if(shi->mat->nodetree && shi->mat->use_nodes) {
+ ntreeShaderExecTree(shi->mat->nodetree, shi, shr);
+ shi->mat= vlr->mat; /* shi->mat is being set in nodetree */
+ }
+ else
+ shade_color(shi, shr);
else {
if(shi->mat->nodetree && shi->mat->use_nodes) {
ntreeShaderExecTree(shi->mat->nodetree, shi, shr);
@@ -376,7 +389,7 @@ static float shade_by_transmission(Isect *is, ShadeInput *shi, ShadeResult *shr)
static void ray_fadeout_endcolor(float *col, ShadeInput *origshi, ShadeInput *shi, ShadeResult *shr, Isect *isec, float *vec)
{
- /* un-intersected rays get either rendered material colour or sky colour */
+ /* un-intersected rays get either rendered material color or sky color */
if (origshi->mat->fadeto_mir == MA_RAYMIR_FADETOMAT) {
VECCOPY(col, shr->combined);
} else if (origshi->mat->fadeto_mir == MA_RAYMIR_FADETOSKY) {
@@ -384,12 +397,13 @@ static void ray_fadeout_endcolor(float *col, ShadeInput *origshi, ShadeInput *sh
Normalize(shi->view);
shadeSkyView(col, isec->start, shi->view, NULL);
+ shadeSunView(col, shi->view);
}
}
static void ray_fadeout(Isect *is, ShadeInput *shi, float *col, float *blendcol, float dist_mir)
{
- /* if fading out, linear blend against fade colour */
+ /* if fading out, linear blend against fade color */
float blendfac;
blendfac = 1.0 - VecLenf(shi->co, is->start)/dist_mir;
@@ -409,6 +423,11 @@ static void traceray(ShadeInput *origshi, ShadeResult *origshr, short depth, flo
float ref[3], maxsize=RE_ray_tree_max_size(R.raytree);
float dist_mir = origshi->mat->dist_mir;
+ /* Warning, This is not that nice, and possibly a bit slow for every ray,
+ however some variables were not initialized properly in, unless using shade_input_initialize(...), we need to do a memset */
+ memset(&shi, 0, sizeof(ShadeInput));
+ /* end warning! - Campbell */
+
VECCOPY(isec.start, start);
if (dist_mir > 0.0) {
isec.end[0]= start[0]+dist_mir*vec[0];
@@ -430,13 +449,13 @@ static void traceray(ShadeInput *origshi, ShadeResult *origshr, short depth, flo
shi.osatex= origshi->osatex;
shi.depth= 1; /* only used to indicate tracing */
shi.thread= origshi->thread;
- shi.sample= 0;
+ //shi.sample= 0; // memset above, so dont need this
shi.xs= origshi->xs;
shi.ys= origshi->ys;
shi.lay= origshi->lay;
shi.passflag= SCE_PASS_COMBINED; /* result of tracing needs no pass info */
shi.combinedflag= 0xFFFFFF; /* ray trace does all options */
- shi.do_preview= 0;
+ //shi.do_preview= 0; // memset above, so dont need this
shi.light_override= origshi->light_override;
shi.mat_override= origshi->mat_override;
@@ -531,8 +550,8 @@ static void traceray(ShadeInput *origshi, ShadeResult *origshr, short depth, flo
if (dist_mir > 0.0) {
float blendcol[3];
- /* max ray distance set, but found an intersection, so fade this colour
- * out towards the sky/material colour for a smooth transition */
+ /* max ray distance set, but found an intersection, so fade this color
+ * out towards the sky/material color for a smooth transition */
ray_fadeout_endcolor(blendcol, origshi, &shi, origshr, &isec, vec);
ray_fadeout(&isec, &shi, col, blendcol, dist_mir);
}
@@ -615,24 +634,27 @@ void init_jitter_plane(LampRen *lar)
/* at least 4, or max threads+1 tables */
if(BLENDER_MAX_THREADS < 4) x= 4;
else x= BLENDER_MAX_THREADS+1;
- fp= lar->jitter= MEM_mallocN(x*tot*2*sizeof(float), "lamp jitter tab");
-
- /* set per-lamp fixed seed */
- BLI_srandom(tot);
-
- /* fill table with random locations, area_size large */
- for(x=0; x<tot; x++, fp+=2) {
- fp[0]= (BLI_frand()-0.5)*lar->area_size;
- fp[1]= (BLI_frand()-0.5)*lar->area_sizey;
- }
+ fp= lar->jitter= MEM_callocN(x*tot*2*sizeof(float), "lamp jitter tab");
- while(iter--) {
- fp= lar->jitter;
- for(x=tot; x>0; x--, fp+=2) {
- DP_energy(lar->jitter, fp, tot, lar->area_size, lar->area_sizey);
+ /* if 1 sample, we leave table to be zero's */
+ if(tot>1) {
+
+ /* set per-lamp fixed seed */
+ BLI_srandom(tot);
+
+ /* fill table with random locations, area_size large */
+ for(x=0; x<tot; x++, fp+=2) {
+ fp[0]= (BLI_frand()-0.5)*lar->area_size;
+ fp[1]= (BLI_frand()-0.5)*lar->area_sizey;
}
- }
-
+
+ while(iter--) {
+ fp= lar->jitter;
+ for(x=tot; x>0; x--, fp+=2) {
+ DP_energy(lar->jitter, fp, tot, lar->area_size, lar->area_sizey);
+ }
+ }
+ }
/* create the dithered tables (could just check lamp type!) */
jitter_plane_offset(lar->jitter, lar->jitter+2*tot, tot, lar->area_size, lar->area_sizey, 0.5f, 0.0f);
jitter_plane_offset(lar->jitter, lar->jitter+4*tot, tot, lar->area_size, lar->area_sizey, 0.5f, 0.5f);
@@ -715,10 +737,10 @@ static void hammersley_create(double *out, int n)
}
}
-struct QMCSampler *QMC_initSampler(int type, int tot)
+static struct QMCSampler *QMC_initSampler(int type, int tot)
{
- QMCSampler *qsa = MEM_mallocN(sizeof(QMCSampler), "qmc sampler");
- qsa->samp2d = MEM_mallocN(2*sizeof(double)*tot, "qmc sample table");
+ QMCSampler *qsa = MEM_callocN(sizeof(QMCSampler), "qmc sampler");
+ qsa->samp2d = MEM_callocN(2*sizeof(double)*tot, "qmc sample table");
qsa->tot = tot;
qsa->type = type;
@@ -859,25 +881,55 @@ static void QMC_sampleHemiCosine(float *vec, QMCSampler *qsa, int thread, int nu
#endif
/* called from convertBlenderScene.c */
-/* samples don't change per pixel, so build the samples in advance for efficiency */
-void init_lamp_hammersley(LampRen *lar)
+void init_render_qmcsampler(Render *re)
{
- lar->qsa = QMC_initSampler(SAMP_TYPE_HAMMERSLEY, lar->ray_totsamp);
+ re->qmcsamplers= MEM_callocN(sizeof(ListBase)*BLENDER_MAX_THREADS, "QMCListBase");
}
-void init_render_hammersley(Render *re)
+static QMCSampler *get_thread_qmcsampler(Render *re, int thread, int type, int tot)
{
- re->qsa = QMC_initSampler(SAMP_TYPE_HAMMERSLEY, (re->wrld.aosamp * re->wrld.aosamp));
+ QMCSampler *qsa;
+
+ /* create qmc samplers as needed, since recursion makes it hard to
+ * predict how many are needed */
+
+ for(qsa=re->qmcsamplers[thread].first; qsa; qsa=qsa->next) {
+ if(qsa->type == type && qsa->tot == tot && !qsa->used) {
+ qsa->used= 1;
+ return qsa;
+ }
+ }
+
+ qsa= QMC_initSampler(type, tot);
+ qsa->used= 1;
+ BLI_addtail(&re->qmcsamplers[thread], qsa);
+
+ return qsa;
}
-void free_lamp_qmcsampler(LampRen *lar)
+static void release_thread_qmcsampler(Render *re, int thread, QMCSampler *qsa)
{
- QMC_freeSampler(lar->qsa);
+ qsa->used= 0;
}
void free_render_qmcsampler(Render *re)
{
- QMC_freeSampler(re->qsa);
+ QMCSampler *qsa, *next;
+ int a;
+
+ if(re->qmcsamplers) {
+ for(a=0; a<BLENDER_MAX_THREADS; a++) {
+ for(qsa=re->qmcsamplers[a].first; qsa; qsa=next) {
+ next= qsa->next;
+ QMC_freeSampler(qsa);
+ }
+
+ re->qmcsamplers[a].first= re->qmcsamplers[a].last= NULL;
+ }
+
+ MEM_freeN(re->qmcsamplers);
+ re->qmcsamplers= NULL;
+ }
}
static int adaptive_sample_variance(int samples, float *col, float *colsq, float thresh)
@@ -954,7 +1006,7 @@ static void trace_refract(float *col, ShadeInput *shi, ShadeResult *shr)
else samp_type = SAMP_TYPE_HAMMERSLEY;
/* all samples are generated per pixel */
- qsa = QMC_initSampler(samp_type, max_samples);
+ qsa = get_thread_qmcsampler(&R, shi->thread, samp_type, max_samples);
QMC_initPixel(qsa, shi->thread);
} else
max_samples = 1;
@@ -1012,7 +1064,8 @@ static void trace_refract(float *col, ShadeInput *shi, ShadeResult *shr)
col[2] /= (float)samples;
col[3] /= (float)samples;
- if (qsa) QMC_freeSampler(qsa);
+ if (qsa)
+ release_thread_qmcsampler(&R, shi->thread, qsa);
}
static void trace_reflect(float *col, ShadeInput *shi, ShadeResult *shr, float fresnelfac)
@@ -1039,7 +1092,7 @@ static void trace_reflect(float *col, ShadeInput *shi, ShadeResult *shr, float f
else samp_type = SAMP_TYPE_HAMMERSLEY;
/* all samples are generated per pixel */
- qsa = QMC_initSampler(samp_type, max_samples);
+ qsa = get_thread_qmcsampler(&R, shi->thread, samp_type, max_samples);
QMC_initPixel(qsa, shi->thread);
} else
max_samples = 1;
@@ -1117,13 +1170,13 @@ static void trace_reflect(float *col, ShadeInput *shi, ShadeResult *shr, float f
col[1] /= (float)samples;
col[2] /= (float)samples;
- if (qsa) QMC_freeSampler(qsa);
+ if (qsa)
+ release_thread_qmcsampler(&R, shi->thread, qsa);
}
/* extern call from render loop */
void ray_trace(ShadeInput *shi, ShadeResult *shr)
{
- VlakRen *vlr;
float i, f, f1, fr, fg, fb;
float mircol[4], tracol[4];
float diff[3];
@@ -1131,7 +1184,7 @@ void ray_trace(ShadeInput *shi, ShadeResult *shr)
do_tra= ((shi->mat->mode & (MA_RAYTRANSP)) && shr->alpha!=1.0f);
do_mir= ((shi->mat->mode & MA_RAYMIRROR) && shi->ray_mirror!=0.0f);
- vlr= shi->vlr;
+
/* raytrace mirror amd refract like to separate the spec color */
if(shi->combinedflag & SCE_PASS_SPEC)
@@ -1231,16 +1284,22 @@ static void ray_trace_shadow_tra(Isect *is, int depth, int traflag)
float d= 1.0f;
/* we got a face */
+ /* Warning, This is not that nice, and possibly a bit slow for every ray,
+ however some variables were not initialized properly in, unless using shade_input_initialize(...), we need to do a memset */
+ memset(&shi, 0, sizeof(ShadeInput));
+ /* end warning! - Campbell */
+
shi.depth= 1; /* only used to indicate tracing */
shi.mask= 1;
- shi.osatex= 0;
+
+ /*shi.osatex= 0;
shi.thread= shi.sample= 0;
shi.lay= 0;
shi.passflag= 0;
shi.combinedflag= 0;
shi.do_preview= 0;
shi.light_override= NULL;
- shi.mat_override= NULL;
+ shi.mat_override= NULL;*/
shade_ray(is, &shi, &shr);
if (traflag & RAY_TRA)
@@ -1300,6 +1359,12 @@ int ray_trace_shadow_rad(ShadeInput *ship, ShadeResult *shr)
if(RE_ray_tree_intersect(R.raytree, &isec)) {
float fac;
+
+ /* Warning, This is not that nice, and possibly a bit slow for every ray,
+ however some variables were not initialized properly in, unless using shade_input_initialize(...), we need to do a memset */
+ memset(&shi, 0, sizeof(ShadeInput));
+ /* end warning! - Campbell */
+
shade_ray(&isec, &shi, &shr_t);
fac= isec.labda*isec.labda;
fac= 1.0f;
@@ -1416,14 +1481,15 @@ static float *sphere_sampler(int type, int resol, int thread, int xs, int ys)
int tot;
float *vec;
- if(resol>16) resol= 16;
-
tot= 2*resol*resol;
if (type & WO_AORNDSMP) {
- static float sphere[2*3*256];
+ float *sphere;
int a;
+ // always returns table
+ sphere= threadsafe_table_sphere(0, thread, xs, ys, tot);
+
/* total random sampling. NOT THREADSAFE! (should be removed, is not useful) */
vec= sphere;
for (a=0; a<tot; a++, vec+=3) {
@@ -1438,7 +1504,8 @@ static float *sphere_sampler(int type, int resol, int thread, int xs, int ys)
float ang, *vec1;
int a;
- sphere= threadsafe_table_sphere(1, thread, xs, ys, tot); // returns table if xs and ys were equal to last call
+ // returns table if xs and ys were equal to last call
+ sphere= threadsafe_table_sphere(1, thread, xs, ys, tot);
if(sphere==NULL) {
sphere= threadsafe_table_sphere(0, thread, xs, ys, tot);
@@ -1460,7 +1527,7 @@ static float *sphere_sampler(int type, int resol, int thread, int xs, int ys)
}
}
-void ray_ao_qmc(ShadeInput *shi, float *shadfac)
+static void ray_ao_qmc(ShadeInput *shi, float *shadfac)
{
Isect isec;
QMCSampler *qsa=NULL;
@@ -1471,7 +1538,6 @@ void ray_ao_qmc(ShadeInput *shi, float *shadfac)
float fac=0.0f, prev=0.0f;
float adapt_thresh = G.scene->world->ao_adapt_thresh;
float adapt_speed_fac = G.scene->world->ao_adapt_speed_fac;
- float bias = G.scene->world->aobias;
int samples=0;
int max_samples = R.wrld.aosamp*R.wrld.aosamp;
@@ -1485,7 +1551,6 @@ void ray_ao_qmc(ShadeInput *shi, float *shadfac)
isec.ob_last= 0;
isec.mode= (R.wrld.aomode & WO_AODIST)?RE_RAY_SHADOW_TRA:RE_RAY_SHADOW;
isec.lay= -1;
- VECCOPY(isec.start, shi->co);
shadfac[0]= shadfac[1]= shadfac[2]= 0.0f;
@@ -1500,13 +1565,10 @@ void ray_ao_qmc(ShadeInput *shi, float *shadfac)
dxyview[2]= 0.0f;
}
- /* bias prevents smoothed faces to appear flat */
if(shi->vlr->flag & R_SMOOTH) {
- bias= G.scene->world->aobias;
VECCOPY(nrm, shi->vn);
}
else {
- bias= 0.0f;
VECCOPY(nrm, shi->facenor);
}
@@ -1521,9 +1583,9 @@ void ray_ao_qmc(ShadeInput *shi, float *shadfac)
max_samples /= speedfac;
if (max_samples < 5) max_samples = 5;
- qsa = QMC_initSampler(SAMP_TYPE_HALTON, max_samples);
+ qsa = get_thread_qmcsampler(&R, shi->thread, SAMP_TYPE_HALTON, max_samples);
} else if (R.wrld.ao_samp_method==WO_AOSAMP_HAMMERSLEY)
- qsa = R.qsa;
+ qsa = get_thread_qmcsampler(&R, shi->thread, SAMP_TYPE_HAMMERSLEY, max_samples);
QMC_initPixel(qsa, shi->thread);
@@ -1538,6 +1600,7 @@ void ray_ao_qmc(ShadeInput *shi, float *shadfac)
Normalize(dir);
+ VECCOPY(isec.start, shi->co);
isec.end[0] = shi->co[0] - maxdist*dir[0];
isec.end[1] = shi->co[1] - maxdist*dir[1];
isec.end[2] = shi->co[2] - maxdist*dir[2];
@@ -1565,6 +1628,7 @@ void ray_ao_qmc(ShadeInput *shi, float *shadfac)
}
else { /* WO_AOSKYTEX */
shadeSkyView(skycol, isec.start, view, dxyview);
+ shadeSunView(skycol, shi->view);
shadfac[0]+= skycol[0];
shadfac[1]+= skycol[1];
shadfac[2]+= skycol[2];
@@ -1595,17 +1659,18 @@ void ray_ao_qmc(ShadeInput *shi, float *shadfac)
shadfac[0]= shadfac[1]= shadfac[2]= 1.0f - fac/(float)samples;
}
- if ((qsa) && (qsa->type == SAMP_TYPE_HALTON)) QMC_freeSampler(qsa);
+ if (qsa)
+ release_thread_qmcsampler(&R, shi->thread, qsa);
}
/* extern call from shade_lamp_loop, ambient occlusion calculus */
-void ray_ao_spheresamp(ShadeInput *shi, float *shadfac)
+static void ray_ao_spheresamp(ShadeInput *shi, float *shadfac)
{
Isect isec;
float *vec, *nrm, div, bias, sh=0.0f;
float maxdist = R.wrld.aodist;
float dxyview[3];
- int j= -1, tot, actual=0, skyadded=0, aocolor;
+ int j= -1, tot, actual=0, skyadded=0, aocolor, resol= R.wrld.aosamp;
isec.faceorig= (RayFace*)shi->vlr;
isec.oborig= RAY_OBJECT_SET(&R, shi->obi);
@@ -1632,14 +1697,16 @@ void ray_ao_spheresamp(ShadeInput *shi, float *shadfac)
if(shi->mat->mode & MA_ONLYSHADOW)
aocolor= WO_AOPLAIN;
- vec= sphere_sampler(R.wrld.aomode, R.wrld.aosamp, shi->thread, shi->xs, shi->ys);
+ if(resol>32) resol= 32;
+
+ vec= sphere_sampler(R.wrld.aomode, resol, shi->thread, shi->xs, shi->ys);
// warning: since we use full sphere now, and dotproduct is below, we do twice as much
- tot= 2*R.wrld.aosamp*R.wrld.aosamp;
+ tot= 2*resol*resol;
if(aocolor == WO_AOSKYTEX) {
- dxyview[0]= 1.0f/(float)R.wrld.aosamp;
- dxyview[1]= 1.0f/(float)R.wrld.aosamp;
+ dxyview[0]= 1.0f/(float)resol;
+ dxyview[1]= 1.0f/(float)resol;
dxyview[2]= 0.0f;
}
@@ -1686,6 +1753,7 @@ void ray_ao_spheresamp(ShadeInput *shi, float *shadfac)
}
else { /* WO_AOSKYTEX */
shadeSkyView(skycol, isec.start, view, dxyview);
+ shadeSunView(skycol, shi->view);
shadfac[0]+= skycol[0];
shadfac[1]+= skycol[1];
shadfac[2]+= skycol[2];
@@ -1724,21 +1792,62 @@ void ray_ao(ShadeInput *shi, float *shadfac)
ray_ao_spheresamp(shi, shadfac);
}
+static void ray_shadow_jittered_coords(ShadeInput *shi, int max, float jitco[RE_MAX_OSA][3], int *totjitco)
+{
+ /* magic numbers for reordering sample positions to give better
+ * results with adaptive sample, when it usually only takes 4 samples */
+ int order8[8] = {0, 1, 5, 6, 2, 3, 4, 7};
+ int order11[11] = {1, 3, 8, 10, 0, 2, 4, 5, 6, 7, 9};
+ int order16[16] = {1, 3, 9, 12, 0, 6, 7, 8, 13, 2, 4, 5, 10, 11, 14, 15};
+ int count = count_mask(shi->mask);
+
+ /* for better antialising shadow samples are distributed over the subpixel
+ * sample coordinates, this only works for raytracing depth 0 though */
+ if(!shi->strand && shi->depth == 0 && count > 1 && count <= max) {
+ float xs, ys, zs, view[3];
+ int samp, ordsamp, tot= 0;
+
+ for(samp=0; samp<R.osa; samp++) {
+ if(R.osa == 8) ordsamp = order8[samp];
+ else if(R.osa == 11) ordsamp = order11[samp];
+ else if(R.osa == 16) ordsamp = order16[samp];
+ else ordsamp = samp;
+
+ if(shi->mask & (1<<ordsamp)) {
+ /* zbuffer has this inverse corrected, ensures xs,ys are inside pixel */
+ xs= (float)shi->scanco[0] + R.jit[ordsamp][0] + 0.5f;
+ ys= (float)shi->scanco[1] + R.jit[ordsamp][1] + 0.5f;
+ zs= shi->scanco[2];
+
+ shade_input_calc_viewco(shi, xs, ys, zs, view, NULL, jitco[tot], NULL, NULL);
+ tot++;
+ }
+ }
+
+ *totjitco= tot;
+ }
+ else {
+ VECCOPY(jitco[0], shi->co);
+ *totjitco= 1;
+ }
+}
static void ray_shadow_qmc(ShadeInput *shi, LampRen *lar, float *lampco, float *shadfac, Isect *isec)
{
QMCSampler *qsa=NULL;
- QMCSampler *qsa_jit=NULL;
int samples=0;
- float samp3d[3], jit[3];
+ float samp3d[3];
float fac=0.0f, vec[3];
float colsq[4];
float adapt_thresh = lar->adapt_thresh;
- int max_samples = lar->ray_totsamp;
- float pos[3];
+ int min_adapt_samples=4, max_samples = lar->ray_totsamp;
+ float *co;
int do_soft=1, full_osa=0;
+ float jitco[RE_MAX_OSA][3];
+ int totjitco;
+
colsq[0] = colsq[1] = colsq[2] = 0.0;
if(isec->mode==RE_RAY_SHADOW_TRA) {
shadfac[0]= shadfac[1]= shadfac[2]= shadfac[3]= 0.0f;
@@ -1756,17 +1865,15 @@ static void ray_shadow_qmc(ShadeInput *shi, LampRen *lar, float *lampco, float *
else max_samples = (R.osa > 4)?R.osa:5;
}
+ ray_shadow_jittered_coords(shi, max_samples, jitco, &totjitco);
+
/* sampling init */
- if (lar->ray_samp_method==LA_SAMP_HALTON) {
- qsa = QMC_initSampler(SAMP_TYPE_HALTON, max_samples);
- qsa_jit = QMC_initSampler(SAMP_TYPE_HALTON, max_samples);
- } else if (lar->ray_samp_method==LA_SAMP_HAMMERSLEY) {
- qsa = lar->qsa;
- qsa_jit = QMC_initSampler(SAMP_TYPE_HAMMERSLEY, max_samples);
- }
+ if (lar->ray_samp_method==LA_SAMP_HALTON)
+ qsa = get_thread_qmcsampler(&R, shi->thread, SAMP_TYPE_HALTON, max_samples);
+ else if (lar->ray_samp_method==LA_SAMP_HAMMERSLEY)
+ qsa = get_thread_qmcsampler(&R, shi->thread, SAMP_TYPE_HAMMERSLEY, max_samples);
QMC_initPixel(qsa, shi->thread);
- QMC_initPixel(qsa_jit, shi->thread);
VECCOPY(vec, lampco);
@@ -1774,18 +1881,11 @@ static void ray_shadow_qmc(ShadeInput *shi, LampRen *lar, float *lampco, float *
while (samples < max_samples) {
isec->faceorig= (RayFace*)shi->vlr;
isec->oborig= RAY_OBJECT_SET(&R, shi->obi);
-
+
/* manually jitter the start shading co-ord per sample
* based on the pre-generated OSA texture sampling offsets,
* for anti-aliasing sharp shadow edges. */
- VECCOPY(pos, shi->co);
- if (shi->vlr && !full_osa) {
- QMC_sampleRect(jit, qsa_jit, shi->thread, samples, 1.0, 1.0);
-
- pos[0] += shi->dxco[0]*jit[0] + shi->dyco[0]*jit[1];
- pos[1] += shi->dxco[1]*jit[0] + shi->dyco[1]*jit[1];
- pos[2] += shi->dxco[2]*jit[0] + shi->dyco[2]*jit[1];
- }
+ co = jitco[samples % totjitco];
if (do_soft) {
/* sphere shadow source */
@@ -1793,9 +1893,9 @@ static void ray_shadow_qmc(ShadeInput *shi, LampRen *lar, float *lampco, float *
float ru[3], rv[3], v[3], s[3];
/* calc tangent plane vectors */
- v[0] = pos[0] - lampco[0];
- v[1] = pos[1] - lampco[1];
- v[2] = pos[2] - lampco[2];
+ v[0] = co[0] - lampco[0];
+ v[1] = co[1] - lampco[1];
+ v[2] = co[2] - lampco[2];
Normalize(v);
VecOrthoBasisf(v, ru, rv);
@@ -1822,8 +1922,21 @@ static void ray_shadow_qmc(ShadeInput *shi, LampRen *lar, float *lampco, float *
} else {
VECCOPY(isec->end, vec);
}
- VECCOPY(isec->start, pos);
-
+
+ if(shi->strand) {
+ /* bias away somewhat to avoid self intersection */
+ float jitbias= 0.5f*(VecLength(shi->dxco) + VecLength(shi->dyco));
+ float v[3];
+
+ VECSUB(v, co, isec->end);
+ Normalize(v);
+
+ co[0] -= jitbias*v[0];
+ co[1] -= jitbias*v[1];
+ co[2] -= jitbias*v[2];
+ }
+
+ VECCOPY(isec->start, co);
/* trace the ray */
if(isec->mode==RE_RAY_SHADOW_TRA) {
@@ -1850,7 +1963,7 @@ static void ray_shadow_qmc(ShadeInput *shi, LampRen *lar, float *lampco, float *
if ((lar->ray_samp_method == LA_SAMP_HALTON)) {
/* adaptive sampling - consider samples below threshold as in shadow (or vice versa) and exit early */
- if ((max_samples > 4) && (adapt_thresh > 0.0) && (samples > max_samples / 3)) {
+ if ((max_samples > min_adapt_samples) && (adapt_thresh > 0.0) && (samples > max_samples / 3)) {
if (isec->mode==RE_RAY_SHADOW_TRA) {
if ((shadfac[3] / samples > (1.0-adapt_thresh)) || (shadfac[3] / samples < adapt_thresh))
break;
@@ -1872,8 +1985,8 @@ static void ray_shadow_qmc(ShadeInput *shi, LampRen *lar, float *lampco, float *
} else
shadfac[3]= 1.0f-fac/samples;
- if (qsa_jit) QMC_freeSampler(qsa_jit);
- if ((qsa) && (qsa->type == SAMP_TYPE_HALTON)) QMC_freeSampler(qsa);
+ if (qsa)
+ release_thread_qmcsampler(&R, shi->thread, qsa);
}
static void ray_shadow_jitter(ShadeInput *shi, LampRen *lar, float *lampco, float *shadfac, Isect *isec)
@@ -1964,7 +2077,10 @@ void ray_shadow(ShadeInput *shi, LampRen *lar, float *shadfac)
if(shi->mat->mode & MA_SHADOW_TRA) isec.mode= RE_RAY_SHADOW_TRA;
else isec.mode= RE_RAY_SHADOW;
- if(lar->mode & LA_LAYER) isec.lay= lar->lay; else isec.lay= -1;
+ if(lar->mode & (LA_LAYER|LA_LAYER_SHADOW))
+ isec.lay= lar->lay;
+ else
+ isec.lay= -1;
/* only when not mir tracing, first hit optimm */
if(shi->depth==0) {
@@ -2025,7 +2141,7 @@ void ray_shadow(ShadeInput *shi, LampRen *lar, float *shadfac)
}
/* only when face points away from lamp, in direction of lamp, trace ray and find first exit point */
-void ray_translucent(ShadeInput *shi, LampRen *lar, float *distfac, float *co)
+static void ray_translucent(ShadeInput *shi, LampRen *lar, float *distfac, float *co)
{
Isect isec;
float lampco[3], maxsize;
diff --git a/source/blender/render/intern/source/raytrace.c b/source/blender/render/intern/source/raytrace.c
index 54e8e4cfab5..ec47df74d04 100644
--- a/source/blender/render/intern/source/raytrace.c
+++ b/source/blender/render/intern/source/raytrace.c
@@ -635,6 +635,8 @@ void RE_ray_tree_done(RayTree *tree)
/* ************ raytracer **************** */
+#define ISECT_EPSILON ((float)FLT_EPSILON)
+
/* only for self-intersecting test with current render face (where ray left) */
static int intersection2(RayFace *face, int ob, RayObjectTransformFunc transformfunc, RayCoordsFunc coordsfunc, void *userdata, float r0, float r1, float r2, float rx1, float ry1, float rz1)
{
@@ -692,13 +694,13 @@ static int intersection2(RayFace *face, int ob, RayObjectTransformFunc transform
if(divdet!=0.0f) {
u1= det1/divdet;
- if(u1<=0.0f) {
+ if(u1<ISECT_EPSILON) {
det= t00*(m1*r2-m2*r1);
det+= t01*(m2*r0-m0*r2);
det+= t02*(m0*r1-m1*r0);
v= det/divdet;
- if(v<=0.0f && (u1 + v) >= -1.0f) {
+ if(v<ISECT_EPSILON && (u1 + v) > -(1.0f+ISECT_EPSILON)) {
return 1;
}
}
@@ -714,13 +716,13 @@ static int intersection2(RayFace *face, int ob, RayObjectTransformFunc transform
if(divdet!=0.0f) {
u2= det1/divdet;
- if(u2<=0.0f) {
+ if(u2<ISECT_EPSILON) {
det= t20*(m1*r2-m2*r1);
det+= t21*(m2*r0-m0*r2);
det+= t22*(m0*r1-m1*r0);
v= det/divdet;
- if(v<=0.0f && (u2 + v) >= -1.0f) {
+ if(v<ISECT_EPSILON && (u2 + v) >= -(1.0f+ISECT_EPSILON)) {
return 2;
}
}
@@ -860,7 +862,7 @@ int RE_ray_face_intersection(Isect *is, RayObjectTransformFunc transformfunc, Ra
divdet= 1.0f/divdet;
u= det1*divdet;
- if(u<0.0f && u>-1.0f) {
+ if(u<ISECT_EPSILON && u>-(1.0f+ISECT_EPSILON)) {
float v, cros0, cros1, cros2;
cros0= m1*t02-m2*t01;
@@ -868,11 +870,11 @@ int RE_ray_face_intersection(Isect *is, RayObjectTransformFunc transformfunc, Ra
cros2= m0*t01-m1*t00;
v= divdet*(cros0*r0 + cros1*r1 + cros2*r2);
- if(v<0.0f && (u + v) > -1.0f) {
+ if(v<ISECT_EPSILON && (u + v) > -(1.0f+ISECT_EPSILON)) {
float labda;
labda= divdet*(cros0*t10 + cros1*t11 + cros2*t12);
- if(labda>0.0f && labda<1.0f) {
+ if(labda>-ISECT_EPSILON && labda<1.0f+ISECT_EPSILON) {
is->labda= labda;
is->u= u; is->v= v;
ok= 1;
@@ -893,18 +895,18 @@ int RE_ray_face_intersection(Isect *is, RayObjectTransformFunc transformfunc, Ra
divdet= 1.0f/divdet;
u = det1*divdet;
- if(u<0.0f && u>-1.0f) {
+ if(u<ISECT_EPSILON && u>-(1.0f+ISECT_EPSILON)) {
float v, cros0, cros1, cros2;
cros0= m1*t22-m2*t21;
cros1= m2*t20-m0*t22;
cros2= m0*t21-m1*t20;
v= divdet*(cros0*r0 + cros1*r1 + cros2*r2);
- if(v<0.0f && (u + v) > -1.0f) {
+ if(v<ISECT_EPSILON && (u + v) >-(1.0f+ISECT_EPSILON)) {
float labda;
labda= divdet*(cros0*t10 + cros1*t11 + cros2*t12);
- if(labda>0.0f && labda<1.0f) {
+ if(labda>-ISECT_EPSILON && labda<1.0f+ISECT_EPSILON) {
ok= 2;
is->labda= labda;
is->u= u; is->v= v;
@@ -983,7 +985,7 @@ static int testnode(Octree *oc, Isect *is, Node *no, OcVal ocval, RayCheckFunc c
if(!(is->faceorig == face && is->oborig == ob)) {
- if(checkfunc(is, face)) {
+ if(checkfunc(is, ob, face)) {
ov= no->ov+nr;
if( (ov->ocx & ocval.ocx) && (ov->ocy & ocval.ocy) && (ov->ocz & ocval.ocz) ) {
@@ -1023,7 +1025,7 @@ static int testnode(Octree *oc, Isect *is, Node *no, OcVal ocval, RayCheckFunc c
while(face) {
if(!(is->faceorig == face && is->oborig == ob)) {
- if(checkfunc(is, face)) {
+ if(checkfunc(is, ob, face)) {
ov= no->ov+nr;
if( (ov->ocx & ocval.ocx) && (ov->ocy & ocval.ocy) && (ov->ocz & ocval.ocz) ) {
//accepted++;
@@ -1031,8 +1033,11 @@ static int testnode(Octree *oc, Isect *is, Node *no, OcVal ocval, RayCheckFunc c
isect.ob= ob;
isect.face= face;
if(RE_ray_face_intersection(&isect, oc->transformfunc, oc->coordsfunc)) {
- if(isect.labda<is->labda) *is= isect;
- found= 1;
+ if(isect.labda<is->labda) {
+ *is= isect;
+ found= 1;
+ }
+
}
}
//else rejected++;
@@ -1205,7 +1210,7 @@ int RE_ray_tree_intersect_check(RayTree *tree, Isect *is, RayCheckFunc checkfunc
/* check with last intersected shadow face */
if(is->face_last!=NULL && !(is->face_last==is->faceorig && is->ob_last==is->oborig)) {
- if(checkfunc(is, is->face_last)) {
+ if(checkfunc(is, is->ob_last, is->face_last)) {
is->ob= is->ob_last;
is->face= is->face_last;
VECSUB(is->vec, is->end, is->start);
diff --git a/source/blender/render/intern/source/rendercore.c b/source/blender/render/intern/source/rendercore.c
index 0a9078b32f0..1eb42bca569 100644
--- a/source/blender/render/intern/source/rendercore.c
+++ b/source/blender/render/intern/source/rendercore.c
@@ -29,6 +29,7 @@
/* system includes */
#include <stdio.h>
#include <math.h>
+#include <float.h>
#include <string.h>
/* External modules: */
@@ -46,6 +47,7 @@
#include "DNA_lamp_types.h"
#include "DNA_material_types.h"
#include "DNA_meshdata_types.h"
+#include "DNA_group_types.h"
#include "BKE_global.h"
#include "BKE_image.h"
@@ -60,6 +62,7 @@
#include "renderpipeline.h"
#include "render_types.h"
#include "renderdatabase.h"
+#include "occlusion.h"
#include "pixelblending.h"
#include "pixelshading.h"
#include "shadbuf.h"
@@ -155,7 +158,7 @@ static int calchalo_z(HaloRen *har, int zz)
{
if(har->type & HA_ONLYSKY) {
- if(zz!=0x7FFFFFFF) zz= - 0x7FFFFF;
+ if(zz < 0x7FFFFFF0) zz= - 0x7FFFFF; /* edge render messes zvalues */
}
else {
zz= (zz>>8);
@@ -163,11 +166,14 @@ static int calchalo_z(HaloRen *har, int zz)
return zz;
}
-static void halo_pixelstruct(HaloRen *har, float *rb, float dist, float xn, float yn, PixStr *ps)
+
+
+static void halo_pixelstruct(HaloRen *har, RenderLayer **rlpp, int totsample, int od, float dist, float xn, float yn, PixStr *ps)
{
- float col[4], accol[4];
- int amount, amountm, zz, flarec;
+ float col[4], accol[4], fac;
+ int amount, amountm, zz, flarec, sample, fullsample, mask=0;
+ fullsample= (totsample > 1);
amount= 0;
accol[0]=accol[1]=accol[2]=accol[3]= 0.0f;
flarec= har->flarec;
@@ -177,50 +183,70 @@ static void halo_pixelstruct(HaloRen *har, float *rb, float dist, float xn, floa
amount+= amountm;
zz= calchalo_z(har, ps->z);
- if(zz> har->zs) {
- float fac;
-
- shadeHaloFloat(har, col, zz, dist, xn, yn, flarec);
- fac= ((float)amountm)/(float)R.osa;
- accol[0]+= fac*col[0];
- accol[1]+= fac*col[1];
- accol[2]+= fac*col[2];
- accol[3]+= fac*col[3];
- flarec= 0;
+ if((zz> har->zs) || (har->mat && (har->mat->mode & MA_HALO_SOFT))) {
+ if(shadeHaloFloat(har, col, zz, dist, xn, yn, flarec)) {
+ flarec= 0;
+
+ if(fullsample) {
+ for(sample=0; sample<totsample; sample++)
+ if(ps->mask & (1 << sample))
+ addalphaAddfacFloat(rlpp[sample]->rectf + od*4, col, har->add);
+ }
+ else {
+ fac= ((float)amountm)/(float)R.osa;
+ accol[0]+= fac*col[0];
+ accol[1]+= fac*col[1];
+ accol[2]+= fac*col[2];
+ accol[3]+= fac*col[3];
+ }
+ }
}
+ mask |= ps->mask;
ps= ps->next;
}
+
/* now do the sky sub-pixels */
amount= R.osa-amount;
if(amount) {
- float fac;
+ if(shadeHaloFloat(har, col, 0x7FFFFF, dist, xn, yn, flarec)) {
+ if(!fullsample) {
+ fac= ((float)amount)/(float)R.osa;
+ accol[0]+= fac*col[0];
+ accol[1]+= fac*col[1];
+ accol[2]+= fac*col[2];
+ accol[3]+= fac*col[3];
+ }
+ }
+ }
- shadeHaloFloat(har, col, 0x7FFFFF, dist, xn, yn, flarec);
- fac= ((float)amount)/(float)R.osa;
- accol[0]+= fac*col[0];
- accol[1]+= fac*col[1];
- accol[2]+= fac*col[2];
- accol[3]+= fac*col[3];
+ if(fullsample) {
+ for(sample=0; sample<totsample; sample++)
+ if(!(mask & (1 << sample)))
+ addalphaAddfacFloat(rlpp[sample]->rectf + od*4, col, har->add);
+ }
+ else {
+ col[0]= accol[0];
+ col[1]= accol[1];
+ col[2]= accol[2];
+ col[3]= accol[3];
+
+ for(sample=0; sample<totsample; sample++)
+ addalphaAddfacFloat(rlpp[sample]->rectf + od*4, col, har->add);
}
- col[0]= accol[0];
- col[1]= accol[1];
- col[2]= accol[2];
- col[3]= accol[3];
-
- addalphaAddfacFloat(rb, col, har->add);
-
}
-static void halo_tile(RenderPart *pa, float *pass, unsigned int lay)
+static void halo_tile(RenderPart *pa, RenderLayer *rl)
{
+ RenderLayer *rlpp[RE_MAX_OSA];
HaloRen *har;
rcti disprect= pa->disprect, testrect= pa->disprect;
- float dist, xsq, ysq, xn, yn, *rb;
+ float dist, xsq, ysq, xn, yn;
float col[4];
- long *rd= NULL;
- int a, *rz, zz, y;
+ intptr_t *rd= NULL;
+ int a, *rz, zz, y, sample, totsample, od;
short minx, maxx, miny, maxy, x;
+ unsigned int lay= rl->lay;
/* we don't render halos in the cropped area, gives errors in flare counter */
if(pa->crop) {
@@ -230,6 +256,8 @@ static void halo_tile(RenderPart *pa, float *pass, unsigned int lay)
testrect.ymax-= pa->crop;
}
+ totsample= get_sample_layers(pa, rl, rlpp);
+
for(a=0; a<R.tothalo; a++) {
har= R.sortedhalos[a];
@@ -254,8 +282,8 @@ static void halo_tile(RenderPart *pa, float *pass, unsigned int lay)
for(y=miny; y<maxy; y++) {
int rectofs= (y-disprect.ymin)*pa->rectx + (minx - disprect.xmin);
- rb= pass + 4*rectofs;
rz= pa->rectz + rectofs;
+ od= rectofs;
if(pa->rectdaps)
rd= pa->rectdaps + rectofs;
@@ -263,19 +291,21 @@ static void halo_tile(RenderPart *pa, float *pass, unsigned int lay)
yn= (y-har->ys)*R.ycor;
ysq= yn*yn;
- for(x=minx; x<maxx; x++, rb+=4, rz++) {
+ for(x=minx; x<maxx; x++, rz++, od++) {
xn= x- har->xs;
xsq= xn*xn;
dist= xsq+ysq;
if(dist<har->radsq) {
if(rd && *rd) {
- halo_pixelstruct(har, rb, dist, xn, yn, (PixStr *)*rd);
+ halo_pixelstruct(har, rlpp, totsample, od, dist, xn, yn, (PixStr *)*rd);
}
else {
zz= calchalo_z(har, *rz);
- if(zz> har->zs) {
- shadeHaloFloat(har, col, zz, dist, xn, yn, har->flarec);
- addalphaAddfacFloat(rb, col, har->add);
+ if((zz> har->zs) || (har->mat && (har->mat->mode & MA_HALO_SOFT))) {
+ if(shadeHaloFloat(har, col, zz, dist, xn, yn, har->flarec)) {
+ for(sample=0; sample<totsample; sample++)
+ addalphaAddfacFloat(rlpp[sample]->rectf + od*4, col, har->add);
+ }
}
}
}
@@ -290,22 +320,27 @@ static void halo_tile(RenderPart *pa, float *pass, unsigned int lay)
static void lamphalo_tile(RenderPart *pa, RenderLayer *rl)
{
+ RenderLayer *rlpp[RE_MAX_OSA];
ShadeInput shi;
- float *pass= rl->rectf;
- float fac;
- long *rd= pa->rectdaps;
- int x, y, *rz= pa->rectz;
+ float *pass;
+ float fac, col[4];
+ intptr_t *rd= pa->rectdaps;
+ int *rz= pa->rectz;
+ int x, y, sample, totsample, fullsample, od;
- shade_input_initialize(&shi, pa, rl, 0);
+ totsample= get_sample_layers(pa, rl, rlpp);
+ fullsample= (totsample > 1);
+
+ shade_input_initialize(&shi, pa, rl, 0); /* this zero's ShadeInput for us */
- for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++) {
- for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, rz++, pass+=4) {
+ for(od=0, y=pa->disprect.ymin; y<pa->disprect.ymax; y++) {
+ for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, rz++, od++) {
calc_view_vector(shi.view, x, y);
if(rd && *rd) {
PixStr *ps= (PixStr *)*rd;
- int samp, totsamp= 0;
+ int count, totsamp= 0, mask= 0;
while(ps) {
if(R.r.mode & R_ORTHO)
@@ -313,15 +348,64 @@ static void lamphalo_tile(RenderPart *pa, RenderLayer *rl)
else
calc_renderco_zbuf(shi.co, shi.view, ps->z);
- totsamp+= samp= count_mask(ps->mask);
- fac= ((float)samp)/(float)R.osa;
- renderspothalo(&shi, pass, fac);
+ totsamp+= count= count_mask(ps->mask);
+ mask |= ps->mask;
+
+ col[0]= col[1]= col[2]= col[3]= 0.0f;
+ renderspothalo(&shi, col, 1.0f);
+
+ if(fullsample) {
+ for(sample=0; sample<totsample; sample++) {
+ if(ps->mask & (1 << sample)) {
+ pass= rlpp[sample]->rectf + od*4;
+ pass[0]+= col[0];
+ pass[1]+= col[1];
+ pass[2]+= col[2];
+ pass[3]+= col[3];
+ if(pass[3]>1.0f) pass[3]= 1.0f;
+ }
+ }
+ }
+ else {
+ fac= ((float)count)/(float)R.osa;
+ pass= rl->rectf + od*4;
+ pass[0]+= fac*col[0];
+ pass[1]+= fac*col[1];
+ pass[2]+= fac*col[2];
+ pass[3]+= fac*col[3];
+ if(pass[3]>1.0f) pass[3]= 1.0f;
+ }
+
ps= ps->next;
}
+
if(totsamp<R.osa) {
- fac= ((float)R.osa-totsamp)/(float)R.osa;
shi.co[2]= 0.0f;
- renderspothalo(&shi, pass, fac);
+
+ col[0]= col[1]= col[2]= col[3]= 0.0f;
+ renderspothalo(&shi, col, 1.0f);
+
+ if(fullsample) {
+ for(sample=0; sample<totsample; sample++) {
+ if(!(mask & (1 << sample))) {
+ pass= rlpp[sample]->rectf + od*4;
+ pass[0]+= col[0];
+ pass[1]+= col[1];
+ pass[2]+= col[2];
+ pass[3]+= col[3];
+ if(pass[3]>1.0f) pass[3]= 1.0f;
+ }
+ }
+ }
+ else {
+ fac= ((float)R.osa-totsamp)/(float)R.osa;
+ pass= rl->rectf + od*4;
+ pass[0]+= fac*col[0];
+ pass[1]+= fac*col[1];
+ pass[2]+= fac*col[2];
+ pass[3]+= fac*col[3];
+ if(pass[3]>1.0f) pass[3]= 1.0f;
+ }
}
}
else {
@@ -330,7 +414,17 @@ static void lamphalo_tile(RenderPart *pa, RenderLayer *rl)
else
calc_renderco_zbuf(shi.co, shi.view, *rz);
- renderspothalo(&shi, pass, 1.0f);
+ col[0]= col[1]= col[2]= col[3]= 0.0f;
+ renderspothalo(&shi, col, 1.0f);
+
+ for(sample=0; sample<totsample; sample++) {
+ pass= rlpp[sample]->rectf + od*4;
+ pass[0]+= col[0];
+ pass[1]+= col[1];
+ pass[2]+= col[2];
+ pass[3]+= col[3];
+ if(pass[3]>1.0f) pass[3]= 1.0f;
+ }
}
if(rd) rd++;
@@ -347,12 +441,19 @@ static void lamphalo_tile(RenderPart *pa, RenderLayer *rl)
static void add_filt_passes(RenderLayer *rl, int curmask, int rectx, int offset, ShadeInput *shi, ShadeResult *shr)
{
RenderPass *rpass;
+
+ /* combined rgb */
+ add_filt_fmask(curmask, shr->combined, rl->rectf + 4*offset, rectx);
for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
float *fp, *col= NULL;
int pixsize= 3;
switch(rpass->passtype) {
+ case SCE_PASS_Z:
+ fp= rpass->rect + offset;
+ *fp= shr->z;
+ break;
case SCE_PASS_RGBA:
col= shr->col;
pixsize= 4;
@@ -399,6 +500,12 @@ static void add_filt_passes(RenderLayer *rl, int curmask, int rectx, int offset,
*fp= (float)shi->obr->ob->index;
}
break;
+ case SCE_PASS_MIST:
+ /* */
+ col= &shr->mist;
+ pixsize= 1;
+ break;
+
case SCE_PASS_VECTOR:
{
/* add minimum speed in pixel, no filter */
@@ -425,12 +532,20 @@ static void add_filt_passes(RenderLayer *rl, int curmask, int rectx, int offset,
static void add_passes(RenderLayer *rl, int offset, ShadeInput *shi, ShadeResult *shr)
{
RenderPass *rpass;
+ float *fp;
+
+ fp= rl->rectf + 4*offset;
+ QUATCOPY(fp, shr->combined);
for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
- float *fp, *col= NULL, uvcol[3];
+ float *col= NULL, uvcol[3];
int a, pixsize= 3;
switch(rpass->passtype) {
+ case SCE_PASS_Z:
+ fp= rpass->rect + offset;
+ *fp= shr->z;
+ break;
case SCE_PASS_RGBA:
col= shr->col;
pixsize= 4;
@@ -477,6 +592,10 @@ static void add_passes(RenderLayer *rl, int offset, ShadeInput *shi, ShadeResult
*fp= (float)shi->obr->ob->index;
}
break;
+ case SCE_PASS_MIST:
+ fp= rpass->rect + offset;
+ *fp= shr->mist;
+ break;
}
if(col) {
fp= rpass->rect + pixsize*offset;
@@ -486,26 +605,60 @@ static void add_passes(RenderLayer *rl, int offset, ShadeInput *shi, ShadeResult
}
}
+int get_sample_layers(RenderPart *pa, RenderLayer *rl, RenderLayer **rlpp)
+{
+
+ if(pa->fullresult.first) {
+ int sample, nr= BLI_findindex(&pa->result->layers, rl);
+
+ for(sample=0; sample<R.osa; sample++) {
+ RenderResult *rr= BLI_findlink(&pa->fullresult, sample);
+
+ rlpp[sample]= BLI_findlink(&rr->layers, nr);
+ }
+ return R.osa;
+ }
+ else {
+ rlpp[0]= rl;
+ return 1;
+ }
+}
+
+
/* only do sky, is default in the solid layer (shade_tile) btw */
-static void sky_tile(RenderPart *pa, float *pass)
+static void sky_tile(RenderPart *pa, RenderLayer *rl)
{
- float col[4];
- int x, y;
+ RenderLayer *rlpp[RE_MAX_OSA];
+ int x, y, od=0, totsample;
if(R.r.alphamode!=R_ADDSKY)
return;
+ totsample= get_sample_layers(pa, rl, rlpp);
+
for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++) {
- for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, pass+=4) {
- if(pass[3]<1.0f) {
- if(pass[3]==0.0f)
- shadeSkyPixel(pass, x, y);
- else {
- shadeSkyPixel(col, x, y);
- addAlphaOverFloat(col, pass);
- QUATCOPY(pass, col);
+ for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, od+=4) {
+ float col[4];
+ int sample, done= 0;
+
+ for(sample= 0; sample<totsample; sample++) {
+ float *pass= rlpp[sample]->rectf + od;
+
+ if(pass[3]<1.0f) {
+
+ if(done==0) {
+ shadeSkyPixel(col, x, y);
+ done= 1;
+ }
+
+ if(pass[3]==0.0f) {
+ QUATCOPY(pass, col);
+ }
+ else {
+ addAlphaUnderFloat(pass, col);
+ }
}
- }
+ }
}
if(y&1)
@@ -513,14 +666,99 @@ static void sky_tile(RenderPart *pa, float *pass)
}
}
+static void atm_tile(RenderPart *pa, RenderLayer *rl)
+{
+ RenderPass *zpass;
+ GroupObject *go;
+ LampRen *lar;
+ RenderLayer *rlpp[RE_MAX_OSA];
+ int totsample;
+ int x, y, od= 0;
+
+ totsample= get_sample_layers(pa, rl, rlpp);
+
+ /* check that z pass is enabled */
+ if(pa->rectz==NULL) return;
+ for(zpass= rl->passes.first; zpass; zpass= zpass->next)
+ if(zpass->passtype==SCE_PASS_Z)
+ break;
+
+ if(zpass==NULL) return;
+
+ /* check for at least one sun lamp that its atmosphere flag is is enabled */
+ for(go=R.lights.first; go; go= go->next) {
+ lar= go->lampren;
+ if(lar->type==LA_SUN && lar->sunsky && (lar->sunsky->effect_type & LA_SUN_EFFECT_AP))
+ break;
+ }
+ /* do nothign and return if there is no sun lamp */
+ if(go==NULL)
+ return;
+
+ /* for each x,y and each sample, and each sun lamp*/
+ for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++) {
+ for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, od++) {
+ int sample;
+
+ for(sample=0; sample<totsample; sample++) {
+ float *zrect= RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_Z) + od;
+ float *rgbrect = rlpp[sample]->rectf + 4*od;
+ float rgb[3];
+ int done= 0;
+
+ for(go=R.lights.first; go; go= go->next) {
+
+
+ lar= go->lampren;
+ if(lar->type==LA_SUN && lar->sunsky) {
+
+ /* if it's sky continue and don't apply atmosphere effect on it */
+ if(*zrect >= 9.9e10 || rgbrect[3]==0.0f) {
+ continue;
+ }
+
+ if((lar->sunsky->effect_type & LA_SUN_EFFECT_AP)) {
+ float tmp_rgb[3];
+
+ VECCOPY(tmp_rgb, rgbrect);
+ if(rgbrect[3]!=1.0f) { /* de-premul */
+ float div= 1.0f/rgbrect[3];
+ VECMUL(tmp_rgb, div);
+ }
+ shadeAtmPixel(lar->sunsky, tmp_rgb, x, y, *zrect);
+ if(rgbrect[3]!=1.0f) { /* premul */
+ VECMUL(tmp_rgb, rgbrect[3]);
+ }
+
+ if(done==0) {
+ VECCOPY(rgb, tmp_rgb);
+ done = 1;
+ }
+ else{
+ rgb[0] = 0.5f*rgb[0] + 0.5f*tmp_rgb[0];
+ rgb[1] = 0.5f*rgb[1] + 0.5f*tmp_rgb[1];
+ rgb[2] = 0.5f*rgb[2] + 0.5f*tmp_rgb[2];
+ }
+ }
+ }
+ }
+
+ /* if at least for one sun lamp aerial perspective was applied*/
+ if(done) {
+ VECCOPY(rgbrect, rgb);
+ }
+ }
+ }
+ }
+}
+
static void shadeDA_tile(RenderPart *pa, RenderLayer *rl)
{
RenderResult *rr= pa->result;
ShadeSample ssamp;
- float *fcol, *rf, *rectf= rl->rectf;
- long *rd, *rectdaps= pa->rectdaps;
+ intptr_t *rd, *rectdaps= pa->rectdaps;
int samp;
- int x, y, seed, crop=0, offs=0, od, addpassflag;
+ int x, y, seed, crop=0, offs=0, od;
if(R.test_break()) return;
@@ -533,12 +771,14 @@ static void shadeDA_tile(RenderPart *pa, RenderLayer *rl)
/* general shader info, passes */
shade_sample_initialize(&ssamp, pa, rl);
- addpassflag= rl->passflag & ~(SCE_PASS_Z|SCE_PASS_COMBINED);
-
+
+ /* occlusion caching */
+ if(R.occlusiontree)
+ cache_occ_samples(&R, pa, &ssamp);
+
/* filtered render, for now we assume only 1 filter size */
if(pa->crop) {
crop= 1;
- rectf+= 4*(pa->rectx + 1);
rectdaps+= pa->rectx + 1;
offs= pa->rectx + 1;
}
@@ -549,28 +789,35 @@ static void shadeDA_tile(RenderPart *pa, RenderLayer *rl)
rr->renlay= rl;
for(y=pa->disprect.ymin+crop; y<pa->disprect.ymax-crop; y++, rr->renrect.ymax++) {
- rf= rectf;
rd= rectdaps;
od= offs;
- for(x=pa->disprect.xmin+crop; x<pa->disprect.xmax-crop; x++, rd++, rf+=4, od++) {
+ for(x=pa->disprect.xmin+crop; x<pa->disprect.xmax-crop; x++, rd++, od++) {
BLI_thread_srandom(pa->thread, seed++);
if(*rd) {
if(shade_samples(&ssamp, (PixStr *)(*rd), x, y)) {
- for(samp=0; samp<ssamp.tot; samp++) {
-
- fcol= ssamp.shr[samp].combined;
- add_filt_fmask(ssamp.shi[samp].mask, fcol, rf, pa->rectx);
-
- if(addpassflag)
+
+ /* multisample buffers or filtered mask filling? */
+ if(pa->fullresult.first) {
+ int a;
+ for(samp=0; samp<ssamp.tot; samp++) {
+ int smask= ssamp.shi[samp].mask;
+ for(a=0; a<R.osa; a++) {
+ int mask= 1<<a;
+ if(smask & mask)
+ add_passes(ssamp.rlpp[a], od, &ssamp.shi[samp], &ssamp.shr[samp]);
+ }
+ }
+ }
+ else {
+ for(samp=0; samp<ssamp.tot; samp++)
add_filt_passes(rl, ssamp.shi[samp].mask, pa->rectx, od, &ssamp.shi[samp], &ssamp.shr[samp]);
}
}
}
}
- rectf+= 4*pa->rectx;
rectdaps+= pa->rectx;
offs+= pa->rectx;
@@ -582,6 +829,9 @@ static void shadeDA_tile(RenderPart *pa, RenderLayer *rl)
if(R.r.mode & R_SHADOW)
ISB_free(pa);
+
+ if(R.occlusiontree)
+ free_occ_samples(&R, pa);
}
/* ************* pixel struct ******** */
@@ -613,7 +863,7 @@ static void freeps(ListBase *lb)
lb->first= lb->last= NULL;
}
-static void addps(ListBase *lb, long *rd, int obi, int facenr, int z, unsigned short mask)
+static void addps(ListBase *lb, intptr_t *rd, int obi, int facenr, int z, int maskz, unsigned short mask)
{
PixStrMain *psm;
PixStr *ps, *last= NULL;
@@ -640,12 +890,13 @@ static void addps(ListBase *lb, long *rd, int obi, int facenr, int z, unsigned s
ps= psm->ps + psm->counter++;
if(last) last->next= ps;
- else *rd= (long)ps;
+ else *rd= (intptr_t)ps;
ps->next= NULL;
ps->obi= obi;
ps->facenr= facenr;
ps->z= z;
+ ps->maskz= maskz;
ps->mask = mask;
ps->shadfac= 0;
}
@@ -669,23 +920,29 @@ static void edge_enhance_add(RenderPart *pa, float *rectf, float *arect)
}
}
-
-static void convert_to_key_alpha(RenderPart *pa, float *rectf)
+static void convert_to_key_alpha(RenderPart *pa, RenderLayer *rl)
{
- int y;
-
- for(y= pa->rectx*pa->recty; y>0; y--, rectf+=4) {
- if(rectf[3] >= 1.0f);
- else if(rectf[3] > 0.0f) {
- rectf[0] /= rectf[3];
- rectf[1] /= rectf[3];
- rectf[2] /= rectf[3];
+ RenderLayer *rlpp[RE_MAX_OSA];
+ int y, sample, totsample;
+
+ totsample= get_sample_layers(pa, rl, rlpp);
+
+ for(sample= 0; sample<totsample; sample++) {
+ float *rectf= rlpp[sample]->rectf;
+
+ for(y= pa->rectx*pa->recty; y>0; y--, rectf+=4) {
+ if(rectf[3] >= 1.0f);
+ else if(rectf[3] > 0.0f) {
+ rectf[0] /= rectf[3];
+ rectf[1] /= rectf[3];
+ rectf[2] /= rectf[3];
+ }
}
}
}
/* adds only alpha values */
-void edge_enhance_tile(RenderPart *pa, float *rectf)
+void edge_enhance_tile(RenderPart *pa, float *rectf, int *rectz)
{
/* use zbuffer to define edges, add it to the image */
int y, x, col, *rz, *rz1, *rz2, *rz3;
@@ -693,13 +950,13 @@ void edge_enhance_tile(RenderPart *pa, float *rectf)
float *rf;
/* shift values in zbuffer 4 to the right (anti overflows), for filter we need multiplying with 12 max */
- rz= pa->rectz;
+ rz= rectz;
if(rz==NULL) return;
for(y=0; y<pa->recty; y++)
for(x=0; x<pa->rectx; x++, rz++) (*rz)>>= 4;
- rz1= pa->rectz;
+ rz1= rectz;
rz2= rz1+pa->rectx;
rz3= rz2+pa->rectx;
@@ -739,7 +996,7 @@ void edge_enhance_tile(RenderPart *pa, float *rectf)
}
/* shift back zbuf values, we might need it still */
- rz= pa->rectz;
+ rz= rectz;
for(y=0; y<pa->recty; y++)
for(x=0; x<pa->rectx; x++, rz++) (*rz)<<= 4;
@@ -748,20 +1005,24 @@ void edge_enhance_tile(RenderPart *pa, float *rectf)
static void reset_sky_speed(RenderPart *pa, RenderLayer *rl)
{
/* for all pixels with max speed, set to zero */
+ RenderLayer *rlpp[RE_MAX_OSA];
float *fp;
- int a;
-
- fp= RE_RenderLayerGetPass(rl, SCE_PASS_VECTOR);
- if(fp==NULL) return;
+ int a, sample, totsample;
- for(a= 4*pa->rectx*pa->recty - 1; a>=0; a--)
- if(fp[a] == PASS_VECTOR_MAX) fp[a]= 0.0f;
-}
+ totsample= get_sample_layers(pa, rl, rlpp);
+ for(sample= 0; sample<totsample; sample++) {
+ fp= RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_VECTOR);
+ if(fp==NULL) break;
+
+ for(a= 4*pa->rectx*pa->recty - 1; a>=0; a--)
+ if(fp[a] == PASS_VECTOR_MAX) fp[a]= 0.0f;
+ }
+}
static unsigned short *make_solid_mask(RenderPart *pa)
{
- long *rd= pa->rectdaps;
+ intptr_t *rd= pa->rectdaps;
unsigned short *solidmask, *sp;
int x;
@@ -826,25 +1087,25 @@ void make_pixelstructs(RenderPart *pa, ZSpan *zspan, int sample, void *data)
{
ZbufSolidData *sdata= (ZbufSolidData*)data;
ListBase *lb= sdata->psmlist;
- long *rd= pa->rectdaps;
+ intptr_t *rd= pa->rectdaps;
int *ro= zspan->recto;
int *rp= zspan->rectp;
int *rz= zspan->rectz;
+ int *rm= zspan->rectmask;
int x, y;
int mask= 1<<sample;
for(y=0; y<pa->recty; y++) {
- for(x=0; x<pa->rectx; x++, rd++, rp++, ro++) {
+ for(x=0; x<pa->rectx; x++, rd++, rp++, ro++, rz++, rm++) {
if(*rp) {
- addps(lb, rd, *ro, *rp, *(rz+x), mask);
+ addps(lb, rd, *ro, *rp, *rz, (zspan->rectmask)? *rm: 0, mask);
}
}
- rz+= pa->rectx;
}
if(sdata->rl->layflag & SCE_LAY_EDGE)
if(R.r.mode & R_EDGE)
- edge_enhance_tile(pa, sdata->edgerect);
+ edge_enhance_tile(pa, sdata->edgerect, zspan->rectz);
}
/* main call for shading Delta Accum, for OSA */
@@ -861,12 +1122,13 @@ void zbufshadeDA_tile(RenderPart *pa)
pa->recto= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "recto");
pa->rectp= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectp");
pa->rectz= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectz");
-
for(rl= rr->layers.first; rl; rl= rl->next) {
-
+ if((rl->layflag & SCE_LAY_ZMASK) && (rl->layflag & SCE_LAY_NEG_ZMASK))
+ pa->rectmask= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectmask");
+
/* initialize pixelstructs and edge buffer */
addpsmain(&psmlist);
- pa->rectdaps= MEM_callocN(sizeof(long)*pa->rectx*pa->recty+4, "zbufDArectd");
+ pa->rectdaps= MEM_callocN(sizeof(intptr_t)*pa->rectx*pa->recty+4, "zbufDArectd");
if(rl->layflag & SCE_LAY_EDGE)
if(R.r.mode & R_EDGE)
@@ -879,7 +1141,7 @@ void zbufshadeDA_tile(RenderPart *pa)
sdata.rl= rl;
sdata.psmlist= &psmlist;
sdata.edgerect= edgerect;
- zbuffer_solid(pa, rl->lay, rl->layflag, make_pixelstructs, &sdata);
+ zbuffer_solid(pa, rl, make_pixelstructs, &sdata);
if(R.test_break()) break;
}
@@ -895,108 +1157,74 @@ void zbufshadeDA_tile(RenderPart *pa)
/* halo before ztra, because ztra fills in zbuffer now */
if(R.flag & R_HALO)
if(rl->layflag & SCE_LAY_HALO)
- halo_tile(pa, rl->rectf, rl->lay);
+ halo_tile(pa, rl);
/* transp layer */
- if(R.flag & R_ZTRA) {
- if(rl->layflag & SCE_LAY_ZTRA) {
- unsigned short *ztramask, *solidmask= NULL; /* 16 bits, MAX_OSA */
-
- /* allocate, but not free here, for asynchronous display of this rect in main thread */
- rl->acolrect= MEM_callocN(4*sizeof(float)*pa->rectx*pa->recty, "alpha layer");
-
- /* swap for live updates, and it is used in zbuf.c!!! */
- SWAP(float *, rl->acolrect, rl->rectf);
- ztramask= zbuffer_transp_shade(pa, rl, rl->rectf);
- SWAP(float *, rl->acolrect, rl->rectf);
-
- /* zbuffer transp only returns ztramask if there's solid rendered */
- if(ztramask)
- solidmask= make_solid_mask(pa);
-
- if(ztramask && solidmask) {
- unsigned short *sps= solidmask, *spz= ztramask;
- unsigned short fullmask= (1<<R.osa)-1;
- float *fcol= rl->rectf; float *acol= rl->acolrect;
- int x;
+ if(R.flag & R_ZTRA || R.totstrand) {
+ if(rl->layflag & (SCE_LAY_ZTRA|SCE_LAY_STRAND)) {
+ if(pa->fullresult.first) {
+ zbuffer_transp_shade(pa, rl, rl->rectf, &psmlist);
+ }
+ else {
+ unsigned short *ztramask, *solidmask= NULL; /* 16 bits, MAX_OSA */
- for(x=pa->rectx*pa->recty; x>0; x--, acol+=4, fcol+=4, sps++, spz++) {
- if(*sps == fullmask)
- addAlphaOverFloat(fcol, acol);
- else
- addAlphaOverFloatMask(fcol, acol, *sps, *spz);
+ /* allocate, but not free here, for asynchronous display of this rect in main thread */
+ rl->acolrect= MEM_callocN(4*sizeof(float)*pa->rectx*pa->recty, "alpha layer");
+
+ /* swap for live updates, and it is used in zbuf.c!!! */
+ SWAP(float *, rl->acolrect, rl->rectf);
+ ztramask= zbuffer_transp_shade(pa, rl, rl->rectf, &psmlist);
+ SWAP(float *, rl->acolrect, rl->rectf);
+
+ /* zbuffer transp only returns ztramask if there's solid rendered */
+ if(ztramask)
+ solidmask= make_solid_mask(pa);
+
+ if(ztramask && solidmask) {
+ unsigned short *sps= solidmask, *spz= ztramask;
+ unsigned short fullmask= (1<<R.osa)-1;
+ float *fcol= rl->rectf; float *acol= rl->acolrect;
+ int x;
+
+ for(x=pa->rectx*pa->recty; x>0; x--, acol+=4, fcol+=4, sps++, spz++) {
+ if(*sps == fullmask)
+ addAlphaOverFloat(fcol, acol);
+ else
+ addAlphaOverFloatMask(fcol, acol, *sps, *spz);
+ }
}
- }
- else {
- float *fcol= rl->rectf; float *acol= rl->acolrect;
- int x;
- for(x=pa->rectx*pa->recty; x>0; x--, acol+=4, fcol+=4) {
- addAlphaOverFloat(fcol, acol);
+ else {
+ float *fcol= rl->rectf; float *acol= rl->acolrect;
+ int x;
+ for(x=pa->rectx*pa->recty; x>0; x--, acol+=4, fcol+=4) {
+ addAlphaOverFloat(fcol, acol);
+ }
}
- }
- if(solidmask) MEM_freeN(solidmask);
- if(ztramask) MEM_freeN(ztramask);
- }
- }
-
- /* strand rendering */
- if((rl->layflag & SCE_LAY_STRAND) && R.totstrand) {
- float *fcol, *scol;
- unsigned short *strandmask, *solidmask= NULL; /* 16 bits, MAX_OSA */
- int x;
-
- /* allocate, but not free here, for asynchronous display of this rect in main thread */
- rl->scolrect= MEM_callocN(4*sizeof(float)*pa->rectx*pa->recty, "strand layer");
-
- /* swap for live updates, and it is used in zbuf.c!!! */
- SWAP(float*, rl->scolrect, rl->rectf);
- strandmask= zbuffer_strands_shade(&R, pa, rl, rl->rectf);
- SWAP(float*, rl->scolrect, rl->rectf);
-
- /* zbuffer strands only returns strandmask if there's solid rendered */
- if(strandmask)
- solidmask= make_solid_mask(pa);
-
- if(strandmask && solidmask) {
- unsigned short *sps= solidmask, *spz= strandmask;
- unsigned short fullmask= (1<<R.osa)-1;
-
- fcol= rl->rectf; scol= rl->scolrect;
- for(x=pa->rectx*pa->recty; x>0; x--, scol+=4, fcol+=4, sps++, spz++) {
- if(*sps == fullmask)
- addAlphaOverFloat(fcol, scol);
- else
- addAlphaOverFloatMask(fcol, scol, *sps, *spz);
+ if(solidmask) MEM_freeN(solidmask);
+ if(ztramask) MEM_freeN(ztramask);
}
}
- else {
- fcol= rl->rectf; scol= rl->scolrect;
- for(x=pa->rectx*pa->recty; x>0; x--, scol+=4, fcol+=4)
- addAlphaOverFloat(fcol, scol);
- }
-
- if(solidmask) MEM_freeN(solidmask);
- if(strandmask) MEM_freeN(strandmask);
}
+ /* sun/sky */
+ if(rl->layflag & SCE_LAY_SKY)
+ atm_tile(pa, rl);
+
/* sky before edge */
if(rl->layflag & SCE_LAY_SKY)
- sky_tile(pa, rl->rectf);
+ sky_tile(pa, rl);
/* extra layers */
if(rl->layflag & SCE_LAY_EDGE)
if(R.r.mode & R_EDGE)
edge_enhance_add(pa, rl->rectf, edgerect);
- if(rl->passflag & SCE_PASS_Z)
- convert_zbuf_to_distbuf(pa, rl);
-
if(rl->passflag & SCE_PASS_VECTOR)
reset_sky_speed(pa, rl);
/* de-premul alpha */
if(R.r.alphamode & R_ALPHAKEY)
- convert_to_key_alpha(pa, rl->rectf);
+ convert_to_key_alpha(pa, rl);
/* free stuff within loop! */
MEM_freeN(pa->rectdaps); pa->rectdaps= NULL;
@@ -1004,6 +1232,11 @@ void zbufshadeDA_tile(RenderPart *pa)
if(edgerect) MEM_freeN(edgerect);
edgerect= NULL;
+
+ if(pa->rectmask) {
+ MEM_freeN(pa->rectmask);
+ pa->rectmask= NULL;
+ }
}
/* free all */
@@ -1028,7 +1261,6 @@ void zbufshade_tile(RenderPart *pa)
RenderLayer *rl;
PixStr ps;
float *edgerect= NULL;
- int addpassflag;
/* fake pixel struct, to comply to osa render */
ps.next= NULL;
@@ -1040,12 +1272,13 @@ void zbufshade_tile(RenderPart *pa)
pa->rectz= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectz");
for(rl= rr->layers.first; rl; rl= rl->next) {
-
+ if((rl->layflag & SCE_LAY_ZMASK) && (rl->layflag & SCE_LAY_NEG_ZMASK))
+ pa->rectmask= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectmask");
+
/* general shader info, passes */
shade_sample_initialize(&ssamp, pa, rl);
- addpassflag= rl->passflag & ~(SCE_PASS_Z|SCE_PASS_COMBINED);
- zbuffer_solid(pa, rl->lay, rl->layflag, NULL, NULL);
+ zbuffer_solid(pa, rl, NULL, NULL);
if(!R.test_break()) { /* NOTE: this if() is not consistant */
@@ -1053,7 +1286,7 @@ void zbufshade_tile(RenderPart *pa)
if(rl->layflag & SCE_LAY_EDGE) {
if(R.r.mode & R_EDGE) {
edgerect= MEM_callocN(sizeof(float)*pa->rectx*pa->recty, "rectedge");
- edge_enhance_tile(pa, edgerect);
+ edge_enhance_tile(pa, edgerect, pa->rectz);
}
}
@@ -1072,6 +1305,9 @@ void zbufshade_tile(RenderPart *pa)
/* irregular shadowb buffer creation */
if(R.r.mode & R_SHADOW)
ISB_create(pa, NULL);
+
+ if(R.occlusiontree)
+ cache_occ_samples(&R, pa, &ssamp);
for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++, rr->renrect.ymax++) {
for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, ro++, rz++, rp++, fcol+=4, offs++) {
@@ -1083,14 +1319,8 @@ void zbufshade_tile(RenderPart *pa)
ps.facenr= *rp;
ps.z= *rz;
if(shade_samples(&ssamp, &ps, x, y)) {
- QUATCOPY(fcol, ssamp.shr[0].combined);
-
- if(!(fcol[0] == fcol[0]))
- printvecf("fudgecol", fcol);
-
- /* passes */
- if(addpassflag)
- add_passes(rl, offs, ssamp.shi, ssamp.shr);
+ /* combined and passes */
+ add_passes(rl, offs, ssamp.shi, ssamp.shr);
}
}
}
@@ -1098,6 +1328,9 @@ void zbufshade_tile(RenderPart *pa)
if(R.test_break()) break;
}
+ if(R.occlusiontree)
+ free_occ_samples(&R, pa);
+
if(R.r.mode & R_SHADOW)
ISB_free(pa);
}
@@ -1114,10 +1347,10 @@ void zbufshade_tile(RenderPart *pa)
/* halo before ztra, because ztra fills in zbuffer now */
if(R.flag & R_HALO)
if(rl->layflag & SCE_LAY_HALO)
- halo_tile(pa, rl->rectf, rl->lay);
+ halo_tile(pa, rl);
- if(R.flag & R_ZTRA) {
- if(rl->layflag & SCE_LAY_ZTRA) {
+ if(R.flag & R_ZTRA || R.totstrand) {
+ if(rl->layflag & (SCE_LAY_ZTRA|SCE_LAY_STRAND)) {
float *fcol, *acol;
int x;
@@ -1126,7 +1359,7 @@ void zbufshade_tile(RenderPart *pa)
/* swap for live updates */
SWAP(float *, rl->acolrect, rl->rectf);
- zbuffer_transp_shade(pa, rl, rl->rectf);
+ zbuffer_transp_shade(pa, rl, rl->rectf, NULL);
SWAP(float *, rl->acolrect, rl->rectf);
fcol= rl->rectf; acol= rl->acolrect;
@@ -1135,28 +1368,14 @@ void zbufshade_tile(RenderPart *pa)
}
}
}
-
- /* strand rendering */
- if((rl->layflag & SCE_LAY_STRAND) && R.totstrand) {
- float *fcol, *scol;
- int x;
-
- /* allocate, but not free here, for asynchronous display of this rect in main thread */
- rl->scolrect= MEM_callocN(4*sizeof(float)*pa->rectx*pa->recty, "strand layer");
-
- /* swap for live updates */
- SWAP(float*, rl->scolrect, rl->rectf);
- zbuffer_strands_shade(&R, pa, rl, rl->rectf);
- SWAP(float*, rl->scolrect, rl->rectf);
-
- fcol= rl->rectf; scol= rl->scolrect;
- for(x=pa->rectx*pa->recty; x>0; x--, scol+=4, fcol+=4)
- addAlphaOverFloat(fcol, scol);
- }
+
+ /* sun/sky */
+ if(rl->layflag & SCE_LAY_SKY)
+ atm_tile(pa, rl);
/* sky before edge */
if(rl->layflag & SCE_LAY_SKY)
- sky_tile(pa, rl->rectf);
+ sky_tile(pa, rl);
if(!R.test_break()) {
if(rl->layflag & SCE_LAY_EDGE)
@@ -1164,18 +1383,20 @@ void zbufshade_tile(RenderPart *pa)
edge_enhance_add(pa, rl->rectf, edgerect);
}
- if(rl->passflag & SCE_PASS_Z)
- convert_zbuf_to_distbuf(pa, rl);
-
if(rl->passflag & SCE_PASS_VECTOR)
reset_sky_speed(pa, rl);
/* de-premul alpha */
if(R.r.alphamode & R_ALPHAKEY)
- convert_to_key_alpha(pa, rl->rectf);
+ convert_to_key_alpha(pa, rl);
if(edgerect) MEM_freeN(edgerect);
edgerect= NULL;
+
+ if(pa->rectmask) {
+ MEM_freeN(pa->rectmask);
+ pa->rectmask= NULL;
+ }
}
/* display active layer */
@@ -1207,9 +1428,9 @@ static void addps_sss(void *cb_handle, int obi, int facenr, int x, int y, int z)
return;
if(pa->rectall) {
- long *rs= pa->rectall + pa->rectx*y + x;
+ intptr_t *rs= pa->rectall + pa->rectx*y + x;
- addps(&handle->psmlist, rs, obi, facenr, z, 0);
+ addps(&handle->psmlist, rs, obi, facenr, z, 0, 0);
handle->totps++;
}
if(pa->rectz) {
@@ -1244,10 +1465,10 @@ static void shade_sample_sss(ShadeSample *ssamp, Material *mat, ObjectInstanceRe
{
ShadeInput *shi= ssamp->shi;
ShadeResult shr;
- float texfac, orthoarea, nor[3];
+ float texfac, orthoarea, nor[3], alpha, sx, sy;
/* cache for shadow */
- shi->samplenr++;
+ shi->samplenr= R.shadowsamplenr[shi->thread]++;
if(quad)
shade_input_set_triangle_i(shi, obi, vlr, 0, 2, 3);
@@ -1255,8 +1476,8 @@ static void shade_sample_sss(ShadeSample *ssamp, Material *mat, ObjectInstanceRe
shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 2);
/* center pixel */
- x += 0.5f;
- y += 0.5f;
+ sx = x + 0.5f;
+ sy = y + 0.5f;
/* we estimate the area here using shi->dxco and shi->dyco. we need to
enabled shi->osatex these are filled. we compute two areas, one with
@@ -1265,13 +1486,13 @@ static void shade_sample_sss(ShadeSample *ssamp, Material *mat, ObjectInstanceRe
shi->osatex= 1;
VECCOPY(nor, shi->facenor);
- calc_view_vector(shi->facenor, x, y);
+ calc_view_vector(shi->facenor, sx, sy);
Normalize(shi->facenor);
- shade_input_set_viewco(shi, x, y, z);
+ shade_input_set_viewco(shi, x, y, sx, sy, z);
orthoarea= VecLength(shi->dxco)*VecLength(shi->dyco);
VECCOPY(shi->facenor, nor);
- shade_input_set_viewco(shi, x, y, z);
+ shade_input_set_viewco(shi, x, y, sx, sy, z);
*area= VecLength(shi->dxco)*VecLength(shi->dyco);
*area= MIN2(*area, 2.0f*orthoarea);
@@ -1310,16 +1531,8 @@ static void shade_sample_sss(ShadeSample *ssamp, Material *mat, ObjectInstanceRe
/* texture blending */
texfac= shi->mat->sss_texfac;
- if(texfac == 0.0f) {
- if(shr.col[0]!=0.0f) color[0] /= shr.col[0];
- if(shr.col[1]!=0.0f) color[1] /= shr.col[1];
- if(shr.col[2]!=0.0f) color[2] /= shr.col[2];
- }
- else if(texfac != 1.0f) {
- if(shr.col[0]!=0.0f) color[0] *= pow(shr.col[0], texfac)/shr.col[0];
- if(shr.col[1]!=0.0f) color[1] *= pow(shr.col[1], texfac)/shr.col[1];
- if(shr.col[2]!=0.0f) color[2] *= pow(shr.col[2], texfac)/shr.col[2];
- }
+ alpha= shr.combined[3];
+ *area *= alpha;
}
static void zbufshade_sss_free(RenderPart *pa)
@@ -1343,15 +1556,15 @@ void zbufshade_sss_tile(RenderPart *pa)
ShadeSample ssamp;
ZBufSSSHandle handle;
RenderResult *rr= pa->result;
- RenderLayer *rl= rr->layers.first;
+ RenderLayer *rl;
VlakRen *vlr;
Material *mat= re->sss_mat;
- float (*co)[3], (*color)[3], *area, *fcol= rl->rectf;
+ float (*co)[3], (*color)[3], *area, *fcol;
int x, y, seed, quad, totpoint, display = !(re->r.scemode & R_PREVIEWBUTS);
- int *ro, *rz, *rp, *rbo, *rbz, *rbp;
+ int *ro, *rz, *rp, *rbo, *rbz, *rbp, lay;
#if 0
PixStr *ps;
- long *rs;
+ intptr_t *rs;
int z;
#endif
@@ -1363,7 +1576,7 @@ void zbufshade_sss_tile(RenderPart *pa)
handle.psmlist.first= handle.psmlist.last= NULL;
addpsmain(&handle.psmlist);
- pa->rectall= MEM_callocN(sizeof(long)*pa->rectx*pa->recty+4, "rectall");
+ pa->rectall= MEM_callocN(sizeof(intptr_t)*pa->rectx*pa->recty+4, "rectall");
#else
pa->recto= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "recto");
pa->rectp= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectp");
@@ -1373,13 +1586,34 @@ void zbufshade_sss_tile(RenderPart *pa)
pa->rectbackz= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectbackz");
#endif
+ /* setup shade sample with correct passes */
+ memset(&ssamp, 0, sizeof(ssamp));
+ shade_sample_initialize(&ssamp, pa, rr->layers.first);
+ ssamp.tot= 1;
+
+ for(rl=rr->layers.first; rl; rl=rl->next) {
+ ssamp.shi[0].lay |= rl->lay;
+ ssamp.shi[0].layflag |= rl->layflag;
+ ssamp.shi[0].passflag |= rl->passflag;
+ ssamp.shi[0].combinedflag |= ~rl->pass_xor;
+ }
+
+ rl= rr->layers.first;
+ ssamp.shi[0].passflag |= SCE_PASS_RGBA|SCE_PASS_COMBINED;
+ ssamp.shi[0].combinedflag &= ~(SCE_PASS_SPEC);
+ ssamp.shi[0].mat_override= NULL;
+ ssamp.shi[0].light_override= NULL;
+ lay= ssamp.shi[0].lay;
+
/* create the pixelstrs to be used later */
- zbuffer_sss(pa, rl->lay, &handle, addps_sss);
+ zbuffer_sss(pa, lay, &handle, addps_sss);
if(handle.totps==0) {
zbufshade_sss_free(pa);
return;
}
+
+ fcol= rl->rectf;
co= MEM_mallocN(sizeof(float)*3*handle.totps, "SSSCo");
color= MEM_mallocN(sizeof(float)*3*handle.totps, "SSSColor");
@@ -1391,14 +1625,6 @@ void zbufshade_sss_tile(RenderPart *pa)
ISB_create(pa, NULL);
#endif
- /* setup shade sample with correct passes */
- memset(&ssamp, 0, sizeof(ssamp));
- shade_sample_initialize(&ssamp, pa, rl);
- ssamp.shi[0].passflag= SCE_PASS_DIFFUSE|SCE_PASS_AO|SCE_PASS_RADIO;
- ssamp.shi[0].passflag |= SCE_PASS_RGBA;
- ssamp.shi[0].combinedflag= ~(SCE_PASS_SPEC);
- ssamp.tot= 1;
-
if(display) {
/* initialize scanline updates for main thread */
rr->renrect.ymin= 0;
@@ -1563,8 +1789,8 @@ static void renderhalo_post(RenderResult *rr, float *rectf, HaloRen *har) /* pos
dist= xsq+ysq;
if(dist<har->radsq) {
- shadeHaloFloat(har, colf, 0x7FFFFF, dist, xn, yn, har->flarec);
- addalphaAddfacFloat(rtf, colf, har->add);
+ if(shadeHaloFloat(har, colf, 0x7FFFFF, dist, xn, yn, har->flarec))
+ addalphaAddfacFloat(rtf, colf, har->add);
}
rtf+=4;
}
@@ -1701,6 +1927,8 @@ void add_halo_flare(Render *re)
void RE_shade_external(Render *re, ShadeInput *shi, ShadeResult *shr)
{
static VlakRen vlr;
+ static ObjectRen obr;
+ static ObjectInstanceRen obi;
/* init */
if(re) {
@@ -1708,11 +1936,16 @@ void RE_shade_external(Render *re, ShadeInput *shi, ShadeResult *shr)
/* fake render face */
memset(&vlr, 0, sizeof(VlakRen));
- vlr.lay= -1;
+ memset(&obr, 0, sizeof(ObjectRen));
+ memset(&obi, 0, sizeof(ObjectInstanceRen));
+ obr.lay= -1;
+ obi.obr= &obr;
return;
}
shi->vlr= &vlr;
+ shi->obr= &obr;
+ shi->obi= &obi;
if(shi->mat->nodetree && shi->mat->use_nodes)
ntreeShaderExecTree(shi->mat->nodetree, shi, shr);
@@ -1727,7 +1960,6 @@ void RE_shade_external(Render *re, ShadeInput *shi, ShadeResult *shr)
/* ************************* bake ************************ */
-#define FTOCHAR(val) val<=0.0f?0: (val>=1.0f?255: (char)(255.0f*val))
typedef struct BakeShade {
ShadeSample ssamp;
@@ -1745,8 +1977,81 @@ typedef struct BakeShade {
unsigned int *rect;
float *rect_float;
+
+ int usemask;
+ char *rect_mask; /* bake pixel mask */
+
+ float dxco[3], dyco[3];
} BakeShade;
+/* bake uses a char mask to know what has been baked */
+#define BAKE_MASK_NULL 0
+#define BAKE_MASK_MARGIN 1
+#define BAKE_MASK_BAKED 2
+static void bake_mask_filter_extend( char *mask, int width, int height )
+{
+ char *row1, *row2, *row3;
+ int rowlen, x, y;
+ char *temprect;
+
+ rowlen= width;
+
+ /* make a copy, to prevent flooding */
+ temprect= MEM_dupallocN(mask);
+
+ for(y=1; y<=height; y++) {
+ /* setup rows */
+ row1= (char *)(temprect + (y-2)*rowlen);
+ row2= row1 + rowlen;
+ row3= row2 + rowlen;
+ if(y==1)
+ row1= row2;
+ else if(y==height)
+ row3= row2;
+
+ for(x=0; x<rowlen; x++) {
+ if (mask[((y-1)*rowlen)+x]==0) {
+ if (*row1 || *row2 || *row3 || *(row1+1) || *(row3+1) ) {
+ mask[((y-1)*rowlen)+x] = BAKE_MASK_MARGIN;
+ } else if((x!=rowlen-1) && (*(row1+2) || *(row2+2) || *(row3+2)) ) {
+ mask[((y-1)*rowlen)+x] = BAKE_MASK_MARGIN;
+ }
+ }
+
+ if(x!=0) {
+ row1++; row2++; row3++;
+ }
+ }
+ }
+ MEM_freeN(temprect);
+}
+
+static void bake_mask_clear( ImBuf *ibuf, char *mask, char val )
+{
+ int x,y;
+ if (ibuf->rect_float) {
+ for(x=0; x<ibuf->x; x++) {
+ for(y=0; y<ibuf->y; y++) {
+ if (mask[ibuf->x*y + x] == val) {
+ float *col= ibuf->rect_float + 4*(ibuf->x*y + x);
+ col[0] = col[1] = col[2] = col[3] = 0.0f;
+ }
+ }
+ }
+
+ } else {
+ /* char buffer */
+ for(x=0; x<ibuf->x; x++) {
+ for(y=0; y<ibuf->y; y++) {
+ if (mask[ibuf->x*y + x] == val) {
+ char *col= (char *)(ibuf->rect + ibuf->x*y + x);
+ col[0] = col[1] = col[2] = col[3] = 0;
+ }
+ }
+ }
+ }
+}
+
static void bake_set_shade_input(ObjectInstanceRen *obi, VlakRen *vlr, ShadeInput *shi, int quad, int isect, int x, int y, float u, float v)
{
if(isect) {
@@ -1768,23 +2073,28 @@ static void bake_set_shade_input(ObjectInstanceRen *obi, VlakRen *vlr, ShadeInpu
shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 2);
}
- /* set up view vector */
- VECCOPY(shi->view, shi->co);
- Normalize(shi->view);
-
/* cache for shadow */
- shi->samplenr++;
+ shi->samplenr= R.shadowsamplenr[shi->thread]++;
+
+ shi->mask= 0xFFFF; /* all samples */
shi->u= -u;
shi->v= -v;
shi->xs= x;
shi->ys= y;
+ shade_input_set_uv(shi);
shade_input_set_normals(shi);
/* no normal flip */
if(shi->flippednor)
shade_input_flip_normals(shi);
+
+ /* set up view vector to look right at the surface (note that the normal
+ * is negated in the renderer so it does not need to be done here) */
+ shi->view[0]= shi->vn[0];
+ shi->view[1]= shi->vn[1];
+ shi->view[2]= shi->vn[2];
}
static void bake_shade(void *handle, Object *ob, ShadeInput *shi, int quad, int x, int y, float u, float v, float *tvn, float *ttang)
@@ -1800,12 +2110,20 @@ static void bake_shade(void *handle, Object *ob, ShadeInput *shi, int quad, int
if(bs->type==RE_BAKE_AO) {
ambient_occlusion(shi);
- ambient_occlusion_to_diffuse(shi, shr.combined);
+
+ if(R.r.bake_flag & R_BAKE_NORMALIZE)
+ VECCOPY(shr.combined, shi->ao)
+ else
+ ambient_occlusion_to_diffuse(shi, shr.combined);
}
else {
+ if (bs->type==RE_BAKE_SHADOW) /* Why do shadows set the color anyhow?, ignore material color for baking */
+ shi->r = shi->g = shi->b = 1.0f;
+
shade_input_set_shade_texco(shi);
- shade_samples_do_AO(ssamp);
+ if(!ELEM3(bs->type, RE_BAKE_NORMALS, RE_BAKE_TEXTURE, RE_BAKE_SHADOW))
+ shade_samples_do_AO(ssamp);
if(shi->mat->nodetree && shi->mat->use_nodes) {
ntreeShaderExecTree(shi->mat->nodetree, shi, &shr);
@@ -1830,8 +2148,8 @@ static void bake_shade(void *handle, Object *ob, ShadeInput *shi, int quad, int
VECCOPY(mat[2], tvn);
}
else {
- VECCOPY(mat[0], shi->tang);
- Crossf(mat[1], shi->vn, shi->tang);
+ VECCOPY(mat[0], shi->nmaptang);
+ Crossf(mat[1], shi->vn, shi->nmaptang);
VECCOPY(mat[2], shi->vn);
}
@@ -1853,35 +2171,80 @@ static void bake_shade(void *handle, Object *ob, ShadeInput *shi, int quad, int
shr.combined[0]= shi->r;
shr.combined[1]= shi->g;
shr.combined[2]= shi->b;
+ shr.alpha = shi->alpha;
+ }
+ else if(bs->type==RE_BAKE_SHADOW) {
+ VECCOPY(shr.combined, shr.shad);
+ shr.alpha = shi->alpha;
}
}
- if(bs->rect) {
+ if(bs->rect_float) {
+ float *col= bs->rect_float + 4*(bs->rectx*y + x);
+ VECCOPY(col, shr.combined);
+ if (bs->type==RE_BAKE_ALL || bs->type==RE_BAKE_TEXTURE) {
+ col[3]= shr.alpha;
+ } else {
+ col[3]= 1.0;
+ }
+ }
+ else {
char *col= (char *)(bs->rect + bs->rectx*y + x);
col[0]= FTOCHAR(shr.combined[0]);
col[1]= FTOCHAR(shr.combined[1]);
col[2]= FTOCHAR(shr.combined[2]);
- col[3]= 255;
+
+
+ if (bs->type==RE_BAKE_ALL || bs->type==RE_BAKE_TEXTURE) {
+ col[3]= FTOCHAR(shr.alpha);
+ } else {
+ col[3]= 255;
+ }
}
- else {
+
+ if (bs->rect_mask) {
+ bs->rect_mask[bs->rectx*y + x] = BAKE_MASK_BAKED;
+ }
+}
+
+static void bake_displacement(void *handle, ShadeInput *shi, float dist, int x, int y)
+{
+ BakeShade *bs= handle;
+ float disp;
+
+ if(R.r.bake_flag & R_BAKE_NORMALIZE && R.r.bake_maxdist) {
+ disp = (dist+R.r.bake_maxdist) / (R.r.bake_maxdist*2); /* alter the range from [-bake_maxdist, bake_maxdist] to [0, 1]*/
+ } else {
+ disp = 0.5 + dist; /* alter the range from [-0.5,0.5] to [0,1]*/
+ }
+
+ if(bs->rect_float) {
float *col= bs->rect_float + 4*(bs->rectx*y + x);
- VECCOPY(col, shr.combined);
+ col[0] = col[1] = col[2] = disp;
col[3]= 1.0f;
+ } else {
+ char *col= (char *)(bs->rect + bs->rectx*y + x);
+ col[0]= FTOCHAR(disp);
+ col[1]= FTOCHAR(disp);
+ col[2]= FTOCHAR(disp);
+ col[3]= 255;
+ }
+ if (bs->rect_mask) {
+ bs->rect_mask[bs->rectx*y + x] = BAKE_MASK_BAKED;
}
}
-static int bake_check_intersect(Isect *is, RayFace *face)
+static int bake_check_intersect(Isect *is, int ob, RayFace *face)
{
- VlakRen *vlr = (VlakRen*)face;
BakeShade *bs = (BakeShade*)is->userdata;
/* no direction checking for now, doesn't always improve the result
* (INPR(shi->facenor, bs->dir) > 0.0f); */
- return (vlr->obr->ob != bs->actob);
+ return (R.objectinstance[ob].obr->ob != bs->actob);
}
-static int bake_intersect_tree(RayTree* raytree, Isect* isect, float *dir, float sign, float *hitco)
+static int bake_intersect_tree(RayTree* raytree, Isect* isect, float *start, float *dir, float sign, float *hitco, float *dist)
{
float maxdist;
int hit;
@@ -1890,7 +2253,9 @@ static int bake_intersect_tree(RayTree* raytree, Isect* isect, float *dir, float
if(R.r.bake_maxdist > 0.0f)
maxdist= R.r.bake_maxdist;
else
- maxdist= RE_ray_tree_max_size(R.raytree);
+ maxdist= RE_ray_tree_max_size(R.raytree) + R.r.bake_biasdist;
+
+ VECADDFAC(isect->start, start, dir, -R.r.bake_biasdist);
isect->end[0] = isect->start[0] + dir[0]*maxdist*sign;
isect->end[1] = isect->start[1] + dir[1]*maxdist*sign;
@@ -1901,11 +2266,62 @@ static int bake_intersect_tree(RayTree* raytree, Isect* isect, float *dir, float
hitco[0] = isect->start[0] + isect->labda*isect->vec[0];
hitco[1] = isect->start[1] + isect->labda*isect->vec[1];
hitco[2] = isect->start[2] + isect->labda*isect->vec[2];
+
+ *dist= VecLenf(start, hitco);
}
return hit;
}
+static void bake_set_vlr_dxyco(BakeShade *bs, float *uv1, float *uv2, float *uv3)
+{
+ VlakRen *vlr= bs->vlr;
+ float A, d1, d2, d3, *v1, *v2, *v3;
+
+ if(bs->quad) {
+ v1= vlr->v1->co;
+ v2= vlr->v3->co;
+ v3= vlr->v4->co;
+ }
+ else {
+ v1= vlr->v1->co;
+ v2= vlr->v2->co;
+ v3= vlr->v3->co;
+ }
+
+ /* formula derived from barycentric coordinates:
+ * (uvArea1*v1 + uvArea2*v2 + uvArea3*v3)/uvArea
+ * then taking u and v partial derivatives to get dxco and dyco */
+ A= (uv2[0] - uv1[0])*(uv3[1] - uv1[1]) - (uv3[0] - uv1[0])*(uv2[1] - uv1[1]);
+
+ if(fabs(A) > FLT_EPSILON) {
+ A= 0.5f/A;
+
+ d1= uv2[1] - uv3[1];
+ d2= uv3[1] - uv1[1];
+ d3= uv1[1] - uv2[1];
+ bs->dxco[0]= (v1[0]*d1 + v2[0]*d2 + v3[0]*d3)*A;
+ bs->dxco[1]= (v1[1]*d1 + v2[1]*d2 + v3[1]*d3)*A;
+ bs->dxco[2]= (v1[2]*d1 + v2[2]*d2 + v3[2]*d3)*A;
+
+ d1= uv3[0] - uv2[0];
+ d2= uv1[0] - uv3[0];
+ d3= uv2[0] - uv1[0];
+ bs->dyco[0]= (v1[0]*d1 + v2[0]*d2 + v3[0]*d3)*A;
+ bs->dyco[1]= (v1[1]*d1 + v2[1]*d2 + v3[1]*d3)*A;
+ bs->dyco[2]= (v1[2]*d1 + v2[2]*d2 + v3[2]*d3)*A;
+ }
+ else {
+ bs->dxco[0]= bs->dxco[1]= bs->dxco[2]= 0.0f;
+ bs->dyco[0]= bs->dyco[1]= bs->dyco[2]= 0.0f;
+ }
+
+ if(bs->obi->flag & R_TRANSFORMED) {
+ Mat3MulVecfl(bs->obi->nmat, bs->dxco);
+ Mat3MulVecfl(bs->obi->nmat, bs->dyco);
+ }
+}
+
static void do_bake_shade(void *handle, int x, int y, float u, float v)
{
BakeShade *bs= handle;
@@ -1943,52 +2359,64 @@ static void do_bake_shade(void *handle, int x, int y, float u, float v)
if(obi->flag & R_TRANSFORMED)
Mat4MulVecfl(obi->mat, shi->co);
+ VECCOPY(shi->dxco, bs->dxco);
+ VECCOPY(shi->dyco, bs->dyco);
+
quad= bs->quad;
bake_set_shade_input(obi, vlr, shi, quad, 0, x, y, u, v);
if(bs->type==RE_BAKE_NORMALS && R.r.bake_normal_space==R_BAKE_SPACE_TANGENT) {
shade_input_set_shade_texco(shi);
VECCOPY(tvn, shi->vn);
- VECCOPY(ttang, shi->tang);
+ VECCOPY(ttang, shi->nmaptang);
}
/* if we are doing selected to active baking, find point on other face */
if(bs->actob) {
Isect isec, minisec;
- float co[3], minco[3];
- int hit, sign;
+ float co[3], minco[3], dist, mindist=0.0f;
+ int hit, sign, dir=1;
/* intersect with ray going forward and backward*/
hit= 0;
memset(&minisec, 0, sizeof(minisec));
minco[0]= minco[1]= minco[2]= 0.0f;
-
+
VECCOPY(bs->dir, shi->vn);
-
+
for(sign=-1; sign<=1; sign+=2) {
memset(&isec, 0, sizeof(isec));
- VECCOPY(isec.start, shi->co);
isec.mode= RE_RAY_MIRROR;
isec.faceorig= (RayFace*)vlr;
isec.oborig= RAY_OBJECT_SET(&R, obi);
isec.userdata= bs;
-
- if(bake_intersect_tree(R.raytree, &isec, shi->vn, sign, co)) {
+
+ if(bake_intersect_tree(R.raytree, &isec, shi->co, shi->vn, sign, co, &dist)) {
if(!hit || VecLenf(shi->co, co) < VecLenf(shi->co, minco)) {
minisec= isec;
+ mindist= dist;
VECCOPY(minco, co);
hit= 1;
+ dir = sign;
}
}
}
+ if (bs->type==RE_BAKE_DISPLACEMENT) {
+ if(hit)
+ bake_displacement(handle, shi, (dir==-1)? mindist:-mindist, x, y);
+ else
+ bake_displacement(handle, shi, 0.0f, x, y);
+ return;
+ }
+
/* if hit, we shade from the new point, otherwise from point one starting face */
if(hit) {
vlr= (VlakRen*)minisec.face;
obi= RAY_OBJECT_GET(&R, minisec.ob);
quad= (minisec.isect == 2);
VECCOPY(shi->co, minco);
-
+
u= -minisec.u;
v= -minisec.v;
bake_set_shade_input(obi, vlr, shi, quad, 1, x, y, u, v);
@@ -2025,7 +2453,7 @@ static int get_next_bake_face(BakeShade *bs)
vlr= RE_findOrAddVlak(obr, v);
if((bs->actob && bs->actob == obr->ob) || (!bs->actob && (obr->ob->flag & SELECT))) {
- tface= RE_vlakren_get_tface(obr, vlr, obr->actmtface, NULL, 0);
+ tface= RE_vlakren_get_tface(obr, vlr, obr->bakemtface, NULL, 0);
if(tface && tface->tpage) {
Image *ima= tface->tpage;
@@ -2079,7 +2507,7 @@ static void shade_tface(BakeShade *bs)
VlakRen *vlr= bs->vlr;
ObjectInstanceRen *obi= bs->obi;
ObjectRen *obr= obi->obr;
- MTFace *tface= RE_vlakren_get_tface(obr, vlr, obr->actmtface, NULL, 0);
+ MTFace *tface= RE_vlakren_get_tface(obr, vlr, obr->bakemtface, NULL, 0);
Image *ima= tface->tpage;
float vec[4][2];
int a, i1, i2, i3;
@@ -2099,6 +2527,19 @@ static void shade_tface(BakeShade *bs)
bs->rect_float= bs->ibuf->rect_float;
bs->quad= 0;
+ if (bs->usemask) {
+ if (bs->ibuf->userdata==NULL) {
+ BLI_lock_thread(LOCK_CUSTOM1);
+ if (bs->ibuf->userdata==NULL) { /* since the thread was locked, its possible another thread alloced the value */
+ bs->ibuf->userdata = (void *)MEM_callocN(sizeof(char)*bs->rectx*bs->recty, "BakeMask");
+ bs->rect_mask= (char *)bs->ibuf->userdata;
+ }
+ BLI_unlock_thread(LOCK_CUSTOM1);
+ } else {
+ bs->rect_mask= (char *)bs->ibuf->userdata;
+ }
+ }
+
/* get pixel level vertex coordinates */
for(a=0; a<4; a++) {
vec[a][0]= tface->uv[a][0]*(float)bs->rectx - 0.5f;
@@ -2108,10 +2549,12 @@ static void shade_tface(BakeShade *bs)
/* UV indices have to be corrected for possible quad->tria splits */
i1= 0; i2= 1; i3= 2;
vlr_set_uv_indices(vlr, &i1, &i2, &i3);
+ bake_set_vlr_dxyco(bs, vec[i1], vec[i2], vec[i3]);
zspan_scanconvert(bs->zspan, bs, vec[i1], vec[i2], vec[i3], do_bake_shade);
if(vlr->v4) {
bs->quad= 1;
+ bake_set_vlr_dxyco(bs, vec[0], vec[2], vec[3]);
zspan_scanconvert(bs->zspan, bs, vec[0], vec[2], vec[3], do_bake_shade);
}
}
@@ -2140,8 +2583,8 @@ int RE_bake_shade_all_selected(Render *re, int type, Object *actob)
BakeShade handles[BLENDER_MAX_THREADS];
ListBase threads;
Image *ima;
- int a, vdone=0;
-
+ int a, vdone=0, usemask=0;
+
/* initialize render global */
R= *re;
R.bakebuf= NULL;
@@ -2149,9 +2592,17 @@ int RE_bake_shade_all_selected(Render *re, int type, Object *actob)
/* initialize static vars */
get_next_bake_face(NULL);
+ /* do we need a mask? */
+ if (re->r.bake_filter && (re->r.bake_flag & R_BAKE_CLEAR)==0)
+ usemask = 1;
+
/* baker uses this flag to detect if image was initialized */
- for(ima= G.main->image.first; ima; ima= ima->id.next)
+ for(ima= G.main->image.first; ima; ima= ima->id.next) {
+ ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
ima->id.flag |= LIB_DOIT;
+ if (ibuf)
+ ibuf->userdata = NULL; /* use for masking if needed */
+ }
BLI_init_threads(&threads, do_bake_thread, re->r.threads);
@@ -2161,7 +2612,12 @@ int RE_bake_shade_all_selected(Render *re, int type, Object *actob)
memset(&handles[a], 0, sizeof(BakeShade));
handles[a].ssamp.shi[0].lay= re->scene->lay;
- handles[a].ssamp.shi[0].passflag= SCE_PASS_COMBINED;
+
+ if (type==RE_BAKE_SHADOW) {
+ handles[a].ssamp.shi[0].passflag= SCE_PASS_SHADOW;
+ } else {
+ handles[a].ssamp.shi[0].passflag= SCE_PASS_COMBINED;
+ }
handles[a].ssamp.shi[0].combinedflag= ~(SCE_PASS_SPEC);
handles[a].ssamp.shi[0].thread= a;
handles[a].ssamp.tot= 1;
@@ -2170,6 +2626,8 @@ int RE_bake_shade_all_selected(Render *re, int type, Object *actob)
handles[a].actob= actob;
handles[a].zspan= MEM_callocN(sizeof(ZSpan), "zspan for bake");
+ handles[a].usemask = usemask;
+
BLI_insert_thread(&threads, &handles[a]);
}
@@ -2184,23 +2642,52 @@ int RE_bake_shade_all_selected(Render *re, int type, Object *actob)
break;
}
- /* filter images */
+ /* filter and refresh images */
for(ima= G.main->image.first; ima; ima= ima->id.next) {
if((ima->id.flag & LIB_DOIT)==0) {
ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
- for(a=0; a<re->r.bake_filter; a++)
- IMB_filter_extend(ibuf);
+ if (re->r.bake_filter) {
+ if (usemask) {
+ /* extend the mask +2 pixels from the image,
+ * this is so colors dont blend in from outside */
+ char *temprect;
+
+ for(a=0; a<re->r.bake_filter; a++)
+ bake_mask_filter_extend((char *)ibuf->userdata, ibuf->x, ibuf->y);
+
+ temprect = MEM_dupallocN(ibuf->userdata);
+
+ /* expand twice to clear this many pixels, so they blend back in */
+ bake_mask_filter_extend(temprect, ibuf->x, ibuf->y);
+ bake_mask_filter_extend(temprect, ibuf->x, ibuf->y);
+
+ /* clear all pixels in the margin*/
+ bake_mask_clear(ibuf, temprect, BAKE_MASK_MARGIN);
+ MEM_freeN(temprect);
+ }
+
+ for(a=0; a<re->r.bake_filter; a++) {
+ /*the mask, ibuf->userdata - can be null, in this case only zero alpha is used */
+ IMB_filter_extend(ibuf, (char *)ibuf->userdata);
+ }
+
+ if (ibuf->userdata) {
+ MEM_freeN(ibuf->userdata);
+ ibuf->userdata= NULL;
+ }
+ }
ibuf->userflags |= IB_BITMAPDIRTY;
+ if (ibuf->rect_float) IMB_rect_from_float(ibuf);
}
}
/* calculate return value */
- for(a=0; a<re->r.threads; a++) {
+ for(a=0; a<re->r.threads; a++) {
vdone+= handles[a].vdone;
zbuf_free_span(handles[a].zspan);
MEM_freeN(handles[a].zspan);
- }
+ }
BLI_end_threads(&threads);
return vdone;
diff --git a/source/blender/render/intern/source/renderdatabase.c b/source/blender/render/intern/source/renderdatabase.c
index 79c87252fc2..d44b49cc706 100644
--- a/source/blender/render/intern/source/renderdatabase.c
+++ b/source/blender/render/intern/source/renderdatabase.c
@@ -104,7 +104,10 @@
#define RE_MCOL_ELEMS 4
#define RE_UV_ELEMS 2
#define RE_SURFNOR_ELEMS 3
+#define RE_RADFACE_ELEMS 1
#define RE_SIMPLIFY_ELEMS 2
+#define RE_FACE_ELEMS 1
+#define RE_NMAP_TANGENT_ELEMS 12
float *RE_vertren_get_sticky(ObjectRen *obr, VertRen *ver, int verify)
{
@@ -362,12 +365,43 @@ float *RE_vlakren_get_surfnor(ObjectRen *obr, VlakRen *vlak, int verify)
return surfnor + (vlak->index & 255)*RE_SURFNOR_ELEMS;
}
+float *RE_vlakren_get_nmap_tangent(ObjectRen *obr, VlakRen *vlak, int verify)
+{
+ float *tangent;
+ int nr= vlak->index>>8;
+
+ tangent= obr->vlaknodes[nr].tangent;
+ if(tangent==NULL) {
+ if(verify)
+ tangent= obr->vlaknodes[nr].tangent= MEM_callocN(256*RE_NMAP_TANGENT_ELEMS*sizeof(float), "tangent table");
+ else
+ return NULL;
+ }
+ return tangent + (vlak->index & 255)*RE_NMAP_TANGENT_ELEMS;
+}
+
+RadFace **RE_vlakren_get_radface(ObjectRen *obr, VlakRen *vlak, int verify)
+{
+ RadFace **radface;
+ int nr= vlak->index>>8;
+
+ radface= obr->vlaknodes[nr].radface;
+ if(radface==NULL) {
+ if(verify)
+ radface= obr->vlaknodes[nr].radface= MEM_callocN(256*RE_RADFACE_ELEMS*sizeof(void*), "radface table");
+ else
+ return NULL;
+ }
+ return radface + (vlak->index & 255)*RE_RADFACE_ELEMS;
+}
+
VlakRen *RE_vlakren_copy(ObjectRen *obr, VlakRen *vlr)
{
VlakRen *vlr1 = RE_findOrAddVlak(obr, obr->totvlak++);
MTFace *mtface, *mtface1;
MCol *mcol, *mcol1;
- float *surfnor, *surfnor1;
+ float *surfnor, *surfnor1, *tangent, *tangent1;
+ RadFace **radface, **radface1;
int i, index = vlr1->index;
char *name;
@@ -390,24 +424,31 @@ VlakRen *RE_vlakren_copy(ObjectRen *obr, VlakRen *vlr)
VECCOPY(surfnor1, surfnor);
}
+ tangent= RE_vlakren_get_nmap_tangent(obr, vlr, 0);
+ if(tangent) {
+ tangent1= RE_vlakren_get_nmap_tangent(obr, vlr1, 1);
+ memcpy(tangent1, tangent, sizeof(float)*RE_NMAP_TANGENT_ELEMS);
+ }
+
+ radface= RE_vlakren_get_radface(obr, vlr, 0);
+ if(radface) {
+ radface1= RE_vlakren_get_radface(obr, vlr1, 1);
+ *radface1= *radface;
+ }
+
return vlr1;
}
int RE_vlakren_get_normal(Render *re, ObjectInstanceRen *obi, VlakRen *vlr, float *nor)
{
- float xn, yn, zn, v1[3];
- float (*imat)[3]= obi->imat;
+ float v1[3], (*nmat)[3]= obi->nmat;
int flipped= 0;
if(obi->flag & R_TRANSFORMED) {
- xn= vlr->n[0];
- yn= vlr->n[1];
- zn= vlr->n[2];
+ VECCOPY(nor, vlr->n);
- /* transpose! */
- nor[0]= imat[0][0]*xn+imat[0][1]*yn+imat[0][2]*zn;
- nor[1]= imat[1][0]*xn+imat[1][1]*yn+imat[1][2]*zn;
- nor[2]= imat[2][0]*xn+imat[2][1]*yn+imat[2][2]*zn;
+ Mat3MulVecfl(nmat, nor);
+ Normalize(nor);
}
else
VECCOPY(nor, vlr->n);
@@ -442,16 +483,16 @@ void RE_set_customdata_names(ObjectRen *obr, CustomData *data)
DerivedMesh which stores the layers is freed */
CustomDataLayer *layer;
- int numlayers, i, mtfn, mcn;
+ int numtf = 0, numcol = 0, i, mtfn, mcn;
if (CustomData_has_layer(data, CD_MTFACE)) {
- numlayers= CustomData_number_of_layers(data, CD_MTFACE);
- obr->mtface= MEM_callocN(sizeof(*obr->mtface)*numlayers, "mtfacenames");
+ numtf= CustomData_number_of_layers(data, CD_MTFACE);
+ obr->mtface= MEM_callocN(sizeof(*obr->mtface)*numtf, "mtfacenames");
}
if (CustomData_has_layer(data, CD_MCOL)) {
- numlayers= CustomData_number_of_layers(data, CD_MCOL);
- obr->mcol= MEM_callocN(sizeof(*obr->mcol)*numlayers, "mcolnames");
+ numcol= CustomData_number_of_layers(data, CD_MCOL);
+ obr->mcol= MEM_callocN(sizeof(*obr->mcol)*numcol, "mcolnames");
}
for (i=0, mtfn=0, mcn=0; i < data->totlayer; i++) {
@@ -459,11 +500,12 @@ void RE_set_customdata_names(ObjectRen *obr, CustomData *data)
if (layer->type == CD_MTFACE) {
strcpy(obr->mtface[mtfn++], layer->name);
- obr->actmtface= layer->active_rnd;
+ obr->actmtface= CLAMPIS(layer->active_rnd, 0, numtf);
+ obr->bakemtface= layer->active;
}
else if (layer->type == CD_MCOL) {
strcpy(obr->mcol[mcn++], layer->name);
- obr->actmcol= layer->active_rnd;
+ obr->actmcol= CLAMPIS(layer->active_rnd, 0, numcol);
}
}
}
@@ -516,7 +558,7 @@ float *RE_strandren_get_surfnor(ObjectRen *obr, StrandRen *strand, int verify)
surfnor= obr->strandnodes[nr].surfnor;
if(surfnor==NULL) {
if(verify)
- surfnor= obr->strandnodes[nr].surfnor= MEM_callocN(256*RE_SURFNOR_ELEMS*sizeof(float), "surfnor table");
+ surfnor= obr->strandnodes[nr].surfnor= MEM_callocN(256*RE_SURFNOR_ELEMS*sizeof(float), "surfnor strand table");
else
return NULL;
}
@@ -536,7 +578,7 @@ float *RE_strandren_get_uv(ObjectRen *obr, StrandRen *strand, int n, char **name
float *uv= node->uv;
int size= (n+1)*256;
- node->uv= MEM_callocN(size*sizeof(float)*RE_UV_ELEMS, "Strand uv");
+ node->uv= MEM_callocN(size*sizeof(float)*RE_UV_ELEMS, "strand uv table");
if(uv) {
size= node->totuv*256;
@@ -570,7 +612,7 @@ MCol *RE_strandren_get_mcol(ObjectRen *obr, StrandRen *strand, int n, char **nam
MCol *mcol= node->mcol;
int size= (n+1)*256;
- node->mcol= MEM_callocN(size*sizeof(MCol)*RE_MCOL_ELEMS, "Strand mcol");
+ node->mcol= MEM_callocN(size*sizeof(MCol)*RE_MCOL_ELEMS, "strand mcol table");
if(mcol) {
size= node->totmcol*256;
@@ -599,13 +641,28 @@ float *RE_strandren_get_simplify(struct ObjectRen *obr, struct StrandRen *strand
simplify= obr->strandnodes[nr].simplify;
if(simplify==NULL) {
if(verify)
- simplify= obr->strandnodes[nr].simplify= MEM_callocN(256*RE_SIMPLIFY_ELEMS*sizeof(float), "simplify table");
+ simplify= obr->strandnodes[nr].simplify= MEM_callocN(256*RE_SIMPLIFY_ELEMS*sizeof(float), "simplify strand table");
else
return NULL;
}
return simplify + (strand->index & 255)*RE_SIMPLIFY_ELEMS;
}
+int *RE_strandren_get_face(ObjectRen *obr, StrandRen *strand, int verify)
+{
+ int *face;
+ int nr= strand->index>>8;
+
+ face= obr->strandnodes[nr].face;
+ if(face==NULL) {
+ if(verify)
+ face= obr->strandnodes[nr].face= MEM_callocN(256*RE_FACE_ELEMS*sizeof(int), "face strand table");
+ else
+ return NULL;
+ }
+ return face + (strand->index & 255)*RE_FACE_ELEMS;
+}
+
/* winspeed is exception, it is stored per instance */
float *RE_strandren_get_winspeed(ObjectInstanceRen *obi, StrandRen *strand, int verify)
{
@@ -616,7 +673,7 @@ float *RE_strandren_get_winspeed(ObjectInstanceRen *obi, StrandRen *strand, int
if(winspeed==NULL) {
if(verify) {
totvector= obi->obr->totvert + obi->obr->totstrand;
- winspeed= obi->vectors= MEM_callocN(totvector*RE_WINSPEED_ELEMS*sizeof(float), "winspeed table");
+ winspeed= obi->vectors= MEM_callocN(totvector*RE_WINSPEED_ELEMS*sizeof(float), "winspeed strand table");
}
else
return NULL;
@@ -671,14 +728,14 @@ StrandBuffer *RE_addStrandBuffer(ObjectRen *obr, int totvert)
strandbuf->totvert= totvert;
strandbuf->obr= obr;
- BLI_addtail(&obr->strandbufs, strandbuf);
+ obr->strandbuf= strandbuf;
return strandbuf;
}
/* ------------------------------------------------------------------------ */
-ObjectRen *RE_addRenderObject(Render *re, Object *ob, Object *par, int index, int psysindex)
+ObjectRen *RE_addRenderObject(Render *re, Object *ob, Object *par, int index, int psysindex, int lay)
{
ObjectRen *obr= MEM_callocN(sizeof(ObjectRen), "object render struct");
@@ -687,11 +744,7 @@ ObjectRen *RE_addRenderObject(Render *re, Object *ob, Object *par, int index, in
obr->par= par;
obr->index= index;
obr->psysindex= psysindex;
-
- if(!re->objecthash)
- re->objecthash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
- if(!BLI_ghash_lookup(re->objecthash, ob))
- BLI_ghash_insert(re->objecthash, ob, obr);
+ obr->lay= lay;
return obr;
}
@@ -737,6 +790,10 @@ void free_renderdata_vlaknodes(VlakTableNode *vlaknodes)
MEM_freeN(vlaknodes[a].mcol);
if(vlaknodes[a].surfnor)
MEM_freeN(vlaknodes[a].surfnor);
+ if(vlaknodes[a].tangent)
+ MEM_freeN(vlaknodes[a].tangent);
+ if(vlaknodes[a].radface)
+ MEM_freeN(vlaknodes[a].radface);
}
MEM_freeN(vlaknodes);
@@ -761,6 +818,8 @@ void free_renderdata_strandnodes(StrandTableNode *strandnodes)
MEM_freeN(strandnodes[a].surfnor);
if(strandnodes[a].simplify)
MEM_freeN(strandnodes[a].simplify);
+ if(strandnodes[a].face)
+ MEM_freeN(strandnodes[a].face);
}
MEM_freeN(strandnodes);
@@ -802,9 +861,12 @@ void free_renderdata_tables(Render *re)
obr->strandnodeslen= 0;
}
- for(strandbuf=obr->strandbufs.first; strandbuf; strandbuf=strandbuf->next)
+ strandbuf= obr->strandbuf;
+ if(strandbuf) {
if(strandbuf->vert) MEM_freeN(strandbuf->vert);
- BLI_freelistN(&obr->strandbufs);
+ if(strandbuf->bound) MEM_freeN(strandbuf->bound);
+ MEM_freeN(strandbuf);
+ }
if(obr->mtface)
MEM_freeN(obr->mtface);
@@ -822,27 +884,15 @@ void free_renderdata_tables(Render *re)
re->totinstance= 0;
re->instancetable.first= re->instancetable.last= NULL;
}
- else {
- BLI_freelistN(&re->instancetable);
-
- if(re->objecthash) {
- BLI_ghash_free(re->objecthash, NULL, NULL);
- re->objecthash= NULL;
- }
- }
if(re->sortedhalos) {
MEM_freeN(re->sortedhalos);
re->sortedhalos= NULL;
}
- if(re->strandbuckets) {
- free_buckets(re->strandbuckets);
- re->strandbuckets= NULL;
- }
-
BLI_freelistN(&re->customdata_names);
BLI_freelistN(&re->objecttable);
+ BLI_freelistN(&re->instancetable);
}
/* ------------------------------------------------------------------------ */
@@ -1257,13 +1307,11 @@ void project_renderdata(Render *re, void (*projectfunc)(float *, float mat[][4],
}
}
-
- project_strands(re, projectfunc, do_pano, do_buckets);
}
/* ------------------------------------------------------------------------- */
-void RE_addRenderInstance(Render *re, ObjectRen *obr, Object *ob, Object *par, int index, int psysindex, float mat[][4])
+ObjectInstanceRen *RE_addRenderInstance(Render *re, ObjectRen *obr, Object *ob, Object *par, int index, int psysindex, float mat[][4], int lay)
{
ObjectInstanceRen *obi;
float mat3[3][3];
@@ -1274,15 +1322,19 @@ void RE_addRenderInstance(Render *re, ObjectRen *obr, Object *ob, Object *par, i
obi->par= par;
obi->index= index;
obi->psysindex= psysindex;
+ obi->lay= lay;
if(mat) {
Mat4CpyMat4(obi->mat, mat);
Mat3CpyMat4(mat3, mat);
- Mat3Inv(obi->imat, mat3);
+ Mat3Inv(obi->nmat, mat3);
+ Mat3Transp(obi->nmat);
obi->flag |= R_DUPLI_TRANSFORMED;
}
BLI_addtail(&re->instancetable, obi);
+
+ return obi;
}
void RE_makeRenderInstances(Render *re)
@@ -1301,15 +1353,6 @@ void RE_makeRenderInstances(Render *re)
for(oldobi=re->instancetable.first; oldobi; oldobi=oldobi->next) {
*obi= *oldobi;
- if(!obi->obr) {
- /* dupli objects are created after object instances, so they were
- * stored in a object -> objectren hash, we do lookup of the actual
- * pointer here */
- if(re->objecthash && (obi->obr=BLI_ghash_lookup(re->objecthash, obi->ob)))
- while(obi->obr && obi->obr->psysindex != obi->psysindex)
- obi->obr= obi->obr->next;
- }
-
if(obi->obr) {
obi->prev= obi->next= NULL;
BLI_addtail(&newlist, obi);
@@ -1319,11 +1362,44 @@ void RE_makeRenderInstances(Render *re)
re->totinstance--;
}
- if(re->objecthash) {
- BLI_ghash_free(re->objecthash, NULL, NULL);
- re->objecthash= NULL;
- }
BLI_freelistN(&re->instancetable);
re->instancetable= newlist;
}
+int clip_render_object(float boundbox[][3], float *bounds, float winmat[][4])
+{
+ float mat[4][4], vec[4];
+ int a, fl, flag= -1;
+
+ Mat4CpyMat4(mat, winmat);
+
+ for(a=0; a<8; a++) {
+ vec[0]= (a & 1)? boundbox[0][0]: boundbox[1][0];
+ vec[1]= (a & 2)? boundbox[0][1]: boundbox[1][1];
+ vec[2]= (a & 4)? boundbox[0][2]: boundbox[1][2];
+ vec[3]= 1.0;
+ Mat4MulVec4fl(mat, vec);
+
+ fl= 0;
+ if(bounds) {
+ if(vec[0] > bounds[1]*vec[3]) fl |= 1;
+ if(vec[0]< bounds[0]*vec[3]) fl |= 2;
+ if(vec[1] > bounds[3]*vec[3]) fl |= 4;
+ if(vec[1]< bounds[2]*vec[3]) fl |= 8;
+ }
+ else {
+ if(vec[0] < -vec[3]) fl |= 1;
+ if(vec[0] > vec[3]) fl |= 2;
+ if(vec[1] < -vec[3]) fl |= 4;
+ if(vec[1] > vec[3]) fl |= 8;
+ }
+ if(vec[2] < -vec[3]) fl |= 16;
+ if(vec[2] > vec[3]) fl |= 32;
+
+ flag &= fl;
+ if(flag==0) return 0;
+ }
+
+ return flag;
+}
+
diff --git a/source/blender/render/intern/source/shadbuf.c b/source/blender/render/intern/source/shadbuf.c
index 8e37606cdf9..c53a2b68c9c 100644
--- a/source/blender/render/intern/source/shadbuf.c
+++ b/source/blender/render/intern/source/shadbuf.c
@@ -34,6 +34,7 @@
#include "DNA_material_types.h"
#include "BKE_global.h"
+#include "BKE_scene.h"
#include "BKE_utildefines.h"
#include "BLI_arithb.h"
@@ -54,7 +55,7 @@
/* XXX, could be better implemented... this is for endian issues
*/
-#if defined(__sgi) || defined(__sparc) || defined(__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
+#if defined(__sgi) || defined(__sparc) || defined(__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__hppa__) || defined (__BIG_ENDIAN__)
#define RCOMP 3
#define GCOMP 2
#define BCOMP 1
@@ -140,10 +141,11 @@ static float *give_jitter_tab(int samp)
}
-static void make_jitter_weight_tab(ShadBuf *shb, short filtertype)
+static void make_jitter_weight_tab(Render *re, ShadBuf *shb, short filtertype)
{
float *jit, totw= 0.0f;
- int a, tot=shb->samp*shb->samp;
+ int samp= get_render_shadow_samples(&re->r, shb->samp);
+ int a, tot=samp*samp;
shb->weight= MEM_mallocN(sizeof(float)*tot, "weight tab lamp");
@@ -169,7 +171,7 @@ static void compress_shadowbuf(ShadBuf *shb, int *rectz, int square)
{
ShadSampleBuf *shsample;
float dist;
- unsigned long *ztile;
+ uintptr_t *ztile;
int *rz, *rz1, verg, verg1, size= shb->size;
int a, x, y, minx, miny, byt1, byt2;
char *rc, *rcline, *ctile, *zt;
@@ -177,10 +179,10 @@ static void compress_shadowbuf(ShadBuf *shb, int *rectz, int square)
shsample= MEM_mallocN( sizeof(ShadSampleBuf), "shad sample buf");
BLI_addtail(&shb->buffers, shsample);
- shsample->zbuf= MEM_mallocN( sizeof(unsigned long)*(size*size)/256, "initshadbuf2");
+ shsample->zbuf= MEM_mallocN( sizeof(uintptr_t)*(size*size)/256, "initshadbuf2");
shsample->cbuf= MEM_callocN( (size*size)/256, "initshadbuf3");
- ztile= (unsigned long *)shsample->zbuf;
+ ztile= (uintptr_t *)shsample->zbuf;
ctile= shsample->cbuf;
/* help buffer */
@@ -235,7 +237,7 @@ static void compress_shadowbuf(ShadBuf *shb, int *rectz, int square)
}
if(byt1 && byt2) { /* only store byte */
*ctile= 1;
- *ztile= (unsigned long)MEM_mallocN(256+4, "tile1");
+ *ztile= (uintptr_t)MEM_mallocN(256+4, "tile1");
rz= (int *)*ztile;
*rz= *rz1;
@@ -245,7 +247,7 @@ static void compress_shadowbuf(ShadBuf *shb, int *rectz, int square)
}
else if(byt1) { /* only store short */
*ctile= 2;
- *ztile= (unsigned long)MEM_mallocN(2*256+4,"Tile2");
+ *ztile= (uintptr_t)MEM_mallocN(2*256+4,"Tile2");
rz= (int *)*ztile;
*rz= *rz1;
@@ -258,7 +260,7 @@ static void compress_shadowbuf(ShadBuf *shb, int *rectz, int square)
}
else { /* store triple */
*ctile= 3;
- *ztile= (unsigned long)MEM_mallocN(3*256,"Tile3");
+ *ztile= (uintptr_t)MEM_mallocN(3*256,"Tile3");
zt= (char *)*ztile;
rc= rcline;
@@ -288,15 +290,19 @@ static void shadowbuf_autoclip(Render *re, LampRen *lar)
Material *ma= NULL;
float minz, maxz, vec[3], viewmat[4][4], obviewmat[4][4];
unsigned int lay = -1;
- int i, a, ok= 1;
+ int i, a, maxtotvert, ok= 1;
char *clipflag;
minz= 1.0e30f; maxz= -1.0e30f;
Mat4CpyMat4(viewmat, lar->shb->viewmat);
- if(lar->mode & LA_LAYER) lay= lar->lay;
+ if(lar->mode & (LA_LAYER|LA_LAYER_SHADOW)) lay= lar->lay;
- clipflag= MEM_callocN(sizeof(char)*re->totvert, "autoclipflag");
+ maxtotvert= 0;
+ for(obr=re->objecttable.first; obr; obr=obr->next)
+ maxtotvert= MAX2(obr->totvert, maxtotvert);
+
+ clipflag= MEM_callocN(sizeof(char)*maxtotvert, "autoclipflag");
/* set clip in vertices when face visible */
for(i=0, obi=re->instancetable.first; obi; i++, obi=obi->next) {
@@ -321,7 +327,7 @@ static void shadowbuf_autoclip(Render *re, LampRen *lar)
if((ma->mode & MA_SHADBUF)==0) ok= 0;
}
- if(ok && (vlr->lay & lay)) {
+ if(ok && (obi->lay & lay)) {
clipflag[vlr->v1->index]= 1;
clipflag[vlr->v2->index]= 1;
clipflag[vlr->v3->index]= 1;
@@ -402,8 +408,8 @@ void makeshadowbuf(Render *re, LampRen *lar)
if(ELEM(lar->buftype, LA_SHADBUF_REGULAR, LA_SHADBUF_HALFWAY)) {
/* jitter, weights - not threadsafe! */
BLI_lock_thread(LOCK_CUSTOM1);
- shb->jit= give_jitter_tab(shb->samp);
- make_jitter_weight_tab(shb, lar->filtertype);
+ shb->jit= give_jitter_tab(get_render_shadow_samples(&re->r, shb->samp));
+ make_jitter_weight_tab(re, shb, lar->filtertype);
BLI_unlock_thread(LOCK_CUSTOM1);
shb->totbuf= lar->buffers;
@@ -536,7 +542,7 @@ void freeshadowbuf(LampRen *lar)
v= (shb->size*shb->size)/256;
for(shsample= shb->buffers.first; shsample; shsample= shsample->next) {
- long *ztile= shsample->zbuf;
+ intptr_t *ztile= shsample->zbuf;
char *ctile= shsample->cbuf;
for(b=0; b<v; b++, ztile++, ctile++)
@@ -630,7 +636,7 @@ static float readshadowbuf(ShadBuf *shb, ShadSampleBuf *shsample, int bias, int
else {
/* got warning on this for 64 bits.... */
/* but it's working code! in this case rz is not a pointer but zvalue (ton) */
- zsamp= (int) rz;
+ zsamp= GET_INT_FROM_POINTER(rz);
}
/* tricky stuff here; we use ints which can overflow easily with bias values */
@@ -648,11 +654,11 @@ static float readshadowbuf(ShadBuf *shb, ShadSampleBuf *shsample, int bias, int
/* the externally called shadow testing (reading) function */
/* return 1.0: no shadow at all */
-float testshadowbuf(ShadBuf *shb, float *rco, float *dxco, float *dyco, float inp)
+float testshadowbuf(Render *re, ShadBuf *shb, float *rco, float *dxco, float *dyco, float inp, float mat_bias)
{
ShadSampleBuf *shsample;
float fac, co[4], dx[3], dy[3], shadfac=0.0f;
- float xs1,ys1, siz, *jit, *weight, xres, yres;
+ float xs1,ys1, siz, *jit, *weight, xres, yres, biasf;
int xs, ys, zs, bias, *rz;
short a, num;
@@ -686,13 +692,16 @@ float testshadowbuf(ShadBuf *shb, float *rco, float *dxco, float *dyco, float in
zs= ((float)0x7FFFFFFF)*fac;
/* take num*num samples, increase area with fac */
- num= shb->samp*shb->samp;
+ num= get_render_shadow_samples(&re->r, shb->samp);
+ num= num*num;
fac= shb->soft;
+ if(mat_bias!=0.0f) biasf= shb->bias*mat_bias;
+ else biasf= shb->bias;
/* with inp==1.0, bias is half the size. correction value was 1.1, giving errors
on cube edges, with one side being almost frontal lighted (ton) */
- bias= (1.5f-inp*inp)*shb->bias;
-
+ bias= (1.5f-inp*inp)*biasf;
+
if(num==1) {
for(shsample= shb->buffers.first; shsample; shsample= shsample->next)
shadfac += readshadowbuf(shb, shsample, bias, (int)xs1, (int)ys1, zs);
@@ -807,7 +816,7 @@ static float readshadowbuf_halo(ShadBuf *shb, ShadSampleBuf *shsample, int xs, i
else {
/* same as before */
/* still working code! (ton) */
- zsamp= (int) rz;
+ zsamp= GET_INT_FROM_POINTER(rz);
}
/* NO schadow when sampled at 'eternal' distance */
@@ -1511,7 +1520,7 @@ static void isb_bsp_fillfaces(Render *re, LampRen *lar, ISBBranch *root)
minmaxf[2]= (2.0f*root->box.ymin - size-2.0f)/size;
minmaxf[3]= (2.0f*root->box.ymax - size+2.0f)/size;
- if(lar->mode & LA_LAYER) lay= lar->lay;
+ if(lar->mode & (LA_LAYER|LA_LAYER_SHADOW)) lay= lar->lay;
/* (ab)use zspan, since we use zbuffer clipping code */
zbuf_alloc_span(&zspan, size, size, re->clipcrop);
@@ -1552,7 +1561,7 @@ static void isb_bsp_fillfaces(Render *re, LampRen *lar, ISBBranch *root)
zspanstrand.shad_alpha= zspan.shad_alpha= ma->shad_alpha;
}
- if(ok && (vlr->lay & lay)) {
+ if(ok && (obi->lay & lay)) {
float hoco[4][4];
int c1, c2, c3, c4=0;
int d1, d2, d3, d4=0;
@@ -1743,7 +1752,7 @@ static void isb_make_buffer(RenderPart *pa, LampRen *lar)
ISBSample *samp, *samplebuf[16]; /* should be RE_MAX_OSA */
ISBBranch root;
MemArena *memarena;
- long *rd;
+ intptr_t *rd;
int *recto, *rectp, x, y, sindex, sample, bsp_err=0;
/* storage for shadow, per thread */
diff --git a/source/blender/render/intern/source/shadeinput.c b/source/blender/render/intern/source/shadeinput.c
index f937218cdb6..476330152ec 100644
--- a/source/blender/render/intern/source/shadeinput.c
+++ b/source/blender/render/intern/source/shadeinput.c
@@ -31,6 +31,7 @@
#include "MTC_matrixops.h"
#include "BLI_arithb.h"
+#include "BLI_blenlib.h"
#include "DNA_curve_types.h"
#include "DNA_group_types.h"
@@ -129,7 +130,7 @@ void shade_material_loop(ShadeInput *shi, ShadeResult *shr)
}
/* disable adding of sky for raytransp */
if(shi->mat->mode & MA_RAYTRANSP)
- if(shi->layflag & SCE_LAY_SKY)
+ if((shi->layflag & SCE_LAY_SKY) && (R.r.alphamode==R_ADDSKY))
shr->alpha= 1.0f;
}
}
@@ -161,11 +162,16 @@ void shade_input_do_shade(ShadeInput *shi, ShadeResult *shr)
}
/* MIST */
- if((R.wrld.mode & WO_MIST) && (shi->mat->mode & MA_NOMIST)==0 ) {
+ if((shi->passflag & SCE_PASS_MIST) || ((R.wrld.mode & WO_MIST) && (shi->mat->mode & MA_NOMIST)==0)) {
if(R.r.mode & R_ORTHO)
- alpha= mistfactor(-shi->co[2], shi->co);
+ shr->mist= mistfactor(-shi->co[2], shi->co);
else
- alpha= mistfactor(VecLength(shi->co), shi->co);
+ shr->mist= mistfactor(VecLength(shi->co), shi->co);
+ }
+ else shr->mist= 0.0f;
+
+ if((R.wrld.mode & WO_MIST) && (shi->mat->mode & MA_NOMIST)==0 ) {
+ alpha= shr->mist;
}
else alpha= 1.0f;
@@ -180,6 +186,8 @@ void shade_input_do_shade(ShadeInput *shi, ShadeResult *shr)
}
else shr->combined[3]= 1.0f;
+ /* add z */
+ shr->z= -shi->co[2];
}
/* **************************************************************************** */
@@ -209,19 +217,6 @@ void vlr_set_uv_indices(VlakRen *vlr, int *i1, int *i2, int *i3)
}
}
-static void normal_transform(float imat[][3], float *nor)
-{
- float xn, yn, zn;
-
- xn= nor[0];
- yn= nor[1];
- zn= nor[2];
-
- nor[0]= imat[0][0]*xn+imat[0][1]*yn+imat[0][2]*zn;
- nor[1]= imat[1][0]*xn+imat[1][1]*yn+imat[1][2]*zn;
- nor[2]= imat[2][0]*xn+imat[2][1]*yn+imat[2][2]*zn;
-}
-
/* copy data from face to ShadeInput, general case */
/* indices 0 1 2 3 only */
void shade_input_set_triangle_i(ShadeInput *shi, ObjectInstanceRen *obi, VlakRen *vlr, short i1, short i2, short i3)
@@ -231,7 +226,7 @@ void shade_input_set_triangle_i(ShadeInput *shi, ObjectInstanceRen *obi, VlakRen
shi->vlr= vlr;
shi->obi= obi;
shi->obr= obi->obr;
-
+
shi->v1= vpp[i1];
shi->v2= vpp[i2];
shi->v3= vpp[i3];
@@ -261,9 +256,9 @@ void shade_input_set_triangle_i(ShadeInput *shi, ObjectInstanceRen *obi, VlakRen
VECCOPY(shi->n3, shi->v3->n);
if(obi->flag & R_TRANSFORMED) {
- normal_transform(obi->imat, shi->n1);
- normal_transform(obi->imat, shi->n2);
- normal_transform(obi->imat, shi->n3);
+ Mat3MulVecfl(obi->nmat, shi->n1);
+ Mat3MulVecfl(obi->nmat, shi->n2);
+ Mat3MulVecfl(obi->nmat, shi->n3);
}
if(!(vlr->flag & (R_NOPUNOFLIP|R_TANGENT))) {
@@ -348,10 +343,19 @@ void shade_input_set_strand(ShadeInput *shi, StrandRen *strand, StrandPoint *spo
VECCOPY(shi->orignor, shi->facenor);
/* shade_input_set_normals equivalent */
- if(shi->mat->mode & MA_TANGENT_STR)
+ if(shi->mat->mode & MA_TANGENT_STR) {
VECCOPY(shi->vn, spoint->tan)
- else
- VECCOPY(shi->vn, spoint->nor)
+ }
+ else {
+ float cross[3];
+
+ Crossf(cross, spoint->co, spoint->tan);
+ Crossf(shi->vn, cross, spoint->tan);
+ Normalize(shi->vn);
+
+ if(INPR(shi->vn, shi->view) < 0.0f)
+ VecMulf(shi->vn, -1.0f);
+ }
VECCOPY(shi->vno, shi->vn);
}
@@ -374,6 +378,7 @@ void shade_input_set_strand_texco(ShadeInput *shi, StrandRen *strand, StrandVert
if(mode & (MA_TANGENT_V|MA_NORMAP_TANG)) {
VECCOPY(shi->tang, spoint->tan);
+ VECCOPY(shi->nmaptang, spoint->tan);
}
if(mode & MA_STR_SURFDIFF) {
@@ -388,7 +393,7 @@ void shade_input_set_strand_texco(ShadeInput *shi, StrandRen *strand, StrandVert
shi->surfdist= 0.0f;
for(sv=strand->vert; sv!=svert; sv++)
shi->surfdist+=VecLenf(sv->co, (sv+1)->co);
- shi->surfdist += 0.5f*(spoint->strandco+1.0f)*VecLenf(sv->co, (sv+1)->co);
+ shi->surfdist += spoint->t*VecLenf(sv->co, (sv+1)->co);
}
}
@@ -422,7 +427,7 @@ void shade_input_set_strand_texco(ShadeInput *shi, StrandRen *strand, StrandVert
}
if(texco & TEXCO_STRAND) {
- shi->strand= spoint->strandco;
+ shi->strandco= spoint->strandco;
if(shi->osatex) {
shi->dxstrand= spoint->dtstrandco;
@@ -438,6 +443,8 @@ void shade_input_set_strand_texco(ShadeInput *shi, StrandRen *strand, StrandVert
shi->totuv= 0;
shi->totcol= 0;
+ shi->actuv= obr->actmtface;
+ shi->actcol= obr->actmcol;
if(mode & (MA_VERTEXCOL|MA_VERTEXCOLP)) {
for (i=0; (mcol=RE_strandren_get_mcol(obr, strand, i, &name, 0)); i++) {
@@ -447,15 +454,15 @@ void shade_input_set_strand_texco(ShadeInput *shi, StrandRen *strand, StrandVert
shi->totcol++;
scol->name= name;
- scol->col[0]= cp[0]/255.0f;
- scol->col[1]= cp[1]/255.0f;
- scol->col[2]= cp[2]/255.0f;
+ scol->col[0]= cp[3]/255.0f;
+ scol->col[1]= cp[2]/255.0f;
+ scol->col[2]= cp[1]/255.0f;
}
if(shi->totcol) {
- shi->vcol[0]= shi->col[0].col[0];
- shi->vcol[1]= shi->col[0].col[1];
- shi->vcol[2]= shi->col[0].col[2];
+ shi->vcol[0]= shi->col[shi->actcol].col[0];
+ shi->vcol[1]= shi->col[shi->actcol].col[1];
+ shi->vcol[2]= shi->col[shi->actcol].col[2];
}
else {
shi->vcol[0]= 0.0f;
@@ -488,7 +495,7 @@ void shade_input_set_strand_texco(ShadeInput *shi, StrandRen *strand, StrandVert
suv->dyuv[1]= 0.0f;
}
- if((mode & MA_FACETEXTURE) && i==0) {
+ if((mode & MA_FACETEXTURE) && i==obr->actmtface) {
if((mode & (MA_VERTEXCOL|MA_VERTEXCOLP))==0) {
shi->vcol[0]= 1.0f;
shi->vcol[1]= 1.0f;
@@ -537,6 +544,7 @@ void shade_input_set_strand_texco(ShadeInput *shi, StrandRen *strand, StrandVert
if((mode & MA_TANGENT_V)==0) {
/* just prevent surprises */
shi->tang[0]= shi->tang[1]= shi->tang[2]= 0.0f;
+ shi->nmaptang[0]= shi->nmaptang[1]= shi->nmaptang[2]= 0.0f;
}
}
}
@@ -565,31 +573,25 @@ void shade_input_set_strand_texco(ShadeInput *shi, StrandRen *strand, StrandVert
}
}
-/* scanline pixel coordinates */
-/* requires set_triangle */
-void shade_input_set_viewco(ShadeInput *shi, float x, float y, float z)
+/* from scanline pixel coordinates to 3d coordinates, requires set_triangle */
+void shade_input_calc_viewco(ShadeInput *shi, float x, float y, float z, float *view, float *dxyview, float *co, float *dxco, float *dyco)
{
- float fac;
-
- /* currently in use for dithering (soft shadow), node preview, irregular shad */
- shi->xs= (int)(x);
- shi->ys= (int)(y);
+ /* returns not normalized, so is in viewplane coords */
+ calc_view_vector(view, x, y);
- calc_view_vector(shi->view, x, y); /* returns not normalized, so is in viewplane coords */
-
- /* wire cannot use normal for calculating shi->co */
if(shi->mat->mode & MA_WIRE) {
-
+ /* wire cannot use normal for calculating shi->co, so
+ * we reconstruct the coordinate less accurate */
if(R.r.mode & R_ORTHO)
- calc_renderco_ortho(shi->co, x, y, z);
+ calc_renderco_ortho(co, x, y, z);
else
- calc_renderco_zbuf(shi->co, shi->view, z);
+ calc_renderco_zbuf(co, view, z);
}
else {
- float dface, v1[3];
+ /* for non-wire, intersect with the triangle to get the exact coord */
+ float fac, dface, v1[3];
VECCOPY(v1, shi->v1->co);
-
if(shi->obi->flag & R_TRANSFORMED)
Mat4MulVecfl(shi->obi->mat, v1);
@@ -601,72 +603,98 @@ void shade_input_set_viewco(ShadeInput *shi, float x, float y, float z)
float fx= 2.0f/(R.winx*R.winmat[0][0]);
float fy= 2.0f/(R.winy*R.winmat[1][1]);
- shi->co[0]= (x - 0.5f*R.winx)*fx - R.winmat[3][0]/R.winmat[0][0];
- shi->co[1]= (y - 0.5f*R.winy)*fy - R.winmat[3][1]/R.winmat[1][1];
+ co[0]= (x - 0.5f*R.winx)*fx - R.winmat[3][0]/R.winmat[0][0];
+ co[1]= (y - 0.5f*R.winy)*fy - R.winmat[3][1]/R.winmat[1][1];
/* using a*x + b*y + c*z = d equation, (a b c) is normal */
if(shi->facenor[2]!=0.0f)
- shi->co[2]= (dface - shi->facenor[0]*shi->co[0] - shi->facenor[1]*shi->co[1])/shi->facenor[2];
+ co[2]= (dface - shi->facenor[0]*co[0] - shi->facenor[1]*co[1])/shi->facenor[2];
else
- shi->co[2]= 0.0f;
+ co[2]= 0.0f;
- if(shi->osatex || (R.r.mode & R_SHADOW) ) {
- shi->dxco[0]= fx;
- shi->dxco[1]= 0.0f;
+ if(dxco && dyco) {
+ dxco[0]= fx;
+ dxco[1]= 0.0f;
if(shi->facenor[2]!=0.0f)
- shi->dxco[2]= (shi->facenor[0]*fx)/shi->facenor[2];
+ dxco[2]= (shi->facenor[0]*fx)/shi->facenor[2];
else
- shi->dxco[2]= 0.0f;
+ dxco[2]= 0.0f;
- shi->dyco[0]= 0.0f;
- shi->dyco[1]= fy;
+ dyco[0]= 0.0f;
+ dyco[1]= fy;
if(shi->facenor[2]!=0.0f)
- shi->dyco[2]= (shi->facenor[1]*fy)/shi->facenor[2];
+ dyco[2]= (shi->facenor[1]*fy)/shi->facenor[2];
else
- shi->dyco[2]= 0.0f;
+ dyco[2]= 0.0f;
- if( (shi->mat->texco & TEXCO_REFL) ) {
- if(shi->co[2]!=0.0f) fac= 1.0f/shi->co[2]; else fac= 0.0f;
- shi->dxview= -R.viewdx*fac;
- shi->dyview= -R.viewdy*fac;
+ if(dxyview) {
+ if(co[2]!=0.0f) fac= 1.0f/co[2]; else fac= 0.0f;
+ dxyview[0]= -R.viewdx*fac;
+ dxyview[1]= -R.viewdy*fac;
}
}
}
else {
float div;
- div= shi->facenor[0]*shi->view[0] + shi->facenor[1]*shi->view[1] + shi->facenor[2]*shi->view[2];
+ div= shi->facenor[0]*view[0] + shi->facenor[1]*view[1] + shi->facenor[2]*view[2];
if (div!=0.0f) fac= dface/div;
else fac= 0.0f;
- shi->co[0]= fac*shi->view[0];
- shi->co[1]= fac*shi->view[1];
- shi->co[2]= fac*shi->view[2];
+ co[0]= fac*view[0];
+ co[1]= fac*view[1];
+ co[2]= fac*view[2];
/* pixel dx/dy for render coord */
- if(shi->osatex || (R.r.mode & R_SHADOW) ) {
+ if(dxco && dyco) {
float u= dface/(div - R.viewdx*shi->facenor[0]);
float v= dface/(div - R.viewdy*shi->facenor[1]);
- shi->dxco[0]= shi->co[0]- (shi->view[0]-R.viewdx)*u;
- shi->dxco[1]= shi->co[1]- (shi->view[1])*u;
- shi->dxco[2]= shi->co[2]- (shi->view[2])*u;
+ dxco[0]= co[0]- (view[0]-R.viewdx)*u;
+ dxco[1]= co[1]- (view[1])*u;
+ dxco[2]= co[2]- (view[2])*u;
- shi->dyco[0]= shi->co[0]- (shi->view[0])*v;
- shi->dyco[1]= shi->co[1]- (shi->view[1]-R.viewdy)*v;
- shi->dyco[2]= shi->co[2]- (shi->view[2])*v;
+ dyco[0]= co[0]- (view[0])*v;
+ dyco[1]= co[1]- (view[1]-R.viewdy)*v;
+ dyco[2]= co[2]- (view[2])*v;
- if( (shi->mat->texco & TEXCO_REFL) ) {
+ if(dxyview) {
if(fac!=0.0f) fac= 1.0f/fac;
- shi->dxview= -R.viewdx*fac;
- shi->dyview= -R.viewdy*fac;
+ dxyview[0]= -R.viewdx*fac;
+ dxyview[1]= -R.viewdy*fac;
}
}
}
}
/* cannot normalize earlier, code above needs it at viewplane level */
- Normalize(shi->view);
+ Normalize(view);
+}
+
+/* from scanline pixel coordinates to 3d coordinates, requires set_triangle */
+void shade_input_set_viewco(ShadeInput *shi, float x, float y, float xs, float ys, float z)
+{
+ float *dxyview= NULL, *dxco= NULL, *dyco= NULL;
+
+ /* currently in use for dithering (soft shadow), node preview, irregular shad */
+ shi->xs= (int)xs;
+ shi->ys= (int)ys;
+
+ /* original scanline coordinate without jitter */
+ shi->scanco[0]= x;
+ shi->scanco[1]= y;
+ shi->scanco[2]= z;
+
+ /* check if we need derivatives */
+ if(shi->osatex || (R.r.mode & R_SHADOW)) {
+ dxco= shi->dxco;
+ dyco= shi->dyco;
+
+ if((shi->mat->texco & TEXCO_REFL))
+ dxyview= &shi->dxview;
+ }
+
+ shade_input_calc_viewco(shi, xs, ys, z, shi->view, dxyview, shi->co, dxco, dyco);
}
/* calculate U and V, for scanline (silly render face u and v are in range -1 to 0) */
@@ -798,7 +826,7 @@ void shade_input_set_shade_texco(ShadeInput *shi)
int mode= shi->mode; /* or-ed result for all nodes */
short texco= shi->mat->texco;
- /* calculate dxno and tangents */
+ /* calculate dxno */
if(shi->vlr->flag & R_SMOOTH) {
if(shi->osatex && (texco & (TEXCO_NORM|TEXCO_REFL)) ) {
@@ -814,47 +842,68 @@ void shade_input_set_shade_texco(ShadeInput *shi)
shi->dyno[2]= dl*n3[2]-shi->dy_u*n1[2]-shi->dy_v*n2[2];
}
-
- /* qdn: normalmap tangent space */
- if (mode & (MA_TANGENT_V|MA_NORMAP_TANG) || R.flag & R_NEED_TANGENT) {
- float *s1, *s2, *s3;
+ }
+
+ /* calc tangents */
+ if (mode & (MA_TANGENT_V|MA_NORMAP_TANG) || R.flag & R_NEED_TANGENT) {
+ float *tangent, *s1, *s2, *s3;
+ float tl, tu, tv;
+
+ if(shi->vlr->flag & R_SMOOTH) {
+ tl= l;
+ tu= u;
+ tv= v;
+ }
+ else {
+ /* qdn: flat faces have tangents too,
+ could pick either one, using average here */
+ tl= 1.0f/3.0f;
+ tu= -1.0f/3.0f;
+ tv= -1.0f/3.0f;
+ }
+
+ shi->tang[0]= shi->tang[1]= shi->tang[2]= 0.0f;
+ shi->nmaptang[0]= shi->nmaptang[1]= shi->nmaptang[2]= 0.0f;
+
+ if(mode & MA_TANGENT_V) {
+ s1 = RE_vertren_get_tangent(obr, v1, 0);
+ s2 = RE_vertren_get_tangent(obr, v2, 0);
+ s3 = RE_vertren_get_tangent(obr, v3, 0);
- s1= RE_vertren_get_tangent(obr, v1, 0);
- s2= RE_vertren_get_tangent(obr, v2, 0);
- s3= RE_vertren_get_tangent(obr, v3, 0);
if(s1 && s2 && s3) {
- shi->tang[0]= (l*s3[0] - u*s1[0] - v*s2[0]);
- shi->tang[1]= (l*s3[1] - u*s1[1] - v*s2[1]);
- shi->tang[2]= (l*s3[2] - u*s1[2] - v*s2[2]);
+ shi->tang[0]= (tl*s3[0] - tu*s1[0] - tv*s2[0]);
+ shi->tang[1]= (tl*s3[1] - tu*s1[1] - tv*s2[1]);
+ shi->tang[2]= (tl*s3[2] - tu*s1[2] - tv*s2[2]);
if(obi->flag & R_TRANSFORMED)
- normal_transform(obi->imat, shi->tang);
+ Mat3MulVecfl(obi->nmat, shi->tang);
- /* qdn: normalize just in case */
Normalize(shi->tang);
+ VECCOPY(shi->nmaptang, shi->tang);
}
- else shi->tang[0]= shi->tang[1]= shi->tang[2]= 0.0f;
}
- }
- else {
- /* qdn: normalmap tangent space */
- if (mode & (MA_TANGENT_V|MA_NORMAP_TANG) || R.flag & R_NEED_TANGENT) {
- /* qdn: flat faces have tangents too,
- could pick either one, using average here */
- float *s1 = RE_vertren_get_tangent(obr, v1, 0);
- float *s2 = RE_vertren_get_tangent(obr, v2, 0);
- float *s3 = RE_vertren_get_tangent(obr, v3, 0);
- if (s1 && s2 && s3) {
- shi->tang[0] = (s1[0] + s2[0] + s3[0]);
- shi->tang[1] = (s1[1] + s2[1] + s3[1]);
- shi->tang[2] = (s1[2] + s2[2] + s3[2]);
+
+ if(mode & MA_NORMAP_TANG || R.flag & R_NEED_TANGENT) {
+ tangent= RE_vlakren_get_nmap_tangent(obr, shi->vlr, 0);
+
+ if(tangent) {
+ int j1= shi->i1, j2= shi->i2, j3= shi->i3;
+
+ vlr_set_uv_indices(shi->vlr, &j1, &j2, &j3);
+
+ s1= &tangent[j1*3];
+ s2= &tangent[j2*3];
+ s3= &tangent[j3*3];
+
+ shi->nmaptang[0]= (tl*s3[0] - tu*s1[0] - tv*s2[0]);
+ shi->nmaptang[1]= (tl*s3[1] - tu*s1[1] - tv*s2[1]);
+ shi->nmaptang[2]= (tl*s3[2] - tu*s1[2] - tv*s2[2]);
if(obi->flag & R_TRANSFORMED)
- normal_transform(obi->imat, shi->tang);
+ Mat3MulVecfl(obi->nmat, shi->nmaptang);
- Normalize(shi->tang);
+ Normalize(shi->nmaptang);
}
- else shi->tang[0]= shi->tang[1]= shi->tang[2]= 0.0f;
}
}
@@ -864,7 +913,7 @@ void shade_input_set_shade_texco(ShadeInput *shi)
if(surfnor) {
VECCOPY(shi->surfnor, surfnor)
if(obi->flag & R_TRANSFORMED)
- normal_transform(obi->imat, shi->surfnor);
+ Mat3MulVecfl(obi->nmat, shi->surfnor);
}
else
VECCOPY(shi->surfnor, shi->vn)
@@ -919,6 +968,8 @@ void shade_input_set_shade_texco(ShadeInput *shi)
shi->dylo[2]= dl*o3[2]-shi->dy_u*o1[2]-shi->dy_v*o2[2];
}
}
+
+ VECCOPY(shi->duplilo, obi->dupliorco);
}
if(texco & TEXCO_GLOB) {
@@ -933,7 +984,7 @@ void shade_input_set_shade_texco(ShadeInput *shi)
}
if(texco & TEXCO_STRAND) {
- shi->strand= (l*v3->accum - u*v1->accum - v*v2->accum);
+ shi->strandco= (l*v3->accum - u*v1->accum - v*v2->accum);
if(shi->osatex) {
dl= shi->dx_u+shi->dx_v;
shi->dxstrand= dl*v3->accum-shi->dx_u*v1->accum-shi->dx_v*v2->accum;
@@ -975,9 +1026,9 @@ void shade_input_set_shade_texco(ShadeInput *shi)
}
if(shi->totcol) {
- shi->vcol[0]= shi->col[0].col[0];
- shi->vcol[1]= shi->col[0].col[1];
- shi->vcol[2]= shi->col[0].col[2];
+ shi->vcol[0]= shi->col[shi->actcol].col[0];
+ shi->vcol[1]= shi->col[shi->actcol].col[1];
+ shi->vcol[2]= shi->col[shi->actcol].col[2];
shi->vcol[3]= 1.0f;
}
else {
@@ -1033,6 +1084,10 @@ void shade_input_set_shade_texco(ShadeInput *shi)
}
}
+ shi->dupliuv[0]= -1.0f + 2.0f*obi->dupliuv[0];
+ shi->dupliuv[1]= -1.0f + 2.0f*obi->dupliuv[1];
+ shi->dupliuv[2]= 0.0f;
+
if(shi->totuv == 0) {
ShadeInputUV *suv= &shi->uv[0];
@@ -1097,6 +1152,7 @@ void shade_input_set_shade_texco(ShadeInput *shi)
if((mode & MA_TANGENT_V)==0) {
/* just prevent surprises */
shi->tang[0]= shi->tang[1]= shi->tang[2]= 0.0f;
+ shi->nmaptang[0]= shi->nmaptang[1]= shi->nmaptang[2]= 0.0f;
}
}
}
@@ -1181,7 +1237,9 @@ void shade_input_set_shade_texco(ShadeInput *shi)
}
}
}
- }
+ } /* else {
+ Note! For raytracing winco is not set, important because thus means all shader input's need to have their variables set to zero else in-initialized values are used
+ */
}
/* ****************** ShadeSample ************************************** */
@@ -1201,8 +1259,9 @@ void shade_input_initialize(ShadeInput *shi, RenderPart *pa, RenderLayer *rl, in
shi->combinedflag= ~rl->pass_xor;
shi->mat_override= rl->mat_override;
shi->light_override= rl->light_override;
-
+// shi->rl= rl;
/* note shi.depth==0 means first hit, not raytracing */
+
}
/* initialize per part, not per pixel! */
@@ -1217,7 +1276,7 @@ void shade_sample_initialize(ShadeSample *ssamp, RenderPart *pa, RenderLayer *rl
memset(&ssamp->shr[a], 0, sizeof(ShadeResult));
}
- ssamp->samplenr= 0; /* counter, detect shadow-reuse for shaders */
+ get_sample_layers(pa, rl, ssamp->rlpp);
}
/* Do AO or (future) GI */
@@ -1228,19 +1287,22 @@ void shade_samples_do_AO(ShadeSample *ssamp)
if(!(R.r.mode & R_SHADOW))
return;
- if(!(R.r.mode & R_RAYTRACE))
+ if(!(R.r.mode & R_RAYTRACE) && !(R.wrld.ao_gather_method == WO_AOGATHER_APPROX))
return;
- if(R.wrld.mode & WO_AMB_OCC)
- if(ssamp->shi[0].passflag & (SCE_PASS_COMBINED|SCE_PASS_AO))
+ if(R.wrld.mode & WO_AMB_OCC) {
+ shi= &ssamp->shi[0];
+
+ if(((shi->passflag & SCE_PASS_COMBINED) && (shi->combinedflag & SCE_PASS_AO))
+ || (shi->passflag & SCE_PASS_AO))
for(sample=0, shi= ssamp->shi; sample<ssamp->tot; shi++, sample++)
if(!(shi->mode & MA_SHLESS))
ambient_occlusion(shi); /* stores in shi->ao[] */
-
+ }
}
-static void shade_samples_fill_with_ps(ShadeSample *ssamp, PixStr *ps, int x, int y)
+void shade_samples_fill_with_ps(ShadeSample *ssamp, PixStr *ps, int x, int y)
{
ShadeInput *shi;
float xs, ys;
@@ -1259,15 +1321,17 @@ static void shade_samples_fill_with_ps(ShadeSample *ssamp, PixStr *ps, int x, in
for(samp=0; samp<R.osa; samp++) {
if(curmask & (1<<samp)) {
- xs= (float)x + R.jit[samp][0] + 0.5f; /* zbuffer has this inverse corrected, ensures xs,ys are inside pixel */
+ /* zbuffer has this inverse corrected, ensures xs,ys are inside pixel */
+ xs= (float)x + R.jit[samp][0] + 0.5f;
ys= (float)y + R.jit[samp][1] + 0.5f;
if(shi_cp)
shade_input_copy_triangle(shi, shi-1);
shi->mask= (1<<samp);
- shi->samplenr= ssamp->samplenr++;
- shade_input_set_viewco(shi, xs, ys, (float)ps->z);
+// shi->rl= ssamp->rlpp[samp];
+ shi->samplenr= R.shadowsamplenr[shi->thread]++; /* this counter is not being reset per pixel */
+ shade_input_set_viewco(shi, x, y, xs, ys, (float)ps->z);
shade_input_set_uv(shi);
shade_input_set_normals(shi);
@@ -1286,9 +1350,10 @@ static void shade_samples_fill_with_ps(ShadeSample *ssamp, PixStr *ps, int x, in
xs= (float)x + 0.5f;
ys= (float)y + 0.5f;
}
+
shi->mask= curmask;
- shi->samplenr= ssamp->samplenr++;
- shade_input_set_viewco(shi, xs, ys, (float)ps->z);
+ shi->samplenr= R.shadowsamplenr[shi->thread]++;
+ shade_input_set_viewco(shi, x, y, xs, ys, (float)ps->z);
shade_input_set_uv(shi);
shade_input_set_normals(shi);
shi++;
diff --git a/source/blender/render/intern/source/shadeoutput.c b/source/blender/render/intern/source/shadeoutput.c
index a08046da0da..4c627056c1d 100644
--- a/source/blender/render/intern/source/shadeoutput.c
+++ b/source/blender/render/intern/source/shadeoutput.c
@@ -43,6 +43,7 @@
#include "DNA_material_types.h"
/* local include */
+#include "occlusion.h"
#include "renderpipeline.h"
#include "render_types.h"
#include "pixelblending.h"
@@ -354,7 +355,7 @@ void renderspothalo(ShadeInput *shi, float *col, float alpha)
if(lar->type==LA_SPOT && (lar->mode & LA_HALO) && lar->haint>0) {
if(lar->mode & LA_LAYER)
- if(shi->vlr && (lar->lay & shi->vlr->lay)==0)
+ if(shi->vlr && (lar->lay & shi->obi->lay)==0)
continue;
if((lar->lay & shi->lay)==0)
continue;
@@ -428,10 +429,6 @@ static float area_lamp_energy(float (*area)[3], float *co, float *vn)
double cross[4][3]; /* cross products of this */
double rad[4]; /* angles between vecs */
- /* extra test for dot */
- if ( INPR(co, vn) <= 0.0f)
- return 0.0f;
-
VECSUB(vec[0], co, area[0]);
VECSUB(vec[1], co, area[1]);
VECSUB(vec[2], co, area[2]);
@@ -480,8 +477,12 @@ static float area_lamp_energy_multisample(LampRen *lar, float *co, float *vn)
float *jitlamp= lar->jitter, vec[3];
float area[4][3], intens= 0.0f;
int a= lar->ray_totsamp;
-
-
+
+ /* test if co is behind lamp */
+ VECSUB(vec, co, lar->co);
+ if(INPR(vec, lar->vec) < 0.0f)
+ return 0.0f;
+
while(a--) {
vec[0]= jitlamp[0];
vec[1]= jitlamp[1];
@@ -1006,8 +1007,9 @@ static void do_specular_ramp(ShadeInput *shi, float is, float t, float *spec)
/* pure AO, check for raytrace and world should have been done */
void ambient_occlusion(ShadeInput *shi)
{
-
- if((R.r.mode & R_RAYTRACE) && shi->mat->amb!=0.0f)
+ if((R.wrld.ao_gather_method == WO_AOGATHER_APPROX) && shi->mat->amb!=0.0f)
+ sample_occ(&R, shi);
+ else if((R.r.mode & R_RAYTRACE) && shi->mat->amb!=0.0f)
ray_ao(shi, shi->ao);
else
shi->ao[0]= shi->ao[1]= shi->ao[2]= 1.0f;
@@ -1017,25 +1019,28 @@ void ambient_occlusion(ShadeInput *shi)
/* wrld mode was checked for */
void ambient_occlusion_to_diffuse(ShadeInput *shi, float *diff)
{
-
- if((R.r.mode & R_RAYTRACE) && shi->mat->amb!=0.0f) {
- float f= R.wrld.aoenergy*shi->mat->amb;
-
- if (R.wrld.aomix==WO_AOADDSUB) {
- diff[0] = 2.0f*shi->ao[0]-1.0f;
- diff[1] = 2.0f*shi->ao[1]-1.0f;
- diff[2] = 2.0f*shi->ao[2]-1.0f;
- }
- else if (R.wrld.aomix==WO_AOSUB) {
- diff[0] = shi->ao[0]-1.0f;
- diff[1] = shi->ao[1]-1.0f;
- diff[2] = shi->ao[2]-1.0f;
- }
- else {
- VECCOPY(diff, shi->ao);
+ if((R.r.mode & R_RAYTRACE) || R.wrld.ao_gather_method == WO_AOGATHER_APPROX) {
+ if(shi->mat->amb!=0.0f) {
+ float f= R.wrld.aoenergy*shi->mat->amb;
+
+ if (R.wrld.aomix==WO_AOADDSUB) {
+ diff[0] = 2.0f*shi->ao[0]-1.0f;
+ diff[1] = 2.0f*shi->ao[1]-1.0f;
+ diff[2] = 2.0f*shi->ao[2]-1.0f;
+ }
+ else if (R.wrld.aomix==WO_AOSUB) {
+ diff[0] = shi->ao[0]-1.0f;
+ diff[1] = shi->ao[1]-1.0f;
+ diff[2] = shi->ao[2]-1.0f;
+ }
+ else {
+ VECCOPY(diff, shi->ao);
+ }
+
+ VECMUL(diff, f);
}
-
- VECMUL(diff, f);
+ else
+ diff[0]= diff[1]= diff[2]= 0.0f;
}
else
diff[0]= diff[1]= diff[2]= 0.0f;
@@ -1054,7 +1059,7 @@ void lamp_get_shadow(LampRen *lar, ShadeInput *shi, float inp, float *shadfac, i
if(lar->buftype==LA_SHADBUF_IRREGULAR)
shadfac[3]= ISB_getshadow(shi, lar->shb);
else
- shadfac[3] = testshadowbuf(lar->shb, shi->co, shi->dxco, shi->dyco, inp);
+ shadfac[3] = testshadowbuf(&R, lar->shb, shi->co, shi->dxco, shi->dyco, inp, shi->mat->lbias);
}
else if(lar->mode & LA_SHAD_RAY) {
ray_shadow(shi, lar, shadfac);
@@ -1174,15 +1179,18 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
{
Material *ma= shi->mat;
VlakRen *vlr= shi->vlr;
- float lv[3], lampdist, lacol[3], shadfac[4];
+ float lv[3], lampdist, lacol[3], shadfac[4], lashdw[3];
float i, is, i_noshad, inp, *vn, *view, vnor[3], phongcorr=1.0f;
float visifac;
vn= shi->vn;
view= shi->view;
- if (lar->energy == 0.0) return;
+ if (lar->energy == 0.0) return;
+ /* only shadow lamps shouldn't affect shadow-less materials at all */
+ if ((lar->mode & LA_ONLYSHADOW) && (!(ma->mode & MA_SHADOW) || !(R.r.mode & R_SHADOW)))
+ return;
/* optimisation, don't render fully black lamps */
if (!(lar->mode & LA_TEXTURE) && (lar->r + lar->g + lar->b == 0.0f))
return;
@@ -1211,7 +1219,12 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
lacol[1]= lar->g;
lacol[2]= lar->b;
- if(lar->mode & LA_TEXTURE) do_lamp_tex(lar, lv, shi, lacol);
+ lashdw[0]= lar->shdwr;
+ lashdw[1]= lar->shdwg;
+ lashdw[2]= lar->shdwb;
+
+ if(lar->mode & LA_TEXTURE) do_lamp_tex(lar, lv, shi, lacol, LA_TEXTURE);
+ if(lar->mode & LA_SHAD_TEX) do_lamp_tex(lar, lv, shi, lashdw, LA_SHAD_TEX);
/* tangent case; calculate fake face normal, aligned with lampvector */
/* note, vnor==vn is used as tangent trigger for buffer shadow */
@@ -1223,6 +1236,7 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
Crossf(nstrand, vn, cross);
blend= INPR(nstrand, shi->surfnor);
+ blend= 1.0f - blend;
CLAMP(blend, 0.0f, 1.0f);
VecLerpf(vnor, nstrand, shi->surfnor, blend);
@@ -1231,6 +1245,7 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
else {
Crossf(cross, lv, vn);
Crossf(vnor, cross, vn);
+ Normalize(vnor);
}
if(ma->strand_surfnor > 0.0f) {
@@ -1248,6 +1263,7 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
float cross[3];
Crossf(cross, lv, shi->tang);
Crossf(vnor, cross, shi->tang);
+ Normalize(vnor);
vnor[0]= -vnor[0];vnor[1]= -vnor[1];vnor[2]= -vnor[2];
vn= vnor;
}
@@ -1297,7 +1313,10 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
else is= inp; // Lambert
}
- /* i is diffuse */
+ /* 'is' is diffuse */
+ if((ma->shade_flag & MA_CUBIC) && is>0.0f && is<1.0f)
+ is= 3.0*is*is - 2.0*is*is*is; // nicer termination of shades
+
i= is*phongcorr;
if(i>0.0f) {
@@ -1328,13 +1347,13 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
if((lar->mode & LA_ONLYSHADOW) && i>0.0) {
shadfac[3]= i*lar->energy*(1.0f-shadfac[3]);
- shr->shad[0] -= shadfac[3]*shi->r;
- shr->shad[1] -= shadfac[3]*shi->g;
- shr->shad[2] -= shadfac[3]*shi->b;
+ shr->shad[0] -= shadfac[3]*shi->r*(1.0f-lashdw[0]);
+ shr->shad[1] -= shadfac[3]*shi->g*(1.0f-lashdw[1]);
+ shr->shad[2] -= shadfac[3]*shi->b*(1.0f-lashdw[2]);
- shr->spec[0] -= shadfac[3]*shi->specr;
- shr->spec[1] -= shadfac[3]*shi->specg;
- shr->spec[2] -= shadfac[3]*shi->specb;
+ shr->spec[0] -= shadfac[3]*shi->specr*(1.0f-lashdw[0]);
+ shr->spec[1] -= shadfac[3]*shi->specg*(1.0f-lashdw[1]);
+ shr->spec[2] -= shadfac[3]*shi->specb*(1.0f-lashdw[2]);
return;
}
@@ -1352,6 +1371,10 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
else
add_to_diffuse(shr->shad, shi, is, i*lacol[0], i*lacol[1], i*lacol[2]);
}
+ /* add light for colored shadow */
+ if (i_noshad>i && !(lashdw[0]==0 && lashdw[1]==0 && lashdw[2]==0)) {
+ add_to_diffuse(shr->shad, shi, is, lashdw[0]*(i_noshad-i)*lacol[0], lashdw[1]*(i_noshad-i)*lacol[1], lashdw[2]*(i_noshad-i)*lacol[2]);
+ }
if(i_noshad>0.0f) {
if(passflag & (SCE_PASS_DIFFUSE|SCE_PASS_SHADOW)) {
if(ma->mode & MA_SHADOW_TRA)
@@ -1365,6 +1388,8 @@ static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int
}
/* specularity */
+ shadfac[3]*= phongcorr; /* note, shadfac not allowed to be stored nonlocal */
+
if(shadfac[3]>0.0f && shi->spec!=0.0f && !(lar->mode & LA_NO_SPEC) && !(lar->mode & LA_ONLYSHADOW)) {
if(!(passflag & (SCE_PASS_COMBINED|SCE_PASS_SPEC)));
@@ -1435,10 +1460,10 @@ static void shade_lamp_loop_only_shadow(ShadeInput *shi, ShadeResult *shr)
LampRen *lar;
GroupObject *go;
float inpr, lv[3];
- float *vn, *view, shadfac[4];
+ float *view, shadfac[4];
float ir, accum, visifac, lampdist;
- vn= shi->vn;
+
view= shi->view;
accum= ir= 0.0f;
@@ -1451,7 +1476,7 @@ static void shade_lamp_loop_only_shadow(ShadeInput *shi, ShadeResult *shr)
/* yafray: ignore shading by photonlights, not used in Blender */
if (lar->type==LA_YF_PHOTON) continue;
- if(lar->mode & LA_LAYER) if((lar->lay & shi->vlr->lay)==0) continue;
+ if(lar->mode & LA_LAYER) if((lar->lay & shi->obi->lay)==0) continue;
if((lar->lay & shi->lay)==0) continue;
if(lar->shb || (lar->mode & LA_SHAD_RAY)) {
@@ -1501,8 +1526,10 @@ static void shade_lamp_loop_only_shadow(ShadeInput *shi, ShadeResult *shr)
}
}
+/* let's map negative light as if it mirrors positive light, otherwise negative values disappear */
static void wrld_exposure_correct(float *diff)
{
+
diff[0]= R.wrld.linfac*(1.0f-exp( diff[0]*R.wrld.logfac) );
diff[1]= R.wrld.linfac*(1.0f-exp( diff[1]*R.wrld.logfac) );
diff[2]= R.wrld.linfac*(1.0f-exp( diff[2]*R.wrld.logfac) );
@@ -1511,7 +1538,6 @@ static void wrld_exposure_correct(float *diff)
void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
{
Material *ma= shi->mat;
- VlakRen *vlr= shi->vlr;
int passflag= shi->passflag;
memset(shr, 0, sizeof(ShadeResult));
@@ -1541,6 +1567,24 @@ void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
shr->col[1]= shi->g*shi->alpha;
shr->col[2]= shi->b*shi->alpha;
shr->col[3]= shi->alpha;
+
+ if((ma->sss_flag & MA_DIFF_SSS) && !sss_pass_done(&R, ma)) {
+ if(ma->sss_texfac == 0.0f) {
+ shi->r= shi->g= shi->b= shi->alpha= 1.0f;
+ shr->col[0]= shr->col[1]= shr->col[2]= shr->col[3]= 1.0f;
+ }
+ else {
+ shi->r= pow(shi->r, ma->sss_texfac);
+ shi->g= pow(shi->g, ma->sss_texfac);
+ shi->b= pow(shi->b, ma->sss_texfac);
+ shi->alpha= pow(shi->alpha, ma->sss_texfac);
+
+ shr->col[0]= pow(shr->col[0], ma->sss_texfac);
+ shr->col[1]= pow(shr->col[1], ma->sss_texfac);
+ shr->col[2]= pow(shr->col[2], ma->sss_texfac);
+ shr->col[3]= pow(shr->col[3], ma->sss_texfac);
+ }
+ }
}
if(ma->mode & MA_SHLESS) {
@@ -1565,7 +1609,8 @@ void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
/* AO pass */
if(R.wrld.mode & WO_AMB_OCC) {
- if(passflag & (SCE_PASS_COMBINED|SCE_PASS_AO)) {
+ if(((passflag & SCE_PASS_COMBINED) && (shi->combinedflag & SCE_PASS_AO))
+ || (passflag & SCE_PASS_AO)) {
/* AO was calculated for scanline already */
if(shi->depth)
ambient_occlusion(shi);
@@ -1588,7 +1633,7 @@ void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
if (lar->type==LA_YF_PHOTON) continue;
/* test for lamp layer */
- if(lar->mode & LA_LAYER) if((lar->lay & vlr->lay)==0) continue;
+ if(lar->mode & LA_LAYER) if((lar->lay & shi->obi->lay)==0) continue;
if((lar->lay & shi->lay)==0) continue;
/* accumulates in shr->diff and shr->spec and shr->shad (diffuse with shadow!) */
@@ -1606,20 +1651,26 @@ void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
if (shr->shad[2] < 0) shr->shad[2] = 0;
if(ma->sss_flag & MA_DIFF_SSS) {
- float sss[3], col[3], texfac= ma->sss_texfac;
+ float sss[3], col[3], invalpha, texfac= ma->sss_texfac;
/* this will return false in the preprocess stage */
if(sample_sss(&R, ma, shi->co, sss)) {
+ invalpha= (shr->col[3] > FLT_EPSILON)? 1.0f/shr->col[3]: 1.0f;
+
if(texfac==0.0f) {
VECCOPY(col, shr->col);
+ VecMulf(col, invalpha);
}
else if(texfac==1.0f) {
col[0]= col[1]= col[2]= 1.0f;
+ VecMulf(col, invalpha);
}
else {
- col[0]= pow(shr->col[0], 1.0f-texfac);
- col[1]= pow(shr->col[1], 1.0f-texfac);
- col[2]= pow(shr->col[2], 1.0f-texfac);
+ VECCOPY(col, shr->col);
+ VecMulf(col, invalpha);
+ col[0]= pow(col[0], 1.0f-texfac);
+ col[1]= pow(col[1], 1.0f-texfac);
+ col[2]= pow(col[2], 1.0f-texfac);
}
shr->diff[0]= sss[0]*col[0];
@@ -1627,9 +1678,9 @@ void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
shr->diff[2]= sss[2]*col[2];
if(shi->combinedflag & SCE_PASS_SHADOW) {
- shr->shad[0]= sss[0]*col[0];
- shr->shad[1]= sss[1]*col[1];
- shr->shad[2]= sss[2]*col[2];
+ shr->shad[0]= shr->diff[0];
+ shr->shad[1]= shr->diff[1];
+ shr->shad[2]= shr->diff[2];
}
}
}
@@ -1647,7 +1698,7 @@ void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
}
/* exposure correction */
- if(R.wrld.exp!=0.0f || R.wrld.range!=1.0f) {
+ if((R.wrld.exp!=0.0f || R.wrld.range!=1.0f) && !R.sss_points) {
wrld_exposure_correct(shr->combined); /* has no spec! */
wrld_exposure_correct(shr->spec);
}
@@ -1671,10 +1722,16 @@ void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
shr->alpha= shi->alpha;
/* from now stuff everything in shr->combined: ambient, AO, radio, ramps, exposure */
- if(!(ma->sss_flag & MA_DIFF_SSS) || !has_sss_tree(&R, ma)) {
- shr->combined[0]+= shi->ambr + shi->r*shi->amb*shi->rad[0];
- shr->combined[1]+= shi->ambg + shi->g*shi->amb*shi->rad[1];
- shr->combined[2]+= shi->ambb + shi->b*shi->amb*shi->rad[2];
+ if(!(ma->sss_flag & MA_DIFF_SSS) || !sss_pass_done(&R, ma)) {
+ shr->combined[0]+= shi->ambr;
+ shr->combined[1]+= shi->ambg;
+ shr->combined[2]+= shi->ambb;
+
+ if(shi->combinedflag & SCE_PASS_RADIO) {
+ shr->combined[0]+= shi->r*shi->amb*shi->rad[0];
+ shr->combined[1]+= shi->g*shi->amb*shi->rad[1];
+ shr->combined[2]+= shi->b*shi->amb*shi->rad[2];
+ }
/* add AO in combined? */
if(R.wrld.mode & WO_AMB_OCC) {
@@ -1713,7 +1770,21 @@ void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
if(shi->combinedflag & SCE_PASS_SPEC)
VECADD(shr->combined, shr->combined, shr->spec);
+ /* modulate by the object color */
+ if((ma->shade_flag & MA_OBCOLOR) && shi->obr->ob) {
+ if(!(ma->sss_flag & MA_DIFF_SSS) || !sss_pass_done(&R, ma)) {
+ float obcol[4];
+
+ QUATCOPY(obcol, shi->obr->ob->col);
+ CLAMP(obcol[3], 0.0f, 1.0f);
+
+ shr->combined[0] *= obcol[0];
+ shr->combined[1] *= obcol[1];
+ shr->combined[2] *= obcol[2];
+ shr->alpha *= obcol[3];
+ }
+ }
+
shr->combined[3]= shr->alpha;
}
-
diff --git a/source/blender/render/intern/source/sss.c b/source/blender/render/intern/source/sss.c
index 09a3b9ef66d..9bde6675798 100644
--- a/source/blender/render/intern/source/sss.c
+++ b/source/blender/render/intern/source/sss.c
@@ -59,6 +59,7 @@
#include "BKE_main.h"
#include "BKE_material.h"
#include "BKE_node.h"
+#include "BKE_scene.h"
#include "BKE_utildefines.h"
/* this module */
@@ -450,13 +451,13 @@ static void compute_radiance(ScatterTree *tree, float *co, float *rad)
VECCOPY(rdsum, result.rdsum);
VECADD(backrdsum, result.rdsum, result.backrdsum);
- if(rdsum[0] > 0.0f) rad[0]= tree->ss[0]->color*rad[0]/rdsum[0];
- if(rdsum[1] > 0.0f) rad[1]= tree->ss[1]->color*rad[1]/rdsum[1];
- if(rdsum[2] > 0.0f) rad[2]= tree->ss[2]->color*rad[2]/rdsum[2];
+ if(rdsum[0] > 1e-16f) rad[0]= tree->ss[0]->color*rad[0]/rdsum[0];
+ if(rdsum[1] > 1e-16f) rad[1]= tree->ss[1]->color*rad[1]/rdsum[1];
+ if(rdsum[2] > 1e-16f) rad[2]= tree->ss[2]->color*rad[2]/rdsum[2];
- if(backrdsum[0] > 0.0f) backrad[0]= tree->ss[0]->color*backrad[0]/backrdsum[0];
- if(backrdsum[1] > 0.0f) backrad[1]= tree->ss[1]->color*backrad[1]/backrdsum[1];
- if(backrdsum[2] > 0.0f) backrad[2]= tree->ss[2]->color*backrad[2]/backrdsum[2];
+ if(backrdsum[0] > 1e-16f) backrad[0]= tree->ss[0]->color*backrad[0]/backrdsum[0];
+ if(backrdsum[1] > 1e-16f) backrad[1]= tree->ss[1]->color*backrad[1]/backrdsum[1];
+ if(backrdsum[2] > 1e-16f) backrad[2]= tree->ss[2]->color*backrad[2]/backrdsum[2];
rad[0]= MAX2(rad[0], backrad[0]);
rad[1]= MAX2(rad[1], backrad[1]);
@@ -503,20 +504,20 @@ static void sum_leaf_radiance(ScatterTree *tree, ScatterNode *node)
}
}
- if(node->area > 0) {
+ if(node->area > 1e-16f) {
inv= 1.0/node->area;
node->rad[0] *= inv;
node->rad[1] *= inv;
node->rad[2] *= inv;
}
- if(node->backarea > 0) {
+ if(node->backarea > 1e-16f) {
inv= 1.0/node->backarea;
node->backrad[0] *= inv;
node->backrad[1] *= inv;
node->backrad[2] *= inv;
}
- if(totrad > 0.0f) {
+ if(totrad > 1e-16f) {
inv= 1.0/totrad;
node->co[0] *= inv;
node->co[1] *= inv;
@@ -577,20 +578,20 @@ static void sum_branch_radiance(ScatterTree *tree, ScatterNode *node)
node->backarea += subnode->backarea;
}
- if(node->area > 0) {
+ if(node->area > 1e-16f) {
inv= 1.0/node->area;
node->rad[0] *= inv;
node->rad[1] *= inv;
node->rad[2] *= inv;
}
- if(node->backarea > 0) {
+ if(node->backarea > 1e-16f) {
inv= 1.0/node->backarea;
node->backrad[0] *= inv;
node->backrad[1] *= inv;
node->backrad[2] *= inv;
}
- if(totrad > 0.0f) {
+ if(totrad > 1e-16f) {
inv= 1.0/totrad;
node->co[0] *= inv;
node->co[1] *= inv;
@@ -847,7 +848,7 @@ static void sss_create_tree_mat(Render *re, Material *mat)
{
SSSPoints *p;
RenderResult *rr;
- ListBase layers, points;
+ ListBase points;
float (*co)[3] = NULL, (*color)[3] = NULL, *area = NULL;
int totpoint = 0, osa, osaflag, partsdone;
@@ -860,13 +861,11 @@ static void sss_create_tree_mat(Render *re, Material *mat)
setting them back, maybe we need to create our own Render? */
/* do SSS preprocessing render */
- layers= re->r.layers;
+ rr= re->result;
osa= re->osa;
osaflag= re->r.mode & R_OSA;
partsdone= re->i.partsdone;
- rr= re->result;
- re->r.layers.first= re->r.layers.last= NULL;
re->osa= 0;
re->r.mode &= ~R_OSA;
re->sss_points= &points;
@@ -881,7 +880,6 @@ static void sss_create_tree_mat(Render *re, Material *mat)
re->i.partsdone= partsdone;
re->sss_mat= NULL;
re->sss_points= NULL;
- re->r.layers= layers;
re->osa= osa;
if (osaflag) re->r.mode |= R_OSA;
@@ -921,7 +919,8 @@ static void sss_create_tree_mat(Render *re, Material *mat)
float *col= mat->sss_col, *radius= mat->sss_radius;
float fw= mat->sss_front, bw= mat->sss_back;
float error = mat->sss_error;
-
+
+ error= get_render_aosss_error(&re->r, error);
if((re->r.scemode & R_PREVIEWBUTS) && error < 0.5f)
error= 0.5f;
@@ -985,7 +984,7 @@ void make_sss_tree(Render *re)
re->stats_draw(&re->i);
for(mat= G.main->mat.first; mat; mat= mat->id.next)
- if(mat->id.us && (mat->sss_flag & MA_DIFF_SSS))
+ if(mat->id.us && (mat->flag & MA_IS_USED) && (mat->sss_flag & MA_DIFF_SSS))
sss_create_tree_mat(re, mat);
}
@@ -1024,8 +1023,8 @@ int sample_sss(Render *re, Material *mat, float *co, float *color)
return 0;
}
-int has_sss_tree(struct Render *re, struct Material *mat)
+int sss_pass_done(struct Render *re, struct Material *mat)
{
- return (re->sss_hash && BLI_ghash_lookup(re->sss_hash, mat));
+ return ((re->flag & R_BAKING) || !(re->r.mode & R_SSS) || (re->sss_hash && BLI_ghash_lookup(re->sss_hash, mat)));
}
diff --git a/source/blender/render/intern/source/strand.c b/source/blender/render/intern/source/strand.c
index 4f0e9764a43..05e36160f0e 100644
--- a/source/blender/render/intern/source/strand.c
+++ b/source/blender/render/intern/source/strand.c
@@ -35,12 +35,14 @@
#include "DNA_key_types.h"
#include "DNA_material_types.h"
+#include "DNA_meshdata_types.h"
#include "BLI_arithb.h"
#include "BLI_blenlib.h"
#include "BLI_ghash.h"
#include "BLI_memarena.h"
+#include "BKE_DerivedMesh.h"
#include "BKE_key.h"
#include "BKE_utildefines.h"
@@ -55,248 +57,9 @@
#include "zbuf.h"
/* to be removed */
-void merge_transp_passes(RenderLayer *rl, ShadeResult *shr);
-void add_transp_passes(RenderLayer *rl, int offset, ShadeResult *shr, float alpha);
void hoco_to_zco(ZSpan *zspan, float *zco, float *hoco);
void zspan_scanconvert_strand(ZSpan *zspan, void *handle, float *v1, float *v2, float *v3, void (*func)(void *, int, int, float, float, float) );
-void zbufsinglewire(ZSpan *zspan, ObjectRen *obr, int zvlnr, float *ho1, float *ho2);
-int addtosamp_shr(ShadeResult *samp_shr, ShadeSample *ssamp, int addpassflag);
-void add_transp_speed(RenderLayer *rl, int offset, float *speed, float alpha, long *rdrect);
-void reset_sky_speedvectors(RenderPart *pa, RenderLayer *rl, float *rectf);
-
-/* *************** */
-
-#define BUCKETPRIMS_SIZE 256
-
-typedef struct BucketPrims {
- struct BucketPrims *next, *prev;
- void *prim[BUCKETPRIMS_SIZE];
- int totprim;
-} BucketPrims;
-
-typedef struct RenderBuckets {
- ListBase all;
- ListBase *inside;
- ListBase *overlap;
- int x, y;
- float insize[2];
- float zmulx, zmuly, zofsx, zofsy;
-} RenderBuckets;
-
-static void add_bucket_prim(ListBase *lb, void *prim)
-{
- BucketPrims *bpr= lb->last;
-
- if(!bpr || bpr->totprim == BUCKETPRIMS_SIZE) {
- bpr= MEM_callocN(sizeof(BucketPrims), "BucketPrims");
- BLI_addtail(lb, bpr);
- }
-
- bpr->prim[bpr->totprim++]= prim;
-}
-
-RenderBuckets *init_buckets(Render *re)
-{
- RenderBuckets *buckets;
- RenderPart *pa;
- float scalex, scaley, cropx, cropy;
- int x, y, tempparts= 0;
-
- buckets= MEM_callocN(sizeof(RenderBuckets), "RenderBuckets");
-
- if(!re->parts.first) {
- initparts(re);
- tempparts= 1;
- }
-
- pa= re->parts.first;
- if(!pa)
- return buckets;
-
- x= re->xparts+1;
- y= re->yparts+1;
- buckets->x= x;
- buckets->y= y;
-
- scalex= (2.0f - re->xparts*re->partx/(float)re->winx);
- scaley= (2.0f - re->yparts*re->party/(float)re->winy);
-
- cropx= pa->crop/(float)re->partx;
- cropy= pa->crop/(float)re->party;
-
- buckets->insize[0]= 1.0f - 2.0f*cropx;
- buckets->insize[1]= 1.0f - 2.0f*cropy;
-
- buckets->zmulx= re->xparts*scalex;
- buckets->zmuly= re->yparts*scaley;
- buckets->zofsx= scalex*(1.0f - cropx);
- buckets->zofsy= scaley*(1.0f - cropy);
-
- buckets->inside= MEM_callocN(sizeof(ListBase)*x*y, "BucketPrimsInside");
- buckets->overlap= MEM_callocN(sizeof(ListBase)*x*y, "BucketPrimsOverlap");
-
- if(tempparts)
- freeparts(re);
-
- return buckets;
-}
-
-void add_buckets_primitive(RenderBuckets *buckets, float *min, float *max, void *prim)
-{
- float end[3];
- int x, y, a;
-
- x= (int)min[0];
- y= (int)min[1];
-
- if(x >= 0 && x < buckets->x && y >= 0 && y < buckets->y) {
- a= y*buckets->x + x;
-
- end[0]= x + buckets->insize[0];
- end[1]= y + buckets->insize[1];
-
- if(max[0] <= end[0] && max[1] <= end[1]) {
- add_bucket_prim(&buckets->inside[a], prim);
- return;
- }
- else {
- end[0]= x + 2;
- end[1]= y + 2;
-
- if(max[0] <= end[0] && max[1] <= end[1]) {
- add_bucket_prim(&buckets->overlap[a], prim);
- return;
- }
- }
- }
-
- add_bucket_prim(&buckets->all, prim);
-}
-
-void free_buckets(RenderBuckets *buckets)
-{
- int a, size;
-
- BLI_freelistN(&buckets->all);
-
- size= buckets->x*buckets->y;
- for(a=0; a<size; a++) {
- BLI_freelistN(&buckets->inside[a]);
- BLI_freelistN(&buckets->overlap[a]);
- }
-
- if(buckets->inside)
- MEM_freeN(buckets->inside);
- if(buckets->overlap)
- MEM_freeN(buckets->overlap);
-
- MEM_freeN(buckets);
-}
-
-void project_hoco_to_bucket(RenderBuckets *buckets, float *hoco, float *bucketco)
-{
- float div;
-
- div= 1.0f/hoco[3];
- bucketco[0]= buckets->zmulx*(0.5 + 0.5f*hoco[0]*div) + buckets->zofsx;
- bucketco[1]= buckets->zmuly*(0.5 + 0.5f*hoco[1]*div) + buckets->zofsy;
-}
-
-typedef struct RenderPrimitiveIterator {
- Render *re;
- RenderBuckets *buckets;
- ListBase *list[6];
- int listindex, totlist;
- BucketPrims *bpr;
- int bprindex;
-
- ObjectInstanceRen *obi;
- StrandRen *strand;
- int index, tot;
-} RenderPrimitiveIterator;
-
-RenderPrimitiveIterator *init_primitive_iterator(Render *re, RenderBuckets *buckets, RenderPart *pa)
-{
- RenderPrimitiveIterator *iter;
- int nr, x, y, width;
-
- iter= MEM_callocN(sizeof(RenderPrimitiveIterator), "RenderPrimitiveIterator");
- iter->re= re;
-
- if(buckets) {
- iter->buckets= buckets;
-
- nr= BLI_findindex(&re->parts, pa);
- width= buckets->x - 1;
- x= (nr % width) + 1;
- y= (nr / width) + 1;
-
- iter->list[iter->totlist++]= &buckets->all;
- iter->list[iter->totlist++]= &buckets->inside[y*buckets->x + x];
- iter->list[iter->totlist++]= &buckets->overlap[y*buckets->x + x];
- iter->list[iter->totlist++]= &buckets->overlap[y*buckets->x + (x-1)];
- iter->list[iter->totlist++]= &buckets->overlap[(y-1)*buckets->x + (x-1)];
- iter->list[iter->totlist++]= &buckets->overlap[(y-1)*buckets->x + x];
- }
- else {
- iter->index= 0;
- iter->obi= re->instancetable.first;
- if(iter->obi)
- iter->tot= iter->obi->obr->totstrand;
- }
-
- return iter;
-}
-
-void *next_primitive_iterator(RenderPrimitiveIterator *iter)
-{
- if(iter->buckets) {
- if(iter->bpr && iter->bprindex >= iter->bpr->totprim) {
- iter->bpr= iter->bpr->next;
- iter->bprindex= 0;
- }
-
- while(iter->bpr == NULL) {
- if(iter->listindex == iter->totlist)
- return NULL;
-
- iter->bpr= iter->list[iter->listindex++]->first;
- iter->bprindex= 0;
- }
-
- return iter->bpr->prim[iter->bprindex++];
- }
- else {
- if(!iter->obi)
- return NULL;
-
- if(iter->index >= iter->tot) {
- while((iter->obi=iter->obi->next) && !iter->obi->obr->totstrand)
- iter->obi= iter->obi->next;
-
- if(iter->obi)
- iter->tot= iter->obi->obr->totstrand;
- else
- return NULL;
- }
-
- if(iter->index < iter->tot) {
- if((iter->index & 255)==0)
- iter->strand= iter->obi->obr->strandnodes[iter->index>>8].strand;
- else
- iter->strand++;
-
- return iter->strand;
- }
- else
- return NULL;
- }
-}
-
-void free_primitive_iterator(RenderPrimitiveIterator *iter)
-{
- MEM_freeN(iter);
-}
+void zbufsinglewire(ZSpan *zspan, int obi, int zvlnr, float *ho1, float *ho2);
/* *************** */
@@ -388,9 +151,9 @@ void strand_eval_point(StrandSegment *sseg, StrandPoint *spoint)
Crossf(cross, spoint->co, spoint->tan);
w= spoint->co[2]*strandbuf->winmat[2][3] + strandbuf->winmat[3][3];
- dx= strandbuf->winx*cross[0]*strandbuf->winmat[0][0];
- dy= strandbuf->winy*cross[1]*strandbuf->winmat[1][1];
- w= sqrt(dx*dx + dy*dy)/w;
+ dx= strandbuf->winx*cross[0]*strandbuf->winmat[0][0]/w;
+ dy= strandbuf->winy*cross[1]*strandbuf->winmat[1][1]/w;
+ w= sqrt(dx*dx + dy*dy);
if(w > 0.0f) {
if(strandbuf->flag & R_STRAND_B_UNITS) {
@@ -420,42 +183,9 @@ void strand_eval_point(StrandSegment *sseg, StrandPoint *spoint)
/* *************** */
-typedef struct StrandPart {
- Render *re;
- ZSpan *zspan;
-
- RenderLayer *rl;
- ShadeResult *result;
- float *pass;
- int *rectz, *outrectz;
- unsigned short *mask;
- int rectx, recty;
- int addpassflag, addzbuf, sample;
-
- StrandSegment *segment;
- GHash *hash;
- StrandPoint point1, point2;
- ShadeSample ssamp1, ssamp2, ssamp;
- float t[3];
-} StrandPart;
-
-typedef struct StrandSortSegment {
- struct StrandSortSegment *next;
- int obi, strand, segment;
- float z;
-} StrandSortSegment;
-
-static int compare_strand_segment(const void *poin1, const void *poin2)
+static void interpolate_vec1(float *v1, float *v2, float t, float negt, float *v)
{
- const StrandSortSegment *seg1= (const StrandSortSegment*)poin1;
- const StrandSortSegment *seg2= (const StrandSortSegment*)poin2;
-
- if(seg1->z < seg2->z)
- return -1;
- else if(seg1->z == seg2->z)
- return 0;
- else
- return 1;
+ v[0]= negt*v1[0] + t*v2[0];
}
static void interpolate_vec3(float *v1, float *v2, float t, float negt, float *v)
@@ -473,7 +203,7 @@ static void interpolate_vec4(float *v1, float *v2, float t, float negt, float *v
v[3]= negt*v1[3] + t*v2[3];
}
-static void interpolate_shade_result(ShadeResult *shr1, ShadeResult *shr2, float t, ShadeResult *shr, int addpassflag)
+void interpolate_shade_result(ShadeResult *shr1, ShadeResult *shr2, float t, ShadeResult *shr, int addpassflag)
{
float negt= 1.0f - t;
@@ -484,6 +214,8 @@ static void interpolate_shade_result(ShadeResult *shr1, ShadeResult *shr2, float
}
/* optim... */
if(addpassflag & ~(SCE_PASS_VECTOR)) {
+ if(addpassflag & SCE_PASS_Z)
+ interpolate_vec1(&shr1->z, &shr2->z, t, negt, &shr->z);
if(addpassflag & SCE_PASS_RGBA)
interpolate_vec4(shr1->col, shr2->col, t, negt, shr->col);
if(addpassflag & SCE_PASS_NORMAL) {
@@ -504,142 +236,336 @@ static void interpolate_shade_result(ShadeResult *shr1, ShadeResult *shr2, float
interpolate_vec3(shr1->refr, shr2->refr, t, negt, shr->refr);
if(addpassflag & SCE_PASS_RADIO)
interpolate_vec3(shr1->rad, shr2->rad, t, negt, shr->rad);
+ if(addpassflag & SCE_PASS_MIST)
+ interpolate_vec1(&shr1->mist, &shr2->mist, t, negt, &shr->mist);
}
}
-static void add_strand_obindex(RenderLayer *rl, int offset, ObjectRen *obr)
+void strand_apply_shaderesult_alpha(ShadeResult *shr, float alpha)
{
- RenderPass *rpass;
-
- for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
- if(rpass->passtype == SCE_PASS_INDEXOB) {
- float *fp= rpass->rect + offset;
- *fp= (float)obr->ob->index;
- break;
- }
+ if(alpha < 1.0f) {
+ shr->combined[0] *= alpha;
+ shr->combined[1] *= alpha;
+ shr->combined[2] *= alpha;
+ shr->combined[3] *= alpha;
+
+ shr->col[0] *= alpha;
+ shr->col[1] *= alpha;
+ shr->col[2] *= alpha;
+ shr->col[3] *= alpha;
+
+ shr->alpha *= alpha;
}
}
-static void do_strand_point_project(float winmat[][4], ZSpan *zspan, float *co, float *hoco, float *zco)
+void strand_shade_point(Render *re, ShadeSample *ssamp, StrandSegment *sseg, StrandPoint *spoint)
{
- projectvert(co, winmat, hoco);
- hoco_to_zco(zspan, zco, hoco);
+ ShadeInput *shi= ssamp->shi;
+ ShadeResult *shr= ssamp->shr;
+ VlakRen vlr;
+
+ memset(&vlr, 0, sizeof(vlr));
+ vlr.flag= R_SMOOTH;
+ if(sseg->buffer->ma->mode & MA_TANGENT_STR)
+ vlr.flag |= R_TANGENT;
+
+ shi->vlr= &vlr;
+ shi->strand= sseg->strand;
+ shi->obi= sseg->obi;
+ shi->obr= sseg->obi->obr;
+
+ /* cache for shadow */
+ shi->samplenr= re->shadowsamplenr[shi->thread]++;
+
+ shade_input_set_strand(shi, sseg->strand, spoint);
+ shade_input_set_strand_texco(shi, sseg->strand, sseg->v[1], spoint);
+
+ /* init material vars */
+ // note, keep this synced with render_types.h
+ memcpy(&shi->r, &shi->mat->r, 23*sizeof(float));
+ shi->har= shi->mat->har;
+
+ /* shade */
+ shade_samples_do_AO(ssamp);
+ shade_input_do_shade(shi, shr);
+
+ /* apply simplification */
+ strand_apply_shaderesult_alpha(shr, spoint->alpha);
+
+ /* include lamphalos for strand, since halo layer was added already */
+ if(re->flag & R_LAMPHALO)
+ if(shi->layflag & SCE_LAY_HALO)
+ renderspothalo(shi, shr->combined, shr->combined[3]);
+
+ shi->strand= NULL;
}
-static void strand_project_point(float winmat[][4], float winx, float winy, StrandPoint *spoint)
-{
- float div;
+/* *************** */
- projectvert(spoint->co, winmat, spoint->hoco);
+struct StrandShadeCache {
+ GHash *resulthash;
+ GHash *refcounthash;
+ MemArena *memarena;
+};
- div= 1.0f/spoint->hoco[3];
- spoint->x= spoint->hoco[0]*div*winx*0.5f;
- spoint->y= spoint->hoco[1]*div*winy*0.5f;
+StrandShadeCache *strand_shade_cache_create()
+{
+ StrandShadeCache *cache;
+
+ cache= MEM_callocN(sizeof(StrandShadeCache), "StrandShadeCache");
+ cache->resulthash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
+ cache->refcounthash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
+ cache->memarena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
+
+ return cache;
}
-#include "BLI_rand.h"
-static void strand_shade_point(Render *re, ShadeSample *ssamp, StrandSegment *sseg, StrandPoint *spoint);
+void strand_shade_cache_free(StrandShadeCache *cache)
+{
+ BLI_ghash_free(cache->refcounthash, NULL, NULL);
+ BLI_ghash_free(cache->resulthash, NULL, (GHashValFreeFP)MEM_freeN);
+ BLI_memarena_free(cache->memarena);
+ MEM_freeN(cache);
+}
-static void strand_shade_get(StrandPart *spart, int lookup, ShadeSample *ssamp, StrandPoint *spoint, StrandVert *svert, StrandSegment *sseg)
+static void strand_shade_get(Render *re, StrandShadeCache *cache, ShadeSample *ssamp, StrandSegment *sseg, StrandVert *svert)
{
ShadeResult *hashshr;
+ StrandPoint p;
+ int *refcount;
- if(lookup) {
- hashshr= BLI_ghash_lookup(spart->hash, svert);
+ hashshr= BLI_ghash_lookup(cache->resulthash, svert);
+ refcount= BLI_ghash_lookup(cache->refcounthash, svert);
- if(!hashshr) {
- strand_shade_point(spart->re, ssamp, sseg, spoint);
+ if(!hashshr) {
+ /* not shaded yet, shade and insert into hash */
+ p.t= (sseg->v[1] == svert)? 0.0f: 1.0f;
+ strand_eval_point(sseg, &p);
+ strand_shade_point(re, ssamp, sseg, &p);
- hashshr= MEM_callocN(sizeof(ShadeResult), "HashShadeResult");
- *hashshr= ssamp->shr[0];
- BLI_ghash_insert(spart->hash, svert, hashshr);
- }
- else {
- ssamp->shr[0]= *hashshr;
- BLI_ghash_remove(spart->hash, svert, NULL, (GHashValFreeFP)MEM_freeN);
- }
+ hashshr= MEM_callocN(sizeof(ShadeResult), "HashShadeResult");
+ *hashshr= ssamp->shr[0];
+ BLI_ghash_insert(cache->resulthash, svert, hashshr);
}
else
- strand_shade_point(spart->re, ssamp, sseg, spoint);
+ /* already shaded, just copy previous result from hash */
+ ssamp->shr[0]= *hashshr;
+
+ /* lower reference count and remove if not needed anymore by any samples */
+ (*refcount)--;
+ if(*refcount == 0) {
+ BLI_ghash_remove(cache->resulthash, svert, NULL, (GHashValFreeFP)MEM_freeN);
+ BLI_ghash_remove(cache->refcounthash, svert, NULL, NULL);
+ }
}
-static void strand_shade_segment(StrandPart *spart)
+void strand_shade_segment(Render *re, StrandShadeCache *cache, StrandSegment *sseg, ShadeSample *ssamp, float t, float s, int addpassflag)
{
- StrandSegment *sseg= spart->segment;
- int first, last;
+ ShadeResult shr1, shr2;
- if(!sseg->shaded) {
- first= (sseg->v[1] == &sseg->strand->vert[0]);
- last= (sseg->v[2] == &sseg->strand->vert[sseg->strand->totvert-1]);
+ /* get shading for two endpoints and interpolate */
+ strand_shade_get(re, cache, ssamp, sseg, sseg->v[1]);
+ shr1= ssamp->shr[0];
+ strand_shade_get(re, cache, ssamp, sseg, sseg->v[2]);
+ shr2= ssamp->shr[0];
- strand_shade_get(spart, !first, &spart->ssamp1, &sseg->point1, sseg->v[1], sseg);
- strand_shade_get(spart, !last, &spart->ssamp2, &sseg->point2, sseg->v[2], sseg);
- sseg->shaded= 1;
+ interpolate_shade_result(&shr1, &shr2, t, ssamp->shr, addpassflag);
+
+ /* apply alpha along width */
+ if(sseg->buffer->widthfade != 0.0f) {
+ s = 1.0f - pow(fabs(s), sseg->buffer->widthfade);
+
+ strand_apply_shaderesult_alpha(ssamp->shr, s);
}
+}
-#if 0
- float c[3];
-
- c[0]= BLI_frand();
- c[1]= BLI_frand();
- c[2]= BLI_frand();
+void strand_shade_unref(StrandShadeCache *cache, StrandVert *svert)
+{
+ int *refcount;
- spart->ssamp1.shr[0].combined[0] *= c[0];
- spart->ssamp1.shr[0].combined[1] *= c[1];
- spart->ssamp1.shr[0].combined[2] *= c[2];
+ /* lower reference count and remove if not needed anymore by any samples */
+ refcount= BLI_ghash_lookup(cache->refcounthash, svert);
- spart->ssamp2.shr[0].combined[0] *= c[0];
- spart->ssamp2.shr[0].combined[1] *= c[1];
- spart->ssamp2.shr[0].combined[2] *= c[2];
-#endif
+ (*refcount)--;
+ if(*refcount == 0) {
+ BLI_ghash_remove(cache->resulthash, svert, NULL, (GHashValFreeFP)MEM_freeN);
+ BLI_ghash_remove(cache->refcounthash, svert, NULL, NULL);
+ }
}
-static void do_strand_blend(void *handle, int x, int y, float u, float v, float z)
+static void strand_shade_refcount(StrandShadeCache *cache, StrandVert *svert)
{
- StrandPart *spart= (StrandPart*)handle;
- StrandBuffer *buffer= spart->segment->buffer;
- ShadeResult *shr;
- float /**pass,*/ t;
- int offset, zverg;
+ int *refcount= BLI_ghash_lookup(cache->refcounthash, svert);
- /* check again solid z-buffer */
- offset = y*spart->rectx + x;
- zverg= (int)z;
+ if(!refcount) {
+ refcount= BLI_memarena_alloc(cache->memarena, sizeof(int));
+ *refcount= 1;
+ BLI_ghash_insert(cache->refcounthash, svert, refcount);
+ }
+ else
+ (*refcount)++;
+}
- if(zverg < spart->rectz[offset]) {
- /* fill in output z-buffer if needed */
- if(spart->addzbuf)
- if(zverg < spart->outrectz[offset])
- spart->outrectz[offset]= zverg;
+/* *************** */
- /* check alpha limit */
- shr= spart->result + offset*(spart->re->osa? spart->re->osa: 1);
- if(shr[spart->sample].combined[3]>0.999f)
- return;
+typedef struct StrandPart {
+ Render *re;
+ ZSpan *zspan;
- /* shade points if not shaded yet */
- strand_shade_segment(spart);
+ APixstrand *apixbuf;
+ int *totapixbuf;
+ int *rectz;
+ int *rectmask;
+ intptr_t *rectdaps;
+ int rectx, recty;
+ int sample;
- /* interpolate shading from two control points */
- t = u*spart->t[0] + v*spart->t[1] + (1.0f-u-v)*spart->t[2];
- interpolate_shade_result(spart->ssamp1.shr, spart->ssamp2.shr, t,
- spart->ssamp.shr, spart->addpassflag);
+ StrandSegment *segment;
+ float t[3], s[3];
- /* add in shaderesult array for part */
- spart->ssamp.shi[0].mask= (1<<spart->sample);
- addtosamp_shr(shr, &spart->ssamp, spart->addpassflag);
- spart->mask[offset] |= (1<<spart->sample);
+ StrandShadeCache *cache;
+} StrandPart;
-#if 0
- /* fill in pass for preview */
- if(spart->sample == 0) {
- pass= spart->pass + offset*4;
- QUATCOPY(pass, shr->combined);
+typedef struct StrandSortSegment {
+ struct StrandSortSegment *next;
+ int obi, strand, segment;
+ float z;
+} StrandSortSegment;
+
+static int compare_strand_segment(const void *poin1, const void *poin2)
+{
+ const StrandSortSegment *seg1= (const StrandSortSegment*)poin1;
+ const StrandSortSegment *seg2= (const StrandSortSegment*)poin2;
+
+ if(seg1->z < seg2->z)
+ return -1;
+ else if(seg1->z == seg2->z)
+ return 0;
+ else
+ return 1;
+}
+
+static void do_strand_point_project(float winmat[][4], ZSpan *zspan, float *co, float *hoco, float *zco)
+{
+ projectvert(co, winmat, hoco);
+ hoco_to_zco(zspan, zco, hoco);
+}
+
+static void strand_project_point(float winmat[][4], float winx, float winy, StrandPoint *spoint)
+{
+ float div;
+
+ projectvert(spoint->co, winmat, spoint->hoco);
+
+ div= 1.0f/spoint->hoco[3];
+ spoint->x= spoint->hoco[0]*div*winx*0.5f;
+ spoint->y= spoint->hoco[1]*div*winy*0.5f;
+}
+
+static APixstrand *addpsmainAstrand(ListBase *lb)
+{
+ APixstrMain *psm;
+
+ psm= MEM_mallocN(sizeof(APixstrMain), "addpsmainA");
+ BLI_addtail(lb, psm);
+ psm->ps= MEM_callocN(4096*sizeof(APixstrand),"pixstr");
+
+ return psm->ps;
+}
+
+static APixstrand *addpsAstrand(ZSpan *zspan)
+{
+ /* make new PS */
+ if(zspan->apstrandmcounter==0) {
+ zspan->curpstrand= addpsmainAstrand(zspan->apsmbase);
+ zspan->apstrandmcounter= 4095;
+ }
+ else {
+ zspan->curpstrand++;
+ zspan->apstrandmcounter--;
+ }
+ return zspan->curpstrand;
+}
+
+#define MAX_ZROW 2000
+
+static void do_strand_fillac(void *handle, int x, int y, float u, float v, float z)
+{
+ StrandPart *spart= (StrandPart*)handle;
+ StrandShadeCache *cache= spart->cache;
+ StrandSegment *sseg= spart->segment;
+ APixstrand *apn, *apnew;
+ float t, s;
+ int offset, mask, obi, strnr, seg, zverg, bufferz, maskz=0;
+
+ offset = y*spart->rectx + x;
+ obi= sseg->obi - spart->re->objectinstance;
+ strnr= sseg->strand->index + 1;
+ seg= sseg->v[1] - sseg->strand->vert;
+ mask= (1<<spart->sample);
+
+ /* check against solid z-buffer */
+ zverg= (int)z;
+
+ if(spart->rectdaps) {
+ /* find the z of the sample */
+ PixStr *ps;
+ intptr_t *rd= spart->rectdaps + offset;
+
+ bufferz= 0x7FFFFFFF;
+ if(spart->rectmask) maskz= 0x7FFFFFFF;
+
+ if(*rd) {
+ for(ps= (PixStr *)(*rd); ps; ps= ps->next) {
+ if(mask & ps->mask) {
+ bufferz= ps->z;
+ if(spart->rectmask)
+ maskz= ps->maskz;
+ break;
+ }
+ }
}
-#endif
+ }
+ else {
+ bufferz= spart->rectz[offset];
+ if(spart->rectmask)
+ maskz= spart->rectmask[offset];
+ }
+
+#define CHECK_ADD(n) \
+ if(apn->p[n]==strnr && apn->obi[n]==obi && apn->seg[n]==seg) \
+ { if(!(apn->mask[n] & mask)) { apn->mask[n] |= mask; apn->v[n] += t; apn->u[n] += s; } break; }
+#define CHECK_ASSIGN(n) \
+ if(apn->p[n]==0) \
+ {apn->obi[n]= obi; apn->p[n]= strnr; apn->z[n]= zverg; apn->mask[n]= mask; apn->v[n]= t; apn->u[n]= s; apn->seg[n]= seg; break; }
+
+ /* add to pixel list */
+ if(zverg < bufferz && (spart->totapixbuf[offset] < MAX_ZROW)) {
+ if(!spart->rectmask || zverg > maskz) {
+ t = u*spart->t[0] + v*spart->t[1] + (1.0f-u-v)*spart->t[2];
+ s = fabs(u*spart->s[0] + v*spart->s[1] + (1.0f-u-v)*spart->s[2]);
+
+ apn= spart->apixbuf + offset;
+ while(apn) {
+ CHECK_ADD(0);
+ CHECK_ADD(1);
+ CHECK_ADD(2);
+ CHECK_ADD(3);
+ CHECK_ASSIGN(0);
+ CHECK_ASSIGN(1);
+ CHECK_ASSIGN(2);
+ CHECK_ASSIGN(3);
+
+ apnew= addpsAstrand(spart->zspan);
+ SWAP(APixstrand, *apnew, *apn);
+ apn->next= apnew;
+ CHECK_ASSIGN(0);
+ }
- if(spart->addpassflag & SCE_PASS_INDEXOB)
- add_strand_obindex(spart->rl, offset, buffer->obr);
+ strand_shade_refcount(cache, sseg->v[1]);
+ strand_shade_refcount(cache, sseg->v[2]);
+ spart->totapixbuf[offset]++;
+ }
}
}
@@ -663,59 +589,6 @@ static int strand_test_clip(float winmat[][4], ZSpan *zspan, float *bounds, floa
return clipflag;
}
-static void strand_shade_point(Render *re, ShadeSample *ssamp, StrandSegment *sseg, StrandPoint *spoint)
-{
- ShadeInput *shi= ssamp->shi;
- ShadeResult *shr= ssamp->shr;
- VlakRen vlr;
-
- memset(&vlr, 0, sizeof(vlr));
- vlr.flag= R_SMOOTH;
- vlr.lay= sseg->strand->buffer->lay;
- vlr.obr= sseg->strand->buffer->obr;
- if(sseg->buffer->ma->mode & MA_TANGENT_STR)
- vlr.flag |= R_TANGENT;
-
- shi->vlr= &vlr;
- shi->obi= sseg->obi;
- shi->obr= sseg->obi->obr;
-
- /* cache for shadow */
- shi->samplenr++;
-
- shade_input_set_strand(shi, sseg->strand, spoint);
- shade_input_set_strand_texco(shi, sseg->strand, sseg->v[1], spoint);
-
- /* init material vars */
- // note, keep this synced with render_types.h
- memcpy(&shi->r, &shi->mat->r, 23*sizeof(float));
- shi->har= shi->mat->har;
-
- /* shade */
- shade_samples_do_AO(ssamp);
- shade_input_do_shade(shi, shr);
-
- /* apply simplification */
- if(spoint->alpha < 1.0f) {
- shr->combined[0] *= spoint->alpha;
- shr->combined[1] *= spoint->alpha;
- shr->combined[2] *= spoint->alpha;
- shr->combined[3] *= spoint->alpha;
-
- shr->col[0] *= spoint->alpha;
- shr->col[1] *= spoint->alpha;
- shr->col[2] *= spoint->alpha;
- shr->col[3] *= spoint->alpha;
-
- shr->alpha *= spoint->alpha;
- }
-
- /* include lamphalos for strand, since halo layer was added already */
- if(re->flag & R_LAMPHALO)
- if(shi->layflag & SCE_LAY_HALO)
- renderspothalo(shi, shr->combined, shr->combined[3]);
-}
-
static void do_scanconvert_strand(Render *re, StrandPart *spart, ZSpan *zspan, float t, float dt, float *co1, float *co2, float *co3, float *co4, int sample)
{
float jco1[3], jco2[3], jco3[3], jco4[3], jx, jy;
@@ -747,16 +620,22 @@ static void do_scanconvert_strand(Render *re, StrandPart *spart, ZSpan *zspan, f
spart->sample= sample;
spart->t[0]= t-dt;
+ spart->s[0]= -1.0f;
spart->t[1]= t-dt;
+ spart->s[1]= 1.0f;
spart->t[2]= t;
- zspan_scanconvert_strand(zspan, spart, jco1, jco2, jco3, do_strand_blend);
+ spart->s[2]= 1.0f;
+ zspan_scanconvert_strand(zspan, spart, jco1, jco2, jco3, do_strand_fillac);
spart->t[0]= t-dt;
+ spart->s[0]= -1.0f;
spart->t[1]= t;
+ spart->s[1]= 1.0f;
spart->t[2]= t;
- zspan_scanconvert_strand(zspan, spart, jco1, jco3, jco4, do_strand_blend);
+ spart->s[2]= -1.0f;
+ zspan_scanconvert_strand(zspan, spart, jco1, jco3, jco4, do_strand_fillac);
}
-static void strand_render(Render *re, float winmat[][4], StrandPart *spart, ZSpan *zspan, StrandPoint *p1, StrandPoint *p2)
+static void strand_render(Render *re, StrandSegment *sseg, float winmat[][4], StrandPart *spart, ZSpan *zspan, int totzspan, StrandPoint *p1, StrandPoint *p2)
{
if(spart) {
float t= p2->t;
@@ -771,18 +650,28 @@ static void strand_render(Render *re, float winmat[][4], StrandPart *spart, ZSpa
do_scanconvert_strand(re, spart, zspan, t, dt, p1->zco2, p1->zco1, p2->zco1, p2->zco2, 0);
}
else {
- float hoco1[4], hoco2[3];
-
- projectvert(p1->co, winmat, hoco1);
- projectvert(p2->co, winmat, hoco2);
-
- /* render both strand and single pixel wire to counter aliasing */
- zbufclip4(zspan, 0, 0, p1->hoco2, p1->hoco1, p2->hoco1, p2->hoco2, 0, 0, 0, 0);
- zbufsinglewire(zspan, 0, 0, hoco1, hoco2);
+ float hoco1[4], hoco2[4];
+ int a, obi, index;
+
+ obi= sseg->obi - re->objectinstance;
+ index= sseg->strand->index;
+
+ projectvert(p1->co, winmat, hoco1);
+ projectvert(p2->co, winmat, hoco2);
+
+ for(a=0; a<totzspan; a++) {
+#if 0
+ /* render both strand and single pixel wire to counter aliasing */
+ zbufclip4(re, &zspan[a], obi, index, p1->hoco2, p1->hoco1, p2->hoco1, p2->hoco2, p1->clip2, p1->clip1, p2->clip1, p2->clip2);
+#endif
+ /* only render a line for now, which makes the shadow map more
+ similiar across frames, and so reduces flicker */
+ zbufsinglewire(&zspan[a], obi, index, hoco1, hoco2);
+ }
}
}
-
-static int strand_segment_recursive(Render *re, float winmat[][4], StrandPart *spart, ZSpan *zspan, StrandSegment *sseg, StrandPoint *p1, StrandPoint *p2, int depth)
+
+static int strand_segment_recursive(Render *re, float winmat[][4], StrandPart *spart, ZSpan *zspan, int totzspan, StrandSegment *sseg, StrandPoint *p1, StrandPoint *p2, int depth)
{
StrandPoint p;
StrandBuffer *buffer= sseg->buffer;
@@ -815,19 +704,23 @@ static int strand_segment_recursive(Render *re, float winmat[][4], StrandPart *s
do_strand_point_project(winmat, zspan, p.co2, p.hoco2, p.zco2);
}
else {
+#if 0
projectvert(p.co1, winmat, p.hoco1);
projectvert(p.co2, winmat, p.hoco2);
+ p.clip1= testclip(p.hoco1);
+ p.clip2= testclip(p.hoco2);
+#endif
}
- if(!strand_segment_recursive(re, winmat, spart, zspan, sseg, p1, &p, depth+1))
- strand_render(re, winmat, spart, zspan, p1, &p);
- if(!strand_segment_recursive(re, winmat, spart, zspan, sseg, &p, p2, depth+1))
- strand_render(re, winmat, spart, zspan, &p, p2);
+ if(!strand_segment_recursive(re, winmat, spart, zspan, totzspan, sseg, p1, &p, depth+1))
+ strand_render(re, sseg, winmat, spart, zspan, totzspan, p1, &p);
+ if(!strand_segment_recursive(re, winmat, spart, zspan, totzspan, sseg, &p, p2, depth+1))
+ strand_render(re, sseg, winmat, spart, zspan, totzspan, &p, p2);
return 1;
}
-void render_strand_segment(Render *re, float winmat[][4], StrandPart *spart, ZSpan *zspan, StrandSegment *sseg)
+void render_strand_segment(Render *re, float winmat[][4], StrandPart *spart, ZSpan *zspan, int totzspan, StrandSegment *sseg)
{
StrandBuffer *buffer= sseg->buffer;
StrandPoint *p1= &sseg->point1;
@@ -848,149 +741,55 @@ void render_strand_segment(Render *re, float winmat[][4], StrandPart *spart, ZSp
do_strand_point_project(winmat, zspan, p2->co2, p2->hoco2, p2->zco2);
}
else {
+#if 0
projectvert(p1->co1, winmat, p1->hoco1);
projectvert(p1->co2, winmat, p1->hoco2);
projectvert(p2->co1, winmat, p2->hoco1);
projectvert(p2->co2, winmat, p2->hoco2);
+ p1->clip1= testclip(p1->hoco1);
+ p1->clip2= testclip(p1->hoco2);
+ p2->clip1= testclip(p2->hoco1);
+ p2->clip2= testclip(p2->hoco2);
+#endif
}
- if(!strand_segment_recursive(re, winmat, spart, zspan, sseg, p1, p2, 0))
- strand_render(re, winmat, spart, zspan, p1, p2);
-}
-
-static void zbuffer_strands_filter(Render *re, RenderPart *pa, RenderLayer *rl, StrandPart *spart, float *pass)
-{
- RenderResult *rr= pa->result;
- ShadeResult *shr, *shrrect= spart->result;
- float *passrect= pass;
- long *rdrect;
- int osa, x, y, a, crop= 0, offs=0, od;
-
- osa= (re->osa? re->osa: 1);
-
- /* filtered render, for now we assume only 1 filter size */
- if(pa->crop) {
- crop= 1;
- offs= pa->rectx + 1;
- passrect+= 4*offs;
- shrrect+= offs*osa;
- }
-
- rdrect= pa->rectdaps;
-
- /* zero alpha pixels get speed vector max again */
- if(spart->addpassflag & SCE_PASS_VECTOR)
- if(rl->layflag & SCE_LAY_SOLID)
- reset_sky_speedvectors(pa, rl, rl->scolrect);
-
- /* init scanline updates */
- rr->renrect.ymin= 0;
- rr->renrect.ymax= -pa->crop;
- rr->renlay= rl;
-
- /* filter the shade results */
- for(y=pa->disprect.ymin+crop; y<pa->disprect.ymax-crop; y++, rr->renrect.ymax++) {
- pass= passrect;
- shr= shrrect;
- od= offs;
-
- for(x=pa->disprect.xmin+crop; x<pa->disprect.xmax-crop; x++, shr+=osa, pass+=4, od++) {
- if(spart->mask[od] == 0) {
- if(spart->addpassflag & SCE_PASS_VECTOR)
- add_transp_speed(rl, od, NULL, 0.0f, rdrect);
- }
- else {
- if(re->osa == 0) {
- addAlphaUnderFloat(pass, shr->combined);
- }
- else {
- for(a=0; a<re->osa; a++)
- add_filt_fmask(1<<a, shr[a].combined, pass, rr->rectx);
- }
-
- if(spart->addpassflag) {
- /* merge all in one, and then add */
- merge_transp_passes(rl, shr);
- add_transp_passes(rl, od, shr, pass[3]);
-
- if(spart->addpassflag & SCE_PASS_VECTOR)
- add_transp_speed(rl, od, shr->winspeed, pass[3], rdrect);
- }
- }
- }
-
- shrrect+= pa->rectx*osa;
- passrect+= 4*pa->rectx;
- offs+= pa->rectx;
- }
-
- /* disable scanline updating */
- rr->renlay= NULL;
+ if(!strand_segment_recursive(re, winmat, spart, zspan, totzspan, sseg, p1, p2, 0))
+ strand_render(re, sseg, winmat, spart, zspan, totzspan, p1, p2);
}
/* render call to fill in strands */
-unsigned short *zbuffer_strands_shade(Render *re, RenderPart *pa, RenderLayer *rl, float *pass)
+int zbuffer_strands_abuf(Render *re, RenderPart *pa, RenderLayer *rl, APixstrand *apixbuf, ListBase *apsmbase, StrandShadeCache *cache)
{
- //struct RenderPrimitiveIterator *iter;
ObjectRen *obr;
ObjectInstanceRen *obi;
ZSpan zspan;
StrandRen *strand=0;
StrandVert *svert;
+ StrandBound *sbound;
StrandPart spart;
StrandSegment sseg;
StrandSortSegment *sortsegments = NULL, *sortseg, *firstseg;
MemArena *memarena;
float z[4], bounds[4], winmat[4][4];
- int a, b, i, resultsize, totsegment, clip[4];
+ int a, b, c, i, totsegment, clip[4];
if(re->test_break())
- return NULL;
+ return 0;
if(re->totstrand == 0)
- return NULL;
+ return 0;
/* setup StrandPart */
memset(&spart, 0, sizeof(spart));
spart.re= re;
- spart.rl= rl;
- spart.pass= pass;
spart.rectx= pa->rectx;
spart.recty= pa->recty;
+ spart.apixbuf= apixbuf;
+ spart.zspan= &zspan;
+ spart.rectdaps= pa->rectdaps;
spart.rectz= pa->rectz;
- spart.addpassflag= rl->passflag & ~(SCE_PASS_Z|SCE_PASS_COMBINED);
- spart.addzbuf= rl->passflag & SCE_PASS_Z;
-
- if(re->osa) resultsize= pa->rectx*pa->recty*re->osa;
- else resultsize= pa->rectx*pa->recty;
- spart.result= MEM_callocN(sizeof(ShadeResult)*resultsize, "StrandPartResult");
- spart.mask= MEM_callocN(pa->rectx*pa->recty*sizeof(short), "StrandPartMask");
-
- if(spart.addpassflag & SCE_PASS_VECTOR) {
- /* initialize speed vectors */
- for(a=0; a<resultsize; a++) {
- spart.result[a].winspeed[0]= PASS_VECTOR_MAX;
- spart.result[a].winspeed[1]= PASS_VECTOR_MAX;
- spart.result[a].winspeed[2]= PASS_VECTOR_MAX;
- spart.result[a].winspeed[3]= PASS_VECTOR_MAX;
- }
- }
-
- if(spart.addzbuf) {
- /* duplicate rectz so we can read from the old buffer, while
- * writing new z values */
- spart.rectz= MEM_dupallocN(pa->rectz);
- spart.outrectz= pa->rectz;
- }
-
- shade_sample_initialize(&spart.ssamp1, pa, rl);
- shade_sample_initialize(&spart.ssamp2, pa, rl);
- shade_sample_initialize(&spart.ssamp, pa, rl);
- spart.ssamp1.shi[0].sample= 0;
- spart.ssamp2.shi[0].sample= 1;
- spart.ssamp1.tot= 1;
- spart.ssamp2.tot= 1;
- spart.ssamp.tot= 1;
+ spart.rectmask= pa->rectmask;
+ spart.cache= cache;
zbuf_alloc_span(&zspan, pa->rectx, pa->recty, re->clipcrop);
@@ -1005,83 +804,83 @@ unsigned short *zbuffer_strands_shade(Render *re, RenderPart *pa, RenderLayer *r
zspan.zofsx -= 0.5f;
zspan.zofsy -= 0.5f;
+ zspan.apsmbase= apsmbase;
+
/* clipping setup */
bounds[0]= (2*pa->disprect.xmin - re->winx-1)/(float)re->winx;
bounds[1]= (2*pa->disprect.xmax - re->winx+1)/(float)re->winx;
bounds[2]= (2*pa->disprect.ymin - re->winy-1)/(float)re->winy;
bounds[3]= (2*pa->disprect.ymax - re->winy+1)/(float)re->winy;
- /* sort segments */
- //iter= init_primitive_iterator(re, re->strandbuckets, pa);
-
memarena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
firstseg= NULL;
sortseg= sortsegments;
totsegment= 0;
- //while((strand = next_primitive_iterator(iter))) {
+ /* for all object instances */
for(obi=re->instancetable.first, i=0; obi; obi=obi->next, i++) {
obr= obi->obr;
+ if(!obr->strandbuf || !(obr->strandbuf->lay & rl->lay))
+ continue;
+
+ /* compute matrix and try clipping whole object */
if(obi->flag & R_TRANSFORMED)
zbuf_make_winmat(re, obi->mat, winmat);
else
zbuf_make_winmat(re, NULL, winmat);
- for(a=0; a<obr->totstrand; a++) {
- if((a & 255)==0) strand= obr->strandnodes[a>>8].strand;
- else strand++;
+ if(clip_render_object(obi->obr->boundbox, bounds, winmat))
+ continue;
- if(re->test_break())
- break;
-
-#if 0
- if(strand->clip)
+ /* for each bounding box containing a number of strands */
+ sbound= obr->strandbuf->bound;
+ for(c=0; c<obr->strandbuf->totbound; c++, sbound++) {
+ if(clip_render_object(sbound->boundbox, bounds, winmat))
continue;
-#endif
-
- svert= strand->vert;
-
- /* keep clipping and z depth for 4 control points */
- clip[1]= strand_test_clip(winmat, &zspan, bounds, svert->co, &z[1]);
- clip[2]= strand_test_clip(winmat, &zspan, bounds, (svert+1)->co, &z[2]);
- clip[0]= clip[1]; z[0]= z[1];
- for(b=0; b<strand->totvert-1; b++, svert++) {
- /* compute 4th point clipping and z depth */
- if(b < strand->totvert-2) {
- clip[3]= strand_test_clip(winmat, &zspan, bounds, (svert+2)->co, &z[3]);
- }
- else {
- clip[3]= clip[2]; z[3]= z[2];
- }
-
- /* check clipping and add to sortsegments buffer */
- if(!(clip[0] & clip[1] & clip[2] & clip[3])) {
- sortseg= BLI_memarena_alloc(memarena, sizeof(StrandSortSegment));
- sortseg->obi= i;
- sortseg->strand= strand->index;
- sortseg->segment= b;
+ /* for each strand in this bounding box */
+ for(a=sbound->start; a<sbound->end; a++) {
+ strand= RE_findOrAddStrand(obr, a);
+ svert= strand->vert;
- sortseg->z= 0.5f*(z[1] + z[2]);
+ /* keep clipping and z depth for 4 control points */
+ clip[1]= strand_test_clip(winmat, &zspan, bounds, svert->co, &z[1]);
+ clip[2]= strand_test_clip(winmat, &zspan, bounds, (svert+1)->co, &z[2]);
+ clip[0]= clip[1]; z[0]= z[1];
- sortseg->next= firstseg;
- firstseg= sortseg;
- totsegment++;
+ for(b=0; b<strand->totvert-1; b++, svert++) {
+ /* compute 4th point clipping and z depth */
+ if(b < strand->totvert-2) {
+ clip[3]= strand_test_clip(winmat, &zspan, bounds, (svert+2)->co, &z[3]);
+ }
+ else {
+ clip[3]= clip[2]; z[3]= z[2];
+ }
+
+ /* check clipping and add to sortsegments buffer */
+ if(!(clip[0] & clip[1] & clip[2] & clip[3])) {
+ sortseg= BLI_memarena_alloc(memarena, sizeof(StrandSortSegment));
+ sortseg->obi= i;
+ sortseg->strand= strand->index;
+ sortseg->segment= b;
+
+ sortseg->z= 0.5f*(z[1] + z[2]);
+
+ sortseg->next= firstseg;
+ firstseg= sortseg;
+ totsegment++;
+ }
+
+ /* shift clipping and z depth */
+ clip[0]= clip[1]; z[0]= z[1];
+ clip[1]= clip[2]; z[1]= z[2];
+ clip[2]= clip[3]; z[2]= z[3];
}
-
- /* shift clipping and z depth */
- clip[0]= clip[1]; z[0]= z[1];
- clip[1]= clip[2]; z[1]= z[2];
- clip[2]= clip[3]; z[2]= z[3];
}
}
}
-#if 0
- free_primitive_iterator(iter);
-#endif
-
if(!re->test_break()) {
/* convert list to array and sort */
sortsegments= MEM_mallocN(sizeof(StrandSortSegment)*totsegment, "StrandSortSegment");
@@ -1092,7 +891,7 @@ unsigned short *zbuffer_strands_shade(Render *re, RenderPart *pa, RenderLayer *r
BLI_memarena_free(memarena);
- spart.hash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
+ spart.totapixbuf= MEM_callocN(sizeof(int)*pa->rectx*pa->recty, "totapixbuf");
if(!re->test_break()) {
/* render segments in sorted order */
@@ -1120,135 +919,94 @@ unsigned short *zbuffer_strands_shade(Render *re, RenderPart *pa, RenderLayer *r
spart.segment= &sseg;
- render_strand_segment(re, winmat, &spart, &zspan, &sseg);
+ render_strand_segment(re, winmat, &spart, &zspan, 1, &sseg);
}
}
- // TODO printf(">>> %d\n", BLI_ghash_size(spart.hash));
- BLI_ghash_free(spart.hash, NULL, (GHashValFreeFP)MEM_freeN);
-
- zbuffer_strands_filter(re, pa, rl, &spart, pass);
-
- /* free */
- MEM_freeN(spart.result);
-
- if(spart.addzbuf)
- MEM_freeN(spart.rectz);
-
if(sortsegments)
MEM_freeN(sortsegments);
+ MEM_freeN(spart.totapixbuf);
zbuf_free_span(&zspan);
- if(!(re->osa && (rl->layflag & SCE_LAY_SOLID))) {
- MEM_freeN(spart.mask);
- spart.mask= NULL;
- }
-
- return spart.mask;
+ return totsegment;
}
-void project_strands(Render *re, void (*projectfunc)(float *, float mat[][4], float *), int do_pano, int do_buckets)
-{
-#if 0
- ObjectRen *obr;
- StrandRen *strand = NULL;
- StrandVert *svert;
- float hoco[4], min[2], max[2], bucketco[2], vec[3];
- int a, b;
- /* float bmin[3], bmax[3], bpad[3], padding[2]; */
-
- if(re->strandbuckets) {
- free_buckets(re->strandbuckets);
- re->strandbuckets= NULL;
- }
-
- if(re->totstrand == 0)
- return;
-
- if(do_buckets)
- re->strandbuckets= init_buckets(re);
+/* *************** */
- /* calculate view coordinates (and zbuffer value) */
- for(obr=re->objecttable.first; obr; obr=obr->next) {
- for(a=0; a<obr->totstrand; a++) {
- if((a & 255)==0) strand= obr->strandnodes[a>>8].strand;
- else strand++;
+StrandSurface *cache_strand_surface(Render *re, ObjectRen *obr, DerivedMesh *dm, float mat[][4], int timeoffset)
+{
+ StrandSurface *mesh;
+ MFace *mface;
+ MVert *mvert;
+ float (*co)[3];
+ int a, totvert, totface;
+
+ totvert= dm->getNumVerts(dm);
+ totface= dm->getNumFaces(dm);
+
+ for(mesh=re->strandsurface.first; mesh; mesh=mesh->next)
+ if(mesh->obr.ob == obr->ob && mesh->obr.par == obr->par
+ && mesh->obr.index == obr->index && mesh->totvert==totvert && mesh->totface==totface)
+ break;
- strand->clip= ~0;
+ if(!mesh) {
+ mesh= MEM_callocN(sizeof(StrandSurface), "StrandSurface");
+ mesh->obr= *obr;
+ mesh->totvert= totvert;
+ mesh->totface= totface;
+ mesh->face= MEM_callocN(sizeof(int)*4*mesh->totface, "StrandSurfFaces");
+ mesh->col= MEM_callocN(sizeof(float)*3*mesh->totvert, "StrandSurfCol");
+ BLI_addtail(&re->strandsurface, mesh);
+ }
+
+ if(timeoffset == -1 && !mesh->prevco)
+ mesh->prevco= co= MEM_callocN(sizeof(float)*3*mesh->totvert, "StrandSurfCo");
+ else if(timeoffset == 0 && !mesh->co)
+ mesh->co= co= MEM_callocN(sizeof(float)*3*mesh->totvert, "StrandSurfCo");
+ else if(timeoffset == 1 && !mesh->nextco)
+ mesh->nextco= co= MEM_callocN(sizeof(float)*3*mesh->totvert, "StrandSurfCo");
+ else
+ return mesh;
-#if 0
- if(!(strand->buffer->flag & R_STRAND_BSPLINE)) {
- INIT_MINMAX(bmin, bmax);
- svert= strand->vert;
- for(b=0; b<strand->totvert; b++, svert++)
- DO_MINMAX(svert->co, bmin, bmax)
+ mvert= dm->getVertArray(dm);
+ for(a=0; a<mesh->totvert; a++, mvert++) {
+ VECCOPY(co[a], mvert->co);
+ Mat4MulVecfl(mat, co[a]);
+ }
- bpad[0]= (bmax[0]-bmin[0])*0.2f;
- bpad[1]= (bmax[1]-bmin[1])*0.2f;
- bpad[2]= (bmax[2]-bmin[2])*0.2f;
- }
- else
- bpad[0]= bpad[1]= bpad[2]= 0.0f;
-
- ma= strand->buffer->ma;
- width= MAX2(ma->strand_sta, ma->strand_end);
- if(strand->buffer->flag & R_STRAND_B_UNITS) {
- bpad[0] += 0.5f*width;
- bpad[1] += 0.5f*width;
- bpad[2] += 0.5f*width;
- }
-#endif
+ mface= dm->getFaceArray(dm);
+ for(a=0; a<mesh->totface; a++, mface++) {
+ mesh->face[a][0]= mface->v1;
+ mesh->face[a][1]= mface->v2;
+ mesh->face[a][2]= mface->v3;
+ mesh->face[a][3]= mface->v4;
+ }
- INIT_MINMAX2(min, max);
- svert= strand->vert;
- for(b=0; b<strand->totvert; b++, svert++) {
- //VECADD(vec, svert->co, bpad);
+ return mesh;
+}
- /* same as VertRen */
- if(do_pano) {
- vec[0]= re->panoco*svert->co[0] + re->panosi*svert->co[2];
- vec[1]= svert->co[1];
- vec[2]= -re->panosi*svert->co[0] + re->panoco*svert->co[2];
- }
- else
- VECCOPY(vec, svert->co)
+void free_strand_surface(Render *re)
+{
+ StrandSurface *mesh;
- /* Go from wcs to hcs ... */
- projectfunc(vec, re->winmat, hoco);
- /* ... and clip in that system. */
- strand->clip &= testclip(hoco);
+ for(mesh=re->strandsurface.first; mesh; mesh=mesh->next) {
+ if(mesh->co) MEM_freeN(mesh->co);
+ if(mesh->prevco) MEM_freeN(mesh->prevco);
+ if(mesh->nextco) MEM_freeN(mesh->nextco);
+ if(mesh->col) MEM_freeN(mesh->col);
+ if(mesh->face) MEM_freeN(mesh->face);
+ }
-#if 0
- if(do_buckets) {
- project_hoco_to_bucket(re->strandbuckets, hoco, bucketco);
- DO_MINMAX2(bucketco, min, max);
- }
-#endif
- }
+ BLI_freelistN(&re->strandsurface);
+}
-#if 0
- if(do_buckets) {
- if(strand->buffer->flag & R_STRAND_BSPLINE) {
- min[0] -= width;
- min[1] -= width;
- max[0] += width;
- max[1] += width;
- }
- else {
- /* catmull-rom stays within 1.2f bounds in object space,
- * is this still true after projection? */
- min[0] -= width + (max[0]-min[0])*0.2f;
- min[1] -= width + (max[1]-min[1])*0.2f;
- max[0] += width + (max[0]-min[0])*0.2f;
- max[1] += width + (max[1]-min[1])*0.2f;
- }
+void strand_minmax(StrandRen *strand, float *min, float *max)
+{
+ StrandVert *svert;
+ int a;
- add_buckets_primitive(re->strandbuckets, min, max, strand);
- }
-#endif
- }
- }
-#endif
+ for(a=0, svert=strand->vert; a<strand->totvert; a++, svert++)
+ DO_MINMAX(svert->co, min, max)
}
diff --git a/source/blender/render/intern/source/sunsky.c b/source/blender/render/intern/source/sunsky.c
new file mode 100644
index 00000000000..2b490e71142
--- /dev/null
+++ b/source/blender/render/intern/source/sunsky.c
@@ -0,0 +1,499 @@
+ /**
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+
+#include "sunsky.h"
+#include "math.h"
+#include "BLI_arithb.h"
+#include "BKE_global.h"
+
+/**
+ * These macros are defined for vector operations
+ * */
+
+/**
+ * compute v1 = v2 op v3
+ * v1, v2 and v3 are vectors contains 3 float
+ * */
+#define vec3opv(v1, v2, op, v3) \
+ v1[0] = (v2[0] op v3[0]); \
+ v1[1] = (v2[1] op v3[1]);\
+ v1[2] = (v2[2] op v3[2]);
+
+/**
+ * compute v1 = v2 op f1
+ * v1, v2 are vectors contains 3 float
+ * and f1 is a float
+ * */
+#define vec3opf(v1, v2, op, f1)\
+ v1[0] = (v2[0] op (f1));\
+ v1[1] = (v2[1] op (f1));\
+ v1[2] = (v2[2] op (f1));
+
+/**
+ * compute v1 = f1 op v2
+ * v1, v2 are vectors contains 3 float
+ * and f1 is a float
+ * */
+#define fopvec3(v1, f1, op, v2)\
+ v1[0] = ((f1) op v2[0]);\
+ v1[1] = ((f1) op v2[1]);\
+ v1[2] = ((f1) op v2[2]);
+
+/**
+ * ClipColor:
+ * clip a color to range [0,1];
+ * */
+void ClipColor(float c[3])
+{
+ if (c[0] > 1.0) c[0] = 1.0;
+ if (c[0] < 0.0) c[0] = 0.0;
+ if (c[1] > 1.0) c[1] = 1.0;
+ if (c[1] < 0.0) c[1] = 0.0;
+ if (c[2] > 1.0) c[2] = 1.0;
+ if (c[2] < 0.0) c[2] = 0.0;
+}
+
+/**
+ * AngleBetween:
+ * compute angle between to direction
+ * all angles are in radians
+ * */
+static float AngleBetween(float thetav, float phiv, float theta, float phi)
+{
+ float cospsi = sin(thetav) * sin(theta) * cos(phi - phiv) + cos(thetav) * cos(theta);
+
+ if (cospsi > 1.0)
+ return 0;
+ if (cospsi < -1.0)
+ return M_PI;
+
+ return acos(cospsi);
+}
+
+/**
+ * DirectionToThetaPhi:
+ * this function convert a direction to it's theta and phi value
+ * parameters:
+ * toSun: contains direction information
+ * theta, phi, are return values from this conversion
+ * */
+static void DirectionToThetaPhi(float *toSun, float *theta, float *phi)
+{
+ *theta = acos(toSun[2]);
+ if (fabs(*theta) < 1e-5)
+ *phi = 0;
+ else
+ *phi = atan2(toSun[1], toSun[0]);
+}
+
+/**
+ * PerezFunction:
+ * compute perez function value based on input paramters
+ * */
+float PerezFunction(struct SunSky *sunsky, const float *lam, float theta, float gamma, float lvz)
+{
+ float den, num;
+
+ den = ((1 + lam[0] * exp(lam[1])) *
+ (1 + lam[2] * exp(lam[3] * sunsky->theta) + lam[4] * cos(sunsky->theta) * cos(sunsky->theta)));
+
+ num = ((1 + lam[0] * exp(lam[1] / cos(theta))) *
+ (1 + lam[2] * exp(lam[3] * gamma) + lam[4] * cos(gamma) * cos(gamma)));
+
+ return(lvz * num / den);}
+
+/**
+ * InitSunSky:
+ * this function compute some sun,sky parameters according to input parameters and also initiate some other sun, sky parameters
+ * parameters:
+ * sunSky, is a structure that contains informtion about sun, sky and atmosphere, in this function, most of its values initiated
+ * turb, is atmosphere turbidity
+ * toSun, contains sun direction
+ * horizon_brighness, controls the brightness of the horizon colors
+ * spread, controls colors spreed at horizon
+ * sun_brightness, controls sun's brightness
+ * sun_size, controls sun's size
+ * back_scatter, controls back scatter light
+ * */
+void InitSunSky(struct SunSky *sunsky, float turb, float *toSun, float horizon_brightness,
+ float spread,float sun_brightness, float sun_size, float back_scatter,
+ float skyblendfac, short skyblendtype, float sky_exposure, float sky_colorspace)
+{
+
+ float theta2;
+ float theta3;
+ float T;
+ float T2;
+ float chi;
+
+ sunsky->turbidity = turb;
+
+ sunsky->horizon_brightness = horizon_brightness;
+ sunsky->spread = spread;
+ sunsky->sun_brightness = sun_brightness;
+ sunsky->sun_size = sun_size;
+ sunsky->backscattered_light = back_scatter;
+ sunsky->skyblendfac= skyblendfac;
+ sunsky->skyblendtype= skyblendtype;
+ sunsky->sky_exposure= -sky_exposure;
+ sunsky->sky_colorspace= sky_colorspace;
+
+ sunsky->toSun[0] = toSun[0];
+ sunsky->toSun[1] = toSun[1];
+ sunsky->toSun[2] = toSun[2];
+
+ DirectionToThetaPhi(sunsky->toSun, &sunsky->theta, &sunsky->phi);
+
+ sunsky->sunSolidAngle = 0.25 * M_PI * 1.39 * 1.39 / (150 * 150); // = 6.7443e-05
+
+ theta2 = sunsky->theta*sunsky->theta;
+ theta3 = theta2 * sunsky->theta;
+ T = turb;
+ T2 = turb*turb;
+
+ chi = (4.0 / 9.0 - T / 120.0) * (M_PI - 2 * sunsky->theta);
+ sunsky->zenith_Y = (4.0453 * T - 4.9710) * tan(chi) - .2155 * T + 2.4192;
+ sunsky->zenith_Y *= 1000; // conversion from kcd/m^2 to cd/m^2
+
+ if (sunsky->zenith_Y<=0)
+ sunsky->zenith_Y = 1e-6;
+
+ sunsky->zenith_x =
+ ( + 0.00165 * theta3 - 0.00374 * theta2 + 0.00208 * sunsky->theta + 0) * T2 +
+ ( -0.02902 * theta3 + 0.06377 * theta2 - 0.03202 * sunsky->theta + 0.00394) * T +
+ ( + 0.11693 * theta3 - 0.21196 * theta2 + 0.06052 * sunsky->theta + 0.25885);
+
+ sunsky->zenith_y =
+ ( + 0.00275 * theta3 - 0.00610 * theta2 + 0.00316 * sunsky->theta + 0) * T2 +
+ ( -0.04214 * theta3 + 0.08970 * theta2 - 0.04153 * sunsky->theta + 0.00515) * T +
+ ( + 0.15346 * theta3 - 0.26756 * theta2 + 0.06669 * sunsky->theta + 0.26688);
+
+
+ sunsky->perez_Y[0] = 0.17872 * T - 1.46303;
+ sunsky->perez_Y[1] = -0.35540 * T + 0.42749;
+ sunsky->perez_Y[2] = -0.02266 * T + 5.32505;
+ sunsky->perez_Y[3] = 0.12064 * T - 2.57705;
+ sunsky->perez_Y[4] = -0.06696 * T + 0.37027;
+
+ sunsky->perez_x[0] = -0.01925 * T - 0.25922;
+ sunsky->perez_x[1] = -0.06651 * T + 0.00081;
+ sunsky->perez_x[2] = -0.00041 * T + 0.21247;
+ sunsky->perez_x[3] = -0.06409 * T - 0.89887;
+ sunsky->perez_x[4] = -0.00325 * T + 0.04517;
+
+ sunsky->perez_y[0] = -0.01669 * T - 0.26078;
+ sunsky->perez_y[1] = -0.09495 * T + 0.00921;
+ sunsky->perez_y[2] = -0.00792 * T + 0.21023;
+ sunsky->perez_y[3] = -0.04405 * T - 1.65369;
+ sunsky->perez_y[4] = -0.01092 * T + 0.05291;
+
+ /* suggested by glome in
+ * http://projects.blender.org/tracker/?func=detail&atid=127&aid=8063&group_id=9*/
+ sunsky->perez_Y[0] *= sunsky->horizon_brightness;
+ sunsky->perez_x[0] *= sunsky->horizon_brightness;
+ sunsky->perez_y[0] *= sunsky->horizon_brightness;
+
+ sunsky->perez_Y[1] *= sunsky->spread;
+ sunsky->perez_x[1] *= sunsky->spread;
+ sunsky->perez_y[1] *= sunsky->spread;
+
+ sunsky->perez_Y[2] *= sunsky->sun_brightness;
+ sunsky->perez_x[2] *= sunsky->sun_brightness;
+ sunsky->perez_y[2] *= sunsky->sun_brightness;
+
+ sunsky->perez_Y[3] *= sunsky->sun_size;
+ sunsky->perez_x[3] *= sunsky->sun_size;
+ sunsky->perez_y[3] *= sunsky->sun_size;
+
+ sunsky->perez_Y[4] *= sunsky->backscattered_light;
+ sunsky->perez_x[4] *= sunsky->backscattered_light;
+ sunsky->perez_y[4] *= sunsky->backscattered_light;
+}
+
+/**
+ * GetSkyXYZRadiance:
+ * this function compute sky radiance according to a view parameters `theta' and `phi'and sunSky values
+ * parameters:
+ * sunSky, sontains sun and sky parameters
+ * theta, is sun's theta
+ * phi, is sun's phi
+ * color_out, is computed color that shows sky radiance in XYZ color format
+ * */
+void GetSkyXYZRadiance(struct SunSky* sunsky, float theta, float phi, float color_out[3])
+{
+ float gamma;
+ float x,y,Y,X,Z;
+ float hfade=1, nfade=1;
+
+
+ if (theta>(0.5*M_PI)) {
+ hfade = 1.0-(theta*M_1_PI-0.5)*2.0;
+ hfade = hfade*hfade*(3.0-2.0*hfade);
+ theta = 0.5*M_PI;
+ }
+
+ if (sunsky->theta>(0.5*M_PI)) {
+ if (theta<=0.5*M_PI) {
+ nfade = 1.0-(0.5-theta*M_1_PI)*2.0;
+ nfade *= 1.0-(sunsky->theta*M_1_PI-0.5)*2.0;
+ nfade = nfade*nfade*(3.0-2.0*nfade);
+ }
+ }
+
+ gamma = AngleBetween(theta, phi, sunsky->theta, sunsky->phi);
+
+ // Compute xyY values
+ x = PerezFunction(sunsky, sunsky->perez_x, theta, gamma, sunsky->zenith_x);
+ y = PerezFunction(sunsky, sunsky->perez_y, theta, gamma, sunsky->zenith_y);
+ Y = 6.666666667e-5 * nfade * hfade * PerezFunction(sunsky, sunsky->perez_Y, theta, gamma, sunsky->zenith_Y);
+
+ if(sunsky->sky_exposure!=0.0f)
+ Y = 1.0 - exp(Y*sunsky->sky_exposure);
+
+ X = (x / y) * Y;
+ Z = ((1 - x - y) / y) * Y;
+
+ color_out[0] = X;
+ color_out[1] = Y;
+ color_out[2] = Z;
+}
+
+/**
+ * GetSkyXYZRadiancef:
+ * this function compute sky radiance according to a view direction `varg' and sunSky values
+ * parameters:
+ * sunSky, sontains sun and sky parameters
+ * varg, shows direction
+ * color_out, is computed color that shows sky radiance in XYZ color format
+ * */
+void GetSkyXYZRadiancef(struct SunSky* sunsky, const float varg[3], float color_out[3])
+{
+ float theta, phi;
+ float v[3];
+
+ VecCopyf(v, (float*)varg);
+ Normalize(v);
+
+ if (v[2] < 0.001){
+ v[2] = 0.001;
+ Normalize(v);
+ }
+
+ DirectionToThetaPhi(v, &theta, &phi);
+ GetSkyXYZRadiance(sunsky, theta, phi, color_out);
+}
+
+/**
+ * ComputeAttenuatedSunlight:
+ * this function compute attenuated sun light based on sun's theta and atmosphere turbidity
+ * parameters:
+ * theta, is sun's theta
+ * turbidity: is atmosphere turbidity
+ * fTau: contains computed attenuated sun light
+ * */
+void ComputeAttenuatedSunlight(float theta, int turbidity, float fTau[3])
+{
+ float fBeta ;
+ float fTauR, fTauA;
+ float m ;
+ float fAlpha;
+
+ int i;
+ float fLambda[3];
+ fLambda[0] = 0.65f;
+ fLambda[1] = 0.57f;
+ fLambda[2] = 0.475f;
+
+ fAlpha = 1.3f;
+ fBeta = 0.04608365822050f * turbidity - 0.04586025928522f;
+
+ m = 1.0/(cos(theta) + 0.15f*pow(93.885f-theta/M_PI*180.0f,-1.253f));
+
+ for(i = 0; i < 3; i++)
+ {
+ // Rayleigh Scattering
+ fTauR = exp( -m * 0.008735f * pow(fLambda[i], (float)(-4.08f)));
+
+ // Aerosal (water + dust) attenuation
+ fTauA = exp(-m * fBeta * pow(fLambda[i], -fAlpha));
+
+ fTau[i] = fTauR * fTauA;
+ }
+}
+
+/**
+ * InitAtmosphere:
+ * this function intiate sunSky structure with user input parameters.
+ * parameters:
+ * sunSky, contains information about sun, and in this function some atmosphere parameters will initiated
+ * sun_intens, shows sun intensity value
+ * mief, Mie scattering factor this factor currently call with 1.0
+ * rayf, Rayleigh scattering factor, this factor currently call with 1.0
+ * inscattf, inscatter light factor that range from 0.0 to 1.0, 0.0 means no inscatter light and 1.0 means full inscatter light
+ * extincf, extinction light factor that range from 0.0 to 1.0, 0.0 means no extinction and 1.0 means full extinction
+ * disf, is distance factor, multiplyed to pixle's z value to compute each pixle's distance to camera,
+ * */
+void InitAtmosphere(struct SunSky *sunSky, float sun_intens, float mief, float rayf,
+ float inscattf, float extincf, float disf)
+{
+ const float pi = 3.14159265358f;
+ const float n = 1.003f; // refractive index
+ const float N = 2.545e25;
+ const float pn = 0.035f;
+ const float T = 2.0f;
+ float fTemp, fTemp2, fTemp3, fBeta, fBetaDash;
+ float c = (6.544*T - 6.51)*1e-17;
+ float K[3] = {0.685f, 0.679f, 0.670f};
+ float vBetaMieTemp[3];
+
+ float fLambda[3],fLambda2[3], fLambda4[3];
+ float vLambda2[3];
+ float vLambda4[3];
+
+ int i;
+
+ sunSky->atm_SunIntensity = sun_intens;
+ sunSky->atm_BetaMieMultiplier = mief;
+ sunSky->atm_BetaRayMultiplier = rayf;
+ sunSky->atm_InscatteringMultiplier = inscattf;
+ sunSky->atm_ExtinctionMultiplier = extincf;
+ sunSky->atm_DistanceMultiplier = disf;
+
+ sunSky->atm_HGg=0.8;
+
+ fLambda[0] = 1/650e-9f;
+ fLambda[1] = 1/570e-9f;
+ fLambda[2] = 1/475e-9f;
+ for (i=0; i < 3; i++)
+ {
+ fLambda2[i] = fLambda[i]*fLambda[i];
+ fLambda4[i] = fLambda2[i]*fLambda2[i];
+ }
+
+ vLambda2[0] = fLambda2[0];
+ vLambda2[1] = fLambda2[1];
+ vLambda2[2] = fLambda2[2];
+
+ vLambda4[0] = fLambda4[0];
+ vLambda4[1] = fLambda4[1];
+ vLambda4[2] = fLambda4[2];
+
+ // Rayleigh scattering constants.
+ fTemp = pi*pi*(n*n-1)*(n*n-1)*(6+3*pn)/(6-7*pn)/N;
+ fBeta = 8*fTemp*pi/3;
+
+ vec3opf(sunSky->atm_BetaRay, vLambda4, *, fBeta);
+ fBetaDash = fTemp/2;
+ vec3opf(sunSky->atm_BetaDashRay, vLambda4,*, fBetaDash);
+
+
+ // Mie scattering constants.
+ fTemp2 = 0.434*c*(2*pi)*(2*pi)*0.5f;
+ vec3opf(sunSky->atm_BetaDashMie, vLambda2, *, fTemp2);
+
+ fTemp3 = 0.434f*c*pi*(2*pi)*(2*pi);
+
+ vec3opv(vBetaMieTemp, K, *, fLambda);
+ vec3opf(sunSky->atm_BetaMie, vBetaMieTemp,*, fTemp3);
+
+}
+
+/**
+ * AtmospherePixleShader:
+ * this function apply atmosphere effect on a pixle color `rgb' at distance `s'
+ * parameters:
+ * sunSky, contains information about sun parameters and user values
+ * view, is camera view vector
+ * s, is distance
+ * rgb, contains rendered color value for a pixle
+ * */
+void AtmospherePixleShader( struct SunSky* sunSky, float view[3], float s, float rgb[3])
+{
+ float costheta;
+ float Phase_1;
+ float Phase_2;
+ float sunColor[3];
+
+ float E[3];
+ float E1[3];
+
+
+ float I[3];
+ float fTemp;
+ float vTemp1[3], vTemp2[3];
+
+ float sunDirection[3];
+
+ s *= sunSky->atm_DistanceMultiplier;
+
+ sunDirection[0] = sunSky->toSun[0];
+ sunDirection[1] = sunSky->toSun[1];
+ sunDirection[2] = sunSky->toSun[2];
+
+ costheta = Inpf(view, sunDirection); // cos(theta)
+ Phase_1 = 1 + (costheta * costheta); // Phase_1
+
+ vec3opf(sunSky->atm_BetaRay, sunSky->atm_BetaRay, *, sunSky->atm_BetaRayMultiplier);
+ vec3opf(sunSky->atm_BetaMie, sunSky->atm_BetaMie, *, sunSky->atm_BetaMieMultiplier);
+ vec3opv(sunSky->atm_BetaRM, sunSky->atm_BetaRay, +, sunSky->atm_BetaMie);
+
+ //e^(-(beta_1 + beta_2) * s) = E1
+ vec3opf(E1, sunSky->atm_BetaRM, *, -s/log(2));
+ E1[0] = exp(E1[0]);
+ E1[1] = exp(E1[1]);
+ E1[2] = exp(E1[2]);
+
+ VecCopyf(E, E1);
+
+ //Phase2(theta) = (1-g^2)/(1+g-2g*cos(theta))^(3/2)
+ fTemp = 1 + sunSky->atm_HGg - 2 * sunSky->atm_HGg * costheta;
+ fTemp = fTemp * sqrt(fTemp);
+ Phase_2 = (1 - sunSky->atm_HGg * sunSky->atm_HGg)/fTemp;
+
+ vec3opf(vTemp1, sunSky->atm_BetaDashRay, *, Phase_1);
+ vec3opf(vTemp2, sunSky->atm_BetaDashMie, *, Phase_2);
+
+ vec3opv(vTemp1, vTemp1, +, vTemp2);
+ fopvec3(vTemp2, 1.0, -, E1);
+ vec3opv(vTemp1, vTemp1, *, vTemp2);
+
+ fopvec3(vTemp2, 1.0, / , sunSky->atm_BetaRM);
+
+ vec3opv(I, vTemp1, *, vTemp2);
+
+ vec3opf(I, I, *, sunSky->atm_InscatteringMultiplier);
+ vec3opf(E, E, *, sunSky->atm_ExtinctionMultiplier);
+
+ //scale to color sun
+ ComputeAttenuatedSunlight(sunSky->theta, sunSky->turbidity, sunColor);
+ vec3opv(E, E, *, sunColor);
+
+ vec3opf(I, I, *, sunSky->atm_SunIntensity);
+
+ vec3opv(rgb, rgb, *, E);
+ vec3opv(rgb, rgb, +, I);
+}
+
+#undef vec3opv
+#undef vec3opf
+#undef fopvec3
+
+/* EOF */
diff --git a/source/blender/render/intern/source/texture.c b/source/blender/render/intern/source/texture.c
index b502fb2b421..7ce66ff6d12 100644
--- a/source/blender/render/intern/source/texture.c
+++ b/source/blender/render/intern/source/texture.c
@@ -53,6 +53,7 @@
#include "BKE_global.h"
#include "BKE_main.h"
+#include "BKE_material.h"
#include "BKE_library.h"
#include "BKE_image.h"
@@ -98,7 +99,7 @@ void init_render_texture(Render *re, Tex *tex)
}
else if(tex->type==TEX_ENVMAP) {
/* just in case */
- tex->imaflag= TEX_INTERPOL | TEX_MIPMAP;
+ tex->imaflag |= TEX_INTERPOL | TEX_MIPMAP;
tex->extend= TEX_CLIP;
if(tex->env) {
@@ -720,30 +721,59 @@ static int plugintex(Tex *tex, float *texvec, float *dxt, float *dyt, int osatex
{
PluginTex *pit;
int rgbnor=0;
+ float result[ 8 ];
texres->tin= 0.0;
pit= tex->plugin;
if(pit && pit->doit) {
if(texres->nor) {
- VECCOPY(pit->result+5, texres->nor);
+ if (pit->version < 6) {
+ VECCOPY(pit->result+5, texres->nor);
+ } else {
+ VECCOPY(result+5, texres->nor);
+ }
+ }
+ if (pit->version < 6) {
+ if(osatex) rgbnor= ((TexDoitold)pit->doit)(tex->stype,
+ pit->data, texvec, dxt, dyt);
+ else rgbnor= ((TexDoitold)pit->doit)(tex->stype,
+ pit->data, texvec, 0, 0);
+ } else {
+ if(osatex) rgbnor= ((TexDoit)pit->doit)(tex->stype,
+ pit->data, texvec, dxt, dyt, result);
+ else rgbnor= ((TexDoit)pit->doit)(tex->stype,
+ pit->data, texvec, 0, 0, result);
}
- if(osatex) rgbnor= ((TexDoit)pit->doit)(tex->stype, pit->data, texvec, dxt, dyt);
- else rgbnor= ((TexDoit)pit->doit)(tex->stype, pit->data, texvec, 0, 0);
- texres->tin= pit->result[0];
+ if (pit->version < 6) {
+ texres->tin = pit->result[0];
+ } else {
+ texres->tin = result[0];
+ }
if(rgbnor & TEX_NOR) {
if(texres->nor) {
- VECCOPY(texres->nor, pit->result+5);
+ if (pit->version < 6) {
+ VECCOPY(texres->nor, pit->result+5);
+ } else {
+ VECCOPY(texres->nor, result+5);
+ }
}
}
if(rgbnor & TEX_RGB) {
- texres->tr= pit->result[1];
- texres->tg= pit->result[2];
- texres->tb= pit->result[3];
- texres->ta= pit->result[4];
+ if (pit->version < 6) {
+ texres->tr = pit->result[1];
+ texres->tg = pit->result[2];
+ texres->tb = pit->result[3];
+ texres->ta = pit->result[4];
+ } else {
+ texres->tr = result[1];
+ texres->tg = result[2];
+ texres->tb = result[3];
+ texres->ta = result[4];
+ }
BRICONTRGB;
}
@@ -1202,6 +1232,8 @@ static int multitex(Tex *tex, float *texvec, float *dxt, float *dyt, int osatex,
return retval;
}
+/* Warning, if the texres's values are not declared zero, check the return value to be sure
+ * the color values are set before using the r/g/b values, otherwise you may use uninitialized values - Campbell */
int multitex_ext(Tex *tex, float *texvec, float *dxt, float *dyt, int osatex, TexResult *texres)
{
@@ -1255,7 +1287,7 @@ void texture_rgb_blend(float *in, float *tex, float *out, float fact, float facg
in[1]= (fact*tex[1] + facm*out[1]);
in[2]= (fact*tex[2] + facm*out[2]);
break;
-
+
case MTEX_MUL:
fact*= facg;
facm= 1.0-facg;
@@ -1343,9 +1375,28 @@ void texture_rgb_blend(float *in, float *tex, float *out, float fact, float facg
col= fact*tex[2];
if(col > out[2]) in[2]= col; else in[2]= out[2];
break;
+
+ case MTEX_BLEND_HUE:
+ fact*= facg;
+ VECCOPY(in, out);
+ ramp_blend(MA_RAMP_HUE, in, in+1, in+2, fact, tex);
+ break;
+ case MTEX_BLEND_SAT:
+ fact*= facg;
+ VECCOPY(in, out);
+ ramp_blend(MA_RAMP_SAT, in, in+1, in+2, fact, tex);
+ break;
+ case MTEX_BLEND_VAL:
+ fact*= facg;
+ VECCOPY(in, out);
+ ramp_blend(MA_RAMP_VAL, in, in+1, in+2, fact, tex);
+ break;
+ case MTEX_BLEND_COLOR:
+ fact*= facg;
+ VECCOPY(in, out);
+ ramp_blend(MA_RAMP_COLOR, in, in+1, in+2, fact, tex);
+ break;
}
-
-
}
float texture_value_blend(float tex, float out, float fact, float facg, int blendtype, int flip)
@@ -1427,7 +1478,14 @@ void do_material_tex(ShadeInput *shi)
/* which coords */
if(mtex->texco==TEXCO_ORCO) {
- co= shi->lo; dx= shi->dxlo; dy= shi->dylo;
+ if(mtex->texflag & MTEX_DUPLI_MAPTO) {
+ co= shi->duplilo; dx= dxt; dy= dyt;
+ dxt[0]= dxt[1]= dxt[2]= 0.0f;
+ dyt[0]= dyt[1]= dyt[2]= 0.0f;
+ }
+ else {
+ co= shi->lo; dx= shi->dxlo; dy= shi->dylo;
+ }
}
else if(mtex->texco==TEXCO_STICKY) {
co= shi->sticky; dx= shi->dxsticky; dy= shi->dysticky;
@@ -1439,6 +1497,9 @@ void do_material_tex(ShadeInput *shi)
dx= dxt;
dy= dyt;
VECCOPY(tempvec, shi->co);
+ if(mtex->texflag & MTEX_OB_DUPLI_ORIG)
+ if(shi->obi && shi->obi->duplitexmat)
+ MTC_Mat4MulVecfl(shi->obi->duplitexmat, tempvec);
MTC_Mat4MulVecfl(ob->imat, tempvec);
if(shi->osatex) {
VECCOPY(dxt, shi->dxco);
@@ -1466,28 +1527,35 @@ void do_material_tex(ShadeInput *shi)
co= shi->gl; dx= shi->dxco; dy= shi->dyco;
}
else if(mtex->texco==TEXCO_UV) {
- ShadeInputUV *suv= &shi->uv[shi->actuv];
- int i;
-
- if(mtex->uvname[0] != 0) {
- for(i = 0; i < shi->totuv; i++) {
- if(strcmp(shi->uv[i].name, mtex->uvname)==0) {
- suv= &shi->uv[i];
- break;
+ if(mtex->texflag & MTEX_DUPLI_MAPTO) {
+ co= shi->dupliuv; dx= dxt; dy= dyt;
+ dxt[0]= dxt[1]= dxt[2]= 0.0f;
+ dyt[0]= dyt[1]= dyt[2]= 0.0f;
+ }
+ else {
+ ShadeInputUV *suv= &shi->uv[shi->actuv];
+ int i;
+
+ if(mtex->uvname[0] != 0) {
+ for(i = 0; i < shi->totuv; i++) {
+ if(strcmp(shi->uv[i].name, mtex->uvname)==0) {
+ suv= &shi->uv[i];
+ break;
+ }
}
}
- }
- co= suv->uv;
- dx= suv->dxuv;
- dy= suv->dyuv;
+ co= suv->uv;
+ dx= suv->dxuv;
+ dy= suv->dyuv;
+ }
}
else if(mtex->texco==TEXCO_WINDOW) {
co= shi->winco; dx= shi->dxwin; dy= shi->dywin;
}
else if(mtex->texco==TEXCO_STRAND) {
co= tempvec; dx= dxt; dy= dyt;
- co[0]= shi->strand;
+ co[0]= shi->strandco;
co[1]= co[2]= 0.0f;
dx[0]= shi->dxstrand;
dx[1]= dx[2]= 0.0f;
@@ -1644,18 +1712,18 @@ void do_material_tex(ShadeInput *shi)
texres.nor[2]= texres.tb;
}
else {
- float co= 0.5*cos(texres.tin-0.5);
+ float co_nor= 0.5*cos(texres.tin-0.5);
float si= 0.5*sin(texres.tin-0.5);
float f1, f2;
f1= shi->vn[0];
f2= shi->vn[1];
- texres.nor[0]= f1*co+f2*si;
- texres.nor[1]= f2*co-f1*si;
+ texres.nor[0]= f1*co_nor+f2*si;
+ texres.nor[1]= f2*co_nor-f1*si;
f1= shi->vn[1];
f2= shi->vn[2];
- texres.nor[1]= f1*co+f2*si;
- texres.nor[2]= f2*co-f1*si;
+ texres.nor[1]= f1*co_nor+f2*si;
+ texres.nor[2]= f2*co_nor-f1*si;
}
}
// warping, local space
@@ -1743,11 +1811,11 @@ void do_material_tex(ShadeInput *shi)
if(mtex->normapspace == MTEX_NSPACE_TANGENT) {
/* qdn: tangent space */
float B[3], tv[3];
- Crossf(B, shi->vn, shi->tang); /* bitangent */
+ Crossf(B, shi->vn, shi->nmaptang); /* bitangent */
/* transform norvec from tangent space to object surface in camera space */
- tv[0] = texres.nor[0]*shi->tang[0] + texres.nor[1]*B[0] + texres.nor[2]*shi->vn[0];
- tv[1] = texres.nor[0]*shi->tang[1] + texres.nor[1]*B[1] + texres.nor[2]*shi->vn[1];
- tv[2] = texres.nor[0]*shi->tang[2] + texres.nor[1]*B[2] + texres.nor[2]*shi->vn[2];
+ tv[0] = texres.nor[0]*shi->nmaptang[0] + texres.nor[1]*B[0] + texres.nor[2]*shi->vn[0];
+ tv[1] = texres.nor[0]*shi->nmaptang[1] + texres.nor[1]*B[1] + texres.nor[2]*shi->vn[1];
+ tv[2] = texres.nor[0]*shi->nmaptang[2] + texres.nor[1]*B[2] + texres.nor[2]*shi->vn[2];
shi->vn[0]= facm*shi->vn[0] + fact*tv[0];
shi->vn[1]= facm*shi->vn[1] + fact*tv[1];
shi->vn[2]= facm*shi->vn[2] + fact*tv[2];
@@ -1762,8 +1830,8 @@ void do_material_tex(ShadeInput *shi)
Mat4Mul3Vecfl(R.viewmat, nor);
}
else if(mtex->normapspace == MTEX_NSPACE_OBJECT) {
- if(shi->vlr && shi->vlr->obr->ob)
- Mat4Mul3Vecfl(shi->vlr->obr->ob->obmat, nor);
+ if(shi->obr && shi->obr->ob)
+ Mat4Mul3Vecfl(shi->obr->ob->obmat, nor);
Mat4Mul3Vecfl(R.viewmat, nor);
}
@@ -1776,24 +1844,24 @@ void do_material_tex(ShadeInput *shi)
}
}
else {
+ float nor[3], dot;
+
if(shi->mat->mode & MA_TANGENT_V) {
shi->tang[0]+= Tnor*tex->norfac*texres.nor[0];
shi->tang[1]+= Tnor*tex->norfac*texres.nor[1];
shi->tang[2]+= Tnor*tex->norfac*texres.nor[2];
}
- else {
- float nor[3], dot;
- /* prevent bump to become negative normal */
- nor[0]= Tnor*tex->norfac*texres.nor[0];
- nor[1]= Tnor*tex->norfac*texres.nor[1];
- nor[2]= Tnor*tex->norfac*texres.nor[2];
-
- dot= 0.5f + 0.5f*INPR(nor, shi->vn);
-
- shi->vn[0]+= dot*nor[0];
- shi->vn[1]+= dot*nor[1];
- shi->vn[2]+= dot*nor[2];
- }
+
+ /* prevent bump to become negative normal */
+ nor[0]= Tnor*tex->norfac*texres.nor[0];
+ nor[1]= Tnor*tex->norfac*texres.nor[1];
+ nor[2]= Tnor*tex->norfac*texres.nor[2];
+
+ dot= 0.5f + 0.5f*INPR(nor, shi->vn);
+
+ shi->vn[0]+= dot*nor[0];
+ shi->vn[1]+= dot*nor[1];
+ shi->vn[2]+= dot*nor[2];
}
Normalize(shi->vn);
@@ -2233,7 +2301,7 @@ void do_sky_tex(float *rco, float *lo, float *dxyview, float *hor, float *zen, f
/* ------------------------------------------------------------------------- */
/* colf supposed to be initialized with la->r,g,b */
-void do_lamp_tex(LampRen *la, float *lavec, ShadeInput *shi, float *colf)
+void do_lamp_tex(LampRen *la, float *lavec, ShadeInput *shi, float *colf, int effect)
{
Object *ob;
MTex *mtex;
@@ -2372,7 +2440,7 @@ void do_lamp_tex(LampRen *la, float *lavec, ShadeInput *shi, float *colf)
}
/* mapping */
- if(mtex->mapto & LAMAP_COL) {
+ if(((mtex->mapto & LAMAP_COL) && (effect & LA_TEXTURE))||((mtex->mapto & LAMAP_SHAD) && (effect & LA_SHAD_TEX))) {
float col[3];
if(rgb==0) {
@@ -2450,21 +2518,31 @@ int externtex(MTex *mtex, float *vec, float *tin, float *tr, float *tg, float *t
void render_realtime_texture(ShadeInput *shi, Image *ima)
{
TexResult texr;
- static Tex tex1, tex2; // threadsafe
+ static Tex imatex[BLENDER_MAX_THREADS]; // threadsafe
static int firsttime= 1;
Tex *tex;
float texvec[3], dx[2], dy[2];
ShadeInputUV *suv= &shi->uv[shi->actuv];
+ int a;
+
+ if(R.r.scemode & R_NO_TEX) return;
if(firsttime) {
- firsttime= 0;
- default_tex(&tex1);
- default_tex(&tex2);
- tex1.type= TEX_IMAGE;
- tex2.type= TEX_IMAGE;
+ BLI_lock_thread(LOCK_IMAGE);
+ if(firsttime) {
+ for(a=0; a<BLENDER_MAX_THREADS; a++) {
+ memset(&imatex[a], 0, sizeof(Tex));
+ default_tex(&imatex[a]);
+ imatex[a].type= TEX_IMAGE;
+ }
+
+ firsttime= 0;
+ }
+ BLI_unlock_thread(LOCK_IMAGE);
}
- if(shi->ys & 1) tex= &tex1; else tex= &tex2; // threadsafe
+ tex= &imatex[shi->thread];
+ tex->iuser.ok= ima->ok;
texvec[0]= 0.5+0.5*suv->uv[0];
texvec[1]= 0.5+0.5*suv->uv[1];
@@ -2480,7 +2558,7 @@ void render_realtime_texture(ShadeInput *shi, Image *ima)
if(shi->osatex) imagewraposa(tex, ima, NULL, texvec, dx, dy, &texr);
else imagewrap(tex, ima, NULL, texvec, &texr);
-
+
shi->vcol[0]*= texr.tr;
shi->vcol[1]*= texr.tg;
shi->vcol[2]*= texr.tb;
diff --git a/source/blender/render/intern/source/zbuf.c b/source/blender/render/intern/source/zbuf.c
index 57d2bbb3489..509ac81c58b 100644
--- a/source/blender/render/intern/source/zbuf.c
+++ b/source/blender/render/intern/source/zbuf.c
@@ -196,7 +196,6 @@ static void zbuf_add_to_span(ZSpan *zspan, float *v1, float *v2)
/* Functions */
/*-----------------------------------------------------------*/
-
void fillrect(int *rect, int x, int y, int val)
{
int len, *drect;
@@ -307,8 +306,8 @@ static void zbuffillAc4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v2,
float x0,y0,z0;
float x1,y1,z1,x2,y2,z2,xx1;
float *span1, *span2;
- int *rz, x, y;
- int sn1, sn2, rectx, *rectzofs, my0, my2, mask;
+ int *rz, *rm, x, y;
+ int sn1, sn2, rectx, *rectzofs, *rectmaskofs, my0, my2, mask;
/* init */
zbuf_init_span(zspan);
@@ -353,6 +352,7 @@ static void zbuffillAc4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v2,
/* start-offset in rect */
rectx= zspan->rectx;
rectzofs= (int *)(zspan->arectz+rectx*(my2));
+ rectmaskofs= (int *)(zspan->rectmask+rectx*(my2));
apofs= (zspan->apixbuf+ rectx*(my2));
mask= zspan->mask;
@@ -377,35 +377,40 @@ static void zbuffillAc4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v2,
if(sn1<0) sn1= 0;
if(sn2>=sn1) {
+ int intzverg;
+
zverg= (double)sn1*zxd + zy0;
rz= rectzofs+sn1;
+ rm= rectmaskofs+sn1;
ap= apofs+sn1;
x= sn2-sn1;
zverg-= zspan->polygon_offset;
while(x>=0) {
- if( (int)zverg < *rz) {
-// int i= zvlnr & 3;
-
- apn= ap;
- while(apn) {
- if(apn->p[0]==0) {apn->obi[0]= obi; apn->p[0]= zvlnr; apn->z[0]= zverg; apn->mask[0]= mask; break; }
- if(apn->p[0]==zvlnr && apn->obi[0]==obi) {apn->mask[0]|= mask; break; }
- if(apn->p[1]==0) {apn->obi[1]= obi; apn->p[1]= zvlnr; apn->z[1]= zverg; apn->mask[1]= mask; break; }
- if(apn->p[1]==zvlnr && apn->obi[1]==obi) {apn->mask[1]|= mask; break; }
- if(apn->p[2]==0) {apn->obi[2]= obi; apn->p[2]= zvlnr; apn->z[2]= zverg; apn->mask[2]= mask; break; }
- if(apn->p[2]==zvlnr && apn->obi[2]==obi) {apn->mask[2]|= mask; break; }
- if(apn->p[3]==0) {apn->obi[3]= obi; apn->p[3]= zvlnr; apn->z[3]= zverg; apn->mask[3]= mask; break; }
- if(apn->p[3]==zvlnr && apn->obi[3]==obi) {apn->mask[3]|= mask; break; }
-// if(apn->p[i]==0) {apn->obi[i]= obi; apn->p[i]= zvlnr; apn->z[i]= zverg; apn->mask[i]= mask; break; }
-// if(apn->p[i]==zvlnr && apn->obi[i]==obi) {apn->mask[i]|= mask; break; }
- if(apn->next==NULL) apn->next= addpsA(zspan);
- apn= apn->next;
- }
+ intzverg= (int)CLAMPIS(zverg, INT_MIN, INT_MAX);
+
+ if( intzverg < *rz) {
+ if(!zspan->rectmask || intzverg > *rm) {
+
+ apn= ap;
+ while(apn) {
+ if(apn->p[0]==0) {apn->obi[0]= obi; apn->p[0]= zvlnr; apn->z[0]= intzverg; apn->mask[0]= mask; break; }
+ if(apn->p[0]==zvlnr && apn->obi[0]==obi) {apn->mask[0]|= mask; break; }
+ if(apn->p[1]==0) {apn->obi[1]= obi; apn->p[1]= zvlnr; apn->z[1]= intzverg; apn->mask[1]= mask; break; }
+ if(apn->p[1]==zvlnr && apn->obi[1]==obi) {apn->mask[1]|= mask; break; }
+ if(apn->p[2]==0) {apn->obi[2]= obi; apn->p[2]= zvlnr; apn->z[2]= intzverg; apn->mask[2]= mask; break; }
+ if(apn->p[2]==zvlnr && apn->obi[2]==obi) {apn->mask[2]|= mask; break; }
+ if(apn->p[3]==0) {apn->obi[3]= obi; apn->p[3]= zvlnr; apn->z[3]= intzverg; apn->mask[3]= mask; break; }
+ if(apn->p[3]==zvlnr && apn->obi[3]==obi) {apn->mask[3]|= mask; break; }
+ if(apn->next==NULL) apn->next= addpsA(zspan);
+ apn= apn->next;
+ }
+ }
}
zverg+= zxd;
rz++;
+ rm++;
ap++;
x--;
}
@@ -413,6 +418,7 @@ static void zbuffillAc4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v2,
zy0-=zyd;
rectzofs-= rectx;
+ rectmaskofs-= rectx;
apofs-= rectx;
}
}
@@ -422,7 +428,7 @@ static void zbuffillAc4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v2,
static void zbuflineAc(ZSpan *zspan, int obi, int zvlnr, float *vec1, float *vec2)
{
APixstr *ap, *apn;
- int *rectz;
+ int *rectz, *rectmask;
int start, end, x, y, oldx, oldy, ofs;
int dz, vergz, mask, maxtest=0;
float dx, dy;
@@ -459,37 +465,40 @@ static void zbuflineAc(ZSpan *zspan, int obi, int zvlnr, float *vec1, float *vec
if(vergz>0x50000000 && dz>0) maxtest= 1; // prevent overflow
rectz= (int *)(zspan->arectz+zspan->rectx*(oldy) +start);
+ rectmask= (int *)(zspan->rectmask+zspan->rectx*(oldy) +start);
ap= (zspan->apixbuf+ zspan->rectx*(oldy) +start);
if(dy<0) ofs= -zspan->rectx;
else ofs= zspan->rectx;
- for(x= start; x<=end; x++, rectz++, ap++) {
+ for(x= start; x<=end; x++, rectz++, rectmask++, ap++) {
y= floor(v1[1]);
if(y!=oldy) {
oldy= y;
rectz+= ofs;
+ rectmask+= ofs;
ap+= ofs;
}
if(x>=0 && y>=0 && y<zspan->recty) {
if(vergz<*rectz) {
-
- apn= ap;
- while(apn) { /* loop unrolled */
- if(apn->p[0]==0) {apn->obi[0]= obi; apn->p[0]= zvlnr; apn->z[0]= vergz; apn->mask[0]= mask; break; }
- if(apn->p[0]==zvlnr && apn->obi[0]==obi) {apn->mask[0]|= mask; break; }
- if(apn->p[1]==0) {apn->obi[1]= obi; apn->p[1]= zvlnr; apn->z[1]= vergz; apn->mask[1]= mask; break; }
- if(apn->p[1]==zvlnr && apn->obi[1]==obi) {apn->mask[1]|= mask; break; }
- if(apn->p[2]==0) {apn->obi[2]= obi; apn->p[2]= zvlnr; apn->z[2]= vergz; apn->mask[2]= mask; break; }
- if(apn->p[2]==zvlnr && apn->obi[2]==obi) {apn->mask[2]|= mask; break; }
- if(apn->p[3]==0) {apn->obi[3]= obi; apn->p[3]= zvlnr; apn->z[3]= vergz; apn->mask[3]= mask; break; }
- if(apn->p[3]==zvlnr && apn->obi[3]==obi) {apn->mask[3]|= mask; break; }
- if(apn->next==0) apn->next= addpsA(zspan);
- apn= apn->next;
- }
+ if(!zspan->rectmask || vergz>*rectmask) {
+ apn= ap;
+ while(apn) { /* loop unrolled */
+ if(apn->p[0]==0) {apn->obi[0]= obi; apn->p[0]= zvlnr; apn->z[0]= vergz; apn->mask[0]= mask; break; }
+ if(apn->p[0]==zvlnr && apn->obi[0]==obi) {apn->mask[0]|= mask; break; }
+ if(apn->p[1]==0) {apn->obi[1]= obi; apn->p[1]= zvlnr; apn->z[1]= vergz; apn->mask[1]= mask; break; }
+ if(apn->p[1]==zvlnr && apn->obi[1]==obi) {apn->mask[1]|= mask; break; }
+ if(apn->p[2]==0) {apn->obi[2]= obi; apn->p[2]= zvlnr; apn->z[2]= vergz; apn->mask[2]= mask; break; }
+ if(apn->p[2]==zvlnr && apn->obi[2]==obi) {apn->mask[2]|= mask; break; }
+ if(apn->p[3]==0) {apn->obi[3]= obi; apn->p[3]= zvlnr; apn->z[3]= vergz; apn->mask[3]= mask; break; }
+ if(apn->p[3]==zvlnr && apn->obi[3]==obi) {apn->mask[3]|= mask; break; }
+ if(apn->next==0) apn->next= addpsA(zspan);
+ apn= apn->next;
+ }
+ }
}
}
@@ -527,37 +536,40 @@ static void zbuflineAc(ZSpan *zspan, int obi, int zvlnr, float *vec1, float *vec
if(vergz>0x50000000 && dz>0) maxtest= 1; // prevent overflow
rectz= (int *)( zspan->arectz+ (start)*zspan->rectx+ oldx );
+ rectmask= (int *)( zspan->rectmask+ (start)*zspan->rectx+ oldx );
ap= (zspan->apixbuf+ zspan->rectx*(start) +oldx);
if(dx<0) ofs= -1;
else ofs= 1;
- for(y= start; y<=end; y++, rectz+=zspan->rectx, ap+=zspan->rectx) {
+ for(y= start; y<=end; y++, rectz+=zspan->rectx, rectmask+=zspan->rectx, ap+=zspan->rectx) {
x= floor(v1[0]);
if(x!=oldx) {
oldx= x;
rectz+= ofs;
+ rectmask+= ofs;
ap+= ofs;
}
if(x>=0 && y>=0 && x<zspan->rectx) {
if(vergz<*rectz) {
-
- apn= ap;
- while(apn) { /* loop unrolled */
- if(apn->p[0]==0) {apn->p[0]= zvlnr; apn->z[0]= vergz; apn->mask[0]= mask; break; }
- if(apn->p[0]==zvlnr) {apn->mask[0]|= mask; break; }
- if(apn->p[1]==0) {apn->p[1]= zvlnr; apn->z[1]= vergz; apn->mask[1]= mask; break; }
- if(apn->p[1]==zvlnr) {apn->mask[1]|= mask; break; }
- if(apn->p[2]==0) {apn->p[2]= zvlnr; apn->z[2]= vergz; apn->mask[2]= mask; break; }
- if(apn->p[2]==zvlnr) {apn->mask[2]|= mask; break; }
- if(apn->p[3]==0) {apn->p[3]= zvlnr; apn->z[3]= vergz; apn->mask[3]= mask; break; }
- if(apn->p[3]==zvlnr) {apn->mask[3]|= mask; break; }
- if(apn->next==0) apn->next= addpsA(zspan);
- apn= apn->next;
- }
-
+ if(!zspan->rectmask || vergz>*rectmask) {
+
+ apn= ap;
+ while(apn) { /* loop unrolled */
+ if(apn->p[0]==0) {apn->obi[0]= obi; apn->p[0]= zvlnr; apn->z[0]= vergz; apn->mask[0]= mask; break; }
+ if(apn->p[0]==zvlnr) {apn->mask[0]|= mask; break; }
+ if(apn->p[1]==0) {apn->obi[1]= obi; apn->p[1]= zvlnr; apn->z[1]= vergz; apn->mask[1]= mask; break; }
+ if(apn->p[1]==zvlnr) {apn->mask[1]|= mask; break; }
+ if(apn->p[2]==0) {apn->obi[2]= obi; apn->p[2]= zvlnr; apn->z[2]= vergz; apn->mask[2]= mask; break; }
+ if(apn->p[2]==zvlnr) {apn->mask[2]|= mask; break; }
+ if(apn->p[3]==0) {apn->obi[3]= obi; apn->p[3]= zvlnr; apn->z[3]= vergz; apn->mask[3]= mask; break; }
+ if(apn->p[3]==zvlnr) {apn->mask[3]|= mask; break; }
+ if(apn->next==0) apn->next= addpsA(zspan);
+ apn= apn->next;
+ }
+ }
}
}
@@ -572,7 +584,7 @@ static void zbuflineAc(ZSpan *zspan, int obi, int zvlnr, float *vec1, float *vec
static void zbufline(ZSpan *zspan, int obi, int zvlnr, float *vec1, float *vec2)
{
- int *rectz, *rectp, *recto;
+ int *rectz, *rectp, *recto, *rectmask;
int start, end, x, y, oldx, oldy, ofs;
int dz, vergz, maxtest= 0;
float dx, dy;
@@ -608,11 +620,12 @@ static void zbufline(ZSpan *zspan, int obi, int zvlnr, float *vec1, float *vec2)
rectz= zspan->rectz + oldy*zspan->rectx+ start;
rectp= zspan->rectp + oldy*zspan->rectx+ start;
recto= zspan->recto + oldy*zspan->rectx+ start;
+ rectmask= zspan->rectmask + oldy*zspan->rectx+ start;
if(dy<0) ofs= -zspan->rectx;
else ofs= zspan->rectx;
- for(x= start; x<=end; x++, rectz++, rectp++, recto++) {
+ for(x= start; x<=end; x++, rectz++, rectp++, recto++, rectmask++) {
y= floor(v1[1]);
if(y!=oldy) {
@@ -620,13 +633,16 @@ static void zbufline(ZSpan *zspan, int obi, int zvlnr, float *vec1, float *vec2)
rectz+= ofs;
rectp+= ofs;
recto+= ofs;
+ rectmask+= ofs;
}
if(x>=0 && y>=0 && y<zspan->recty) {
if(vergz<*rectz) {
- *recto= obi;
- *rectz= vergz;
- *rectp= zvlnr;
+ if(!zspan->rectmask || vergz>*rectmask) {
+ *recto= obi;
+ *rectz= vergz;
+ *rectp= zvlnr;
+ }
}
}
@@ -663,11 +679,12 @@ static void zbufline(ZSpan *zspan, int obi, int zvlnr, float *vec1, float *vec2)
rectz= zspan->rectz + start*zspan->rectx+ oldx;
rectp= zspan->rectp + start*zspan->rectx+ oldx;
recto= zspan->recto + start*zspan->rectx+ oldx;
+ rectmask= zspan->rectmask + start*zspan->rectx+ oldx;
if(dx<0) ofs= -1;
else ofs= 1;
- for(y= start; y<=end; y++, rectz+=zspan->rectx, rectp+=zspan->rectx, recto+=zspan->rectx) {
+ for(y= start; y<=end; y++, rectz+=zspan->rectx, rectp+=zspan->rectx, recto+=zspan->rectx, rectmask+=zspan->rectx) {
x= floor(v1[0]);
if(x!=oldx) {
@@ -675,13 +692,16 @@ static void zbufline(ZSpan *zspan, int obi, int zvlnr, float *vec1, float *vec2)
rectz+= ofs;
rectp+= ofs;
recto+= ofs;
+ rectmask+= ofs;
}
if(x>=0 && y>=0 && x<zspan->rectx) {
if(vergz<*rectz) {
- *rectz= vergz;
- *rectp= zvlnr;
- *recto= obi;
+ if(!zspan->rectmask || vergz>*rectmask) {
+ *rectz= vergz;
+ *rectp= zvlnr;
+ *recto= obi;
+ }
}
}
@@ -1022,6 +1042,7 @@ static void zbuffillGLinv4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v
float *span1, *span2;
int *rectoofs, *ro;
int *rectpofs, *rp;
+ int *rectmaskofs, *rm;
int *rz, x, y;
int sn1, sn2, rectx, *rectzofs, my0, my2;
@@ -1072,6 +1093,7 @@ static void zbuffillGLinv4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v
rectzofs= (zspan->rectz+rectx*my2);
rectpofs= (zspan->rectp+rectx*my2);
rectoofs= (zspan->recto+rectx*my2);
+ rectmaskofs= (zspan->rectmask+rectx*my2);
/* correct span */
sn1= (my0 + my2)/2;
@@ -1094,22 +1116,30 @@ static void zbuffillGLinv4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v
if(sn1<0) sn1= 0;
if(sn2>=sn1) {
+ int intzverg;
+
zverg= (double)sn1*zxd + zy0;
rz= rectzofs+sn1;
rp= rectpofs+sn1;
ro= rectoofs+sn1;
+ rm= rectmaskofs+sn1;
x= sn2-sn1;
while(x>=0) {
- if( (int)zverg > *rz || *rz==0x7FFFFFFF) {
- *ro= obi;
- *rz= (int)zverg;
- *rp= zvlnr;
+ intzverg= (int)CLAMPIS(zverg, INT_MIN, INT_MAX);
+
+ if( intzverg > *rz || *rz==0x7FFFFFFF) {
+ if(!zspan->rectmask || intzverg > *rm) {
+ *ro= obi;
+ *rz= intzverg;
+ *rp= zvlnr;
+ }
}
zverg+= zxd;
rz++;
rp++;
ro++;
+ rm++;
x--;
}
}
@@ -1118,6 +1148,7 @@ static void zbuffillGLinv4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v
rectzofs-= rectx;
rectpofs-= rectx;
rectoofs-= rectx;
+ rectmaskofs-= rectx;
}
}
@@ -1131,6 +1162,7 @@ static void zbuffillGL4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v2,
float *span1, *span2;
int *rectoofs, *ro;
int *rectpofs, *rp;
+ int *rectmaskofs, *rm;
int *rz, x, y;
int sn1, sn2, rectx, *rectzofs, my0, my2;
@@ -1181,6 +1213,7 @@ static void zbuffillGL4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v2,
rectzofs= (zspan->rectz+rectx*my2);
rectpofs= (zspan->rectp+rectx*my2);
rectoofs= (zspan->recto+rectx*my2);
+ rectmaskofs= (zspan->rectmask+rectx*my2);
/* correct span */
sn1= (my0 + my2)/2;
@@ -1203,22 +1236,30 @@ static void zbuffillGL4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v2,
if(sn1<0) sn1= 0;
if(sn2>=sn1) {
+ int intzverg;
+
zverg= (double)sn1*zxd + zy0;
rz= rectzofs+sn1;
rp= rectpofs+sn1;
ro= rectoofs+sn1;
+ rm= rectmaskofs+sn1;
x= sn2-sn1;
while(x>=0) {
- if( (int)zverg < *rz) {
- *rz= (int)zverg;
- *rp= zvlnr;
- *ro= obi;
+ intzverg= (int)CLAMPIS(zverg, INT_MIN, INT_MAX);
+
+ if(intzverg < *rz) {
+ if(!zspan->rectmask || intzverg > *rm) {
+ *rz= intzverg;
+ *rp= zvlnr;
+ *ro= obi;
+ }
}
zverg+= zxd;
rz++;
rp++;
ro++;
+ rm++;
x--;
}
}
@@ -1227,6 +1268,7 @@ static void zbuffillGL4(ZSpan *zspan, int obi, int zvlnr, float *v1, float *v2,
rectzofs-= rectx;
rectpofs-= rectx;
rectoofs-= rectx;
+ rectmaskofs-= rectx;
}
}
@@ -1326,7 +1368,8 @@ static void zbuffillGL_onlyZ(ZSpan *zspan, int obi, int zvlnr, float *v1, float
x= sn2-sn1;
while(x>=0) {
- int zvergi= (int)zverg;
+ int zvergi= (int)CLAMPIS(zverg, INT_MIN, INT_MAX);
+
/* option: maintain two depth values, closest and 2nd closest */
if(zvergi < *rz) {
if(rectzofs1) *rz1= *rz;
@@ -1922,10 +1965,82 @@ void zbufclip4(ZSpan *zspan, int obi, int zvlnr, float *f1, float *f2, float *f3
zspan->zbuffunc(zspan, obi, zvlnr, vez, vez+4, vez+8, vez+12);
}
+/* ************** ZMASK ******************************** */
+
+#define EXTEND_PIXEL(a) if(temprectp[a]) {z+= rectz[a]; tot++;}
+
+/* changes the zbuffer to be ready for z-masking: applies an extend-filter, and then clears */
+static void zmask_rect(int *rectz, int *rectp, int xs, int ys, int neg)
+{
+ int len=0, x, y;
+ int *temprectp;
+ int row1, row2, row3, *curp, *curz;
+
+ temprectp= MEM_dupallocN(rectp);
+
+ /* extend: if pixel is not filled in, we check surrounding pixels and average z value */
+
+ for(y=1; y<=ys; y++) {
+ /* setup row indices */
+ row1= (y-2)*xs;
+ row2= row1 + xs;
+ row3= row2 + xs;
+ if(y==1)
+ row1= row2;
+ else if(y==ys)
+ row3= row2;
+
+ curp= rectp + (y-1)*xs;
+ curz= rectz + (y-1)*xs;
+
+ for(x=0; x<xs; x++, curp++, curz++) {
+ if(curp[0]==0) {
+ int tot= 0;
+ float z= 0.0f;
+
+ EXTEND_PIXEL(row1);
+ EXTEND_PIXEL(row2);
+ EXTEND_PIXEL(row3);
+ EXTEND_PIXEL(row1 + 1);
+ EXTEND_PIXEL(row3 + 1);
+ if(x!=xs-1) {
+ EXTEND_PIXEL(row1 + 2);
+ EXTEND_PIXEL(row2 + 2);
+ EXTEND_PIXEL(row3 + 2);
+ }
+ if(tot) {
+ len++;
+ curz[0]= (int)(z/(float)tot);
+ curp[0]= -1; /* env */
+ }
+ }
+
+ if(x!=0) {
+ row1++; row2++; row3++;
+ }
+ }
+ }
+
+ MEM_freeN(temprectp);
+
+ if(neg); /* z values for negative are already correct */
+ else {
+ /* clear not filled z values */
+ for(len= xs*ys -1; len>=0; len--) {
+ if(rectp[len]==0) {
+ rectz[len] = -0x7FFFFFFF;
+ rectp[len]= -1; /* env code */
+ }
+ }
+ }
+}
+
+
+
/* ***************** ZBUFFER MAIN ROUTINES **************** */
-void zbuffer_solid(RenderPart *pa, unsigned int lay, short layflag, void(*fillfunc)(RenderPart*, ZSpan*, int, void*), void *data)
+void zbuffer_solid(RenderPart *pa, RenderLayer *rl, void(*fillfunc)(RenderPart*, ZSpan*, int, void*), void *data)
{
ZbufProjectCache cache[ZBUF_PROJECT_CACHE_SIZE];
ZSpan zspans[16], *zspan; /* 16 = RE_MAX_OSA */
@@ -1935,9 +2050,12 @@ void zbuffer_solid(RenderPart *pa, unsigned int lay, short layflag, void(*fillfu
ObjectInstanceRen *obi;
ObjectRen *obr;
float winmat[4][4], bounds[4], ho1[4], ho2[4], ho3[4], ho4[4]={0};
+ unsigned int lay= rl->lay, lay_zmask= rl->lay_zmask;
int i, v, zvlnr, zsample, samples, c1, c2, c3, c4=0;
- short nofill=0, env=0, wire=0, all_z= layflag & SCE_LAY_ALL_Z;
-
+ short nofill=0, env=0, wire=0, zmaskpass=0;
+ short all_z= (rl->layflag & SCE_LAY_ALL_Z) && !(rl->layflag & SCE_LAY_ZMASK);
+ short neg_zmask= (rl->layflag & SCE_LAY_ZMASK) && (rl->layflag & SCE_LAY_NEG_ZMASK);
+
samples= (R.osa? R.osa: 1);
samples= MIN2(4, samples-pa->sample);
@@ -1969,9 +2087,13 @@ void zbuffer_solid(RenderPart *pa, unsigned int lay, short layflag, void(*fillfu
/* the buffers */
if(zsample == samples-1) {
- zspan->rectz= pa->rectz;
zspan->rectp= pa->rectp;
zspan->recto= pa->recto;
+
+ if(neg_zmask)
+ zspan->rectz= pa->rectmask;
+ else
+ zspan->rectz= pa->rectz;
}
else {
zspan->recto= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "recto");
@@ -1982,104 +2104,153 @@ void zbuffer_solid(RenderPart *pa, unsigned int lay, short layflag, void(*fillfu
fillrect(zspan->rectz, pa->rectx, pa->recty, 0x7FFFFFFF);
fillrect(zspan->rectp, pa->rectx, pa->recty, 0);
fillrect(zspan->recto, pa->rectx, pa->recty, 0);
-
- /* filling methods */
- zspan->zbuffunc= zbuffillGL4;
- zspan->zbuflinefunc= zbufline;
}
- for(i=0, obi=R.instancetable.first; obi; i++, obi=obi->next) {
- obr= obi->obr;
+ /* in case zmask we fill Z for objects in lay_zmask first, then clear Z, and then do normal zbuffering */
+ if(rl->layflag & SCE_LAY_ZMASK)
+ zmaskpass= 1;
+
+ for(; zmaskpass >=0; zmaskpass--) {
+ ma= NULL;
- if(obi->flag & R_TRANSFORMED)
- zbuf_make_winmat(&R, obi->mat, winmat);
- else
- zbuf_make_winmat(&R, NULL, winmat);
+ /* filling methods */
+ for(zsample=0; zsample<samples; zsample++) {
+ zspan= &zspans[zsample];
- zbuf_project_cache_clear(cache, obr->totvert);
+ if(zmaskpass && neg_zmask)
+ zspan->zbuffunc= zbuffillGLinv4;
+ else
+ zspan->zbuffunc= zbuffillGL4;
+ zspan->zbuflinefunc= zbufline;
+ }
- for(v=0; v<obr->totvlak; v++) {
- if((v & 255)==0) vlr= obr->vlaknodes[v>>8].vlak;
- else vlr++;
+ /* regular zbuffering loop, does all sample buffers */
+ for(i=0, obi=R.instancetable.first; obi; i++, obi=obi->next) {
+ obr= obi->obr;
- /* three cases, visible for render, only z values and nothing */
- if(vlr->lay & lay) {
- if(vlr->mat!=ma) {
- ma= vlr->mat;
- nofill= ma->mode & (MA_ZTRA|MA_ONLYCAST);
- env= (ma->mode & MA_ENV);
- wire= (ma->mode & MA_WIRE);
-
- for(zsample=0; zsample<samples; zsample++) {
- if(ma->mode & MA_ZINV) zspans[zsample].zbuffunc= zbuffillGLinv4;
- else zspans[zsample].zbuffunc= zbuffillGL4;
- }
- }
- }
- else if(all_z) {
- env= 1;
- nofill= 0;
- ma= NULL;
- }
- else {
- nofill= 1;
- ma= NULL; /* otherwise nofill can hang */
+ /* continue happens in 2 different ways... zmaskpass only does lay_zmask stuff */
+ if(zmaskpass) {
+ if((obi->lay & lay_zmask)==0)
+ continue;
}
+ else if(!all_z && !(obi->lay & (lay|lay_zmask)))
+ continue;
+
+ if(obi->flag & R_TRANSFORMED)
+ zbuf_make_winmat(&R, obi->mat, winmat);
+ else
+ zbuf_make_winmat(&R, NULL, winmat);
- if(!(vlr->flag & R_HIDDEN) && nofill==0) {
- unsigned short partclip;
-
- v1= vlr->v1;
- v2= vlr->v2;
- v3= vlr->v3;
- v4= vlr->v4;
-
- c1= zbuf_part_project(cache, v1->index, winmat, bounds, v1->co, ho1);
- c2= zbuf_part_project(cache, v2->index, winmat, bounds, v2->co, ho2);
- c3= zbuf_part_project(cache, v3->index, winmat, bounds, v3->co, ho3);
-
- /* partclipping doesn't need viewplane clipping */
- partclip= c1 & c2 & c3;
- if(v4) {
- c4= zbuf_part_project(cache, v4->index, winmat, bounds, v4->co, ho4);
- partclip &= c4;
+ if(clip_render_object(obi->obr->boundbox, bounds, winmat))
+ continue;
+
+ zbuf_project_cache_clear(cache, obr->totvert);
+
+ for(v=0; v<obr->totvlak; v++) {
+ if((v & 255)==0) vlr= obr->vlaknodes[v>>8].vlak;
+ else vlr++;
+
+ /* the cases: visible for render, only z values, zmask, nothing */
+ if(obi->lay & lay) {
+ if(vlr->mat!=ma) {
+ ma= vlr->mat;
+ nofill= ma->mode & (MA_ZTRA|MA_ONLYCAST);
+ env= (ma->mode & MA_ENV);
+ wire= (ma->mode & MA_WIRE);
+
+ for(zsample=0; zsample<samples; zsample++) {
+ if(ma->mode & MA_ZINV || (zmaskpass && neg_zmask))
+ zspans[zsample].zbuffunc= zbuffillGLinv4;
+ else
+ zspans[zsample].zbuffunc= zbuffillGL4;
+ }
+ }
+ }
+ else if(all_z || (obi->lay & lay_zmask)) {
+ env= 1;
+ nofill= 0;
+ ma= NULL;
+ }
+ else {
+ nofill= 1;
+ ma= NULL; /* otherwise nofill can hang */
}
- if(partclip==0) {
+ if(!(vlr->flag & R_HIDDEN) && nofill==0) {
+ unsigned short partclip;
- if(env) zvlnr= -1;
- else zvlnr= v+1;
+ v1= vlr->v1;
+ v2= vlr->v2;
+ v3= vlr->v3;
+ v4= vlr->v4;
+
+ c1= zbuf_part_project(cache, v1->index, winmat, bounds, v1->co, ho1);
+ c2= zbuf_part_project(cache, v2->index, winmat, bounds, v2->co, ho2);
+ c3= zbuf_part_project(cache, v3->index, winmat, bounds, v3->co, ho3);
+
+ /* partclipping doesn't need viewplane clipping */
+ partclip= c1 & c2 & c3;
+ if(v4) {
+ c4= zbuf_part_project(cache, v4->index, winmat, bounds, v4->co, ho4);
+ partclip &= c4;
+ }
- c1= testclip(ho1);
- c2= testclip(ho2);
- c3= testclip(ho3);
- if(v4)
- c4= testclip(ho4);
+ if(partclip==0) {
+
+ if(env) zvlnr= -1;
+ else zvlnr= v+1;
- for(zsample=0; zsample<samples; zsample++) {
- zspan= &zspans[zsample];
+ c1= testclip(ho1);
+ c2= testclip(ho2);
+ c3= testclip(ho3);
+ if(v4)
+ c4= testclip(ho4);
- if(wire) {
- if(v4)
- zbufclipwire(zspan, i, zvlnr, vlr->ec, ho1, ho2, ho3, ho4, c1, c2, c3, c4);
- else
- zbufclipwire(zspan, i, zvlnr, vlr->ec, ho1, ho2, ho3, 0, c1, c2, c3, 0);
- }
- else {
- /* strands allow to be filled in as quad */
- if(v4 && (vlr->flag & R_STRAND)) {
- zbufclip4(zspan, i, zvlnr, ho1, ho2, ho3, ho4, c1, c2, c3, c4);
+ for(zsample=0; zsample<samples; zsample++) {
+ zspan= &zspans[zsample];
+
+ if(wire) {
+ if(v4)
+ zbufclipwire(zspan, i, zvlnr, vlr->ec, ho1, ho2, ho3, ho4, c1, c2, c3, c4);
+ else
+ zbufclipwire(zspan, i, zvlnr, vlr->ec, ho1, ho2, ho3, 0, c1, c2, c3, 0);
}
else {
- zbufclip(zspan, i, zvlnr, ho1, ho2, ho3, c1, c2, c3);
- if(v4)
- zbufclip(zspan, i, zvlnr+RE_QUAD_OFFS, ho1, ho3, ho4, c1, c3, c4);
+ /* strands allow to be filled in as quad */
+ if(v4 && (vlr->flag & R_STRAND)) {
+ zbufclip4(zspan, i, zvlnr, ho1, ho2, ho3, ho4, c1, c2, c3, c4);
+ }
+ else {
+ zbufclip(zspan, i, zvlnr, ho1, ho2, ho3, c1, c2, c3);
+ if(v4)
+ zbufclip(zspan, i, (env)? zvlnr: zvlnr+RE_QUAD_OFFS, ho1, ho3, ho4, c1, c3, c4);
+ }
}
}
}
}
}
}
+
+ /* clear all z to close value, so it works as mask for next passes (ztra+strand) */
+ if(zmaskpass) {
+ for(zsample=0; zsample<samples; zsample++) {
+ zspan= &zspans[zsample];
+
+ if(neg_zmask) {
+ zspan->rectmask= zspan->rectz;
+ if(zsample == samples-1)
+ zspan->rectz= pa->rectz;
+ else
+ zspan->rectz= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectz");
+ fillrect(zspan->rectz, pa->rectx, pa->recty, 0x7FFFFFFF);
+
+ zmask_rect(zspan->rectmask, zspan->rectp, pa->rectx, pa->recty, 1);
+ }
+ else
+ zmask_rect(zspan->rectz, zspan->rectp, pa->rectx, pa->recty, 0);
+ }
+ }
}
for(zsample=0; zsample<samples; zsample++) {
@@ -2092,6 +2263,8 @@ void zbuffer_solid(RenderPart *pa, unsigned int lay, short layflag, void(*fillfu
MEM_freeN(zspan->rectz);
MEM_freeN(zspan->rectp);
MEM_freeN(zspan->recto);
+ if(zspan->rectmask)
+ MEM_freeN(zspan->rectmask);
}
zbuf_free_span(zspan);
@@ -2115,7 +2288,7 @@ static int hashlist_projectvert(float *v1, float winmat[][4], float *hoco)
return 0;
}
- buck= &bucket[ (((long)v1)/16) & 255 ];
+ buck= &bucket[ (((intptr_t)v1)/16) & 255 ];
if(buck->vert==v1) {
QUATCOPY(hoco, buck->hoco);
return buck->clip;
@@ -2191,7 +2364,7 @@ void RE_zbufferall_radio(struct RadView *vw, RNode **rg_elem, int rg_totelem, Re
else { /* radio render */
ObjectRen *obr;
VlakRen *vlr=NULL;
- RadFace *rf;
+ RadFace **radface, *rf;
int totface=0;
/* note: radio render doesn't support duplis */
@@ -2201,8 +2374,8 @@ void RE_zbufferall_radio(struct RadView *vw, RNode **rg_elem, int rg_totelem, Re
for(a=0; a<obr->totvlak; a++) {
if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak; else vlr++;
- if(vlr->radface) {
- rf= vlr->radface;
+ if((radface=RE_vlakren_get_radface(obr, vlr, 0)) && *radface) {
+ rf= *radface;
if( (rf->flag & RAD_SHOOT)==0 ) { /* no shootelement */
if( rf->flag & RAD_TWOSIDED) zvlnr= totface;
@@ -2243,10 +2416,11 @@ void zbuffer_shadow(Render *re, float winmat[][4], LampRen *lar, int *rectz, int
StrandSegment sseg;
StrandRen *strand= NULL;
StrandVert *svert;
+ StrandBound *sbound;
float obwinmat[4][4], ho1[4], ho2[4], ho3[4], ho4[4];
- int a, b, i, c1, c2, c3, c4, ok=1, lay= -1;
+ int a, b, c, i, c1, c2, c3, c4, ok=1, lay= -1;
- if(lar->mode & LA_LAYER) lay= lar->lay;
+ if(lar->mode & (LA_LAYER|LA_LAYER_SHADOW)) lay= lar->lay;
/* 1.0f for clipping in clippyra()... bad stuff actually */
zbuf_alloc_span(&zspan, size, size, 1.0f);
@@ -2272,12 +2446,17 @@ void zbuffer_shadow(Render *re, float winmat[][4], LampRen *lar, int *rectz, int
if(obr->ob==re->excludeob)
continue;
+ else if(!(obi->lay & lay))
+ continue;
if(obi->flag & R_TRANSFORMED)
Mat4MulMat4(obwinmat, obi->mat, winmat);
else
Mat4CpyMat4(obwinmat, winmat);
+ if(clip_render_object(obi->obr->boundbox, NULL, obwinmat))
+ continue;
+
zbuf_project_cache_clear(cache, obr->totvert);
/* faces */
@@ -2293,7 +2472,7 @@ void zbuffer_shadow(Render *re, float winmat[][4], LampRen *lar, int *rectz, int
if((ma->mode & MA_SHADBUF)==0) ok= 0;
}
- if(ok && (vlr->lay & lay) && !(vlr->flag & R_HIDDEN)) {
+ if(ok && (obi->lay & lay) && !(vlr->flag & R_HIDDEN)) {
c1= zbuf_shadow_project(cache, vlr->v1->index, obwinmat, vlr->v1->co, ho1);
c2= zbuf_shadow_project(cache, vlr->v2->index, obwinmat, vlr->v2->co, ho2);
c3= zbuf_shadow_project(cache, vlr->v3->index, obwinmat, vlr->v3->co, ho3);
@@ -2321,45 +2500,54 @@ void zbuffer_shadow(Render *re, float winmat[][4], LampRen *lar, int *rectz, int
}
/* strands */
- for(a=0; a<obr->totstrand; a++) {
- if((a & 255)==0) strand= obr->strandnodes[a>>8].strand;
- else strand++;
-
- sseg.obi= obi;
- sseg.buffer= strand->buffer;
- sseg.sqadaptcos= sseg.buffer->adaptcos;
- sseg.sqadaptcos *= sseg.sqadaptcos;
- sseg.strand= strand;
- svert= strand->vert;
+ if(obr->strandbuf) {
+ /* for each bounding box containing a number of strands */
+ sbound= obr->strandbuf->bound;
+ for(c=0; c<obr->strandbuf->totbound; c++, sbound++) {
+ if(clip_render_object(sbound->boundbox, NULL, obwinmat))
+ continue;
+
+ /* for each strand in this bounding box */
+ for(a=sbound->start; a<sbound->end; a++) {
+ strand= RE_findOrAddStrand(obr, a);
+
+ sseg.obi= obi;
+ sseg.buffer= strand->buffer;
+ sseg.sqadaptcos= sseg.buffer->adaptcos;
+ sseg.sqadaptcos *= sseg.sqadaptcos;
+ sseg.strand= strand;
+ svert= strand->vert;
+
+ /* note, these conditions are copied in shadowbuf_autoclip() */
+ if(sseg.buffer->ma!= ma) {
+ ma= sseg.buffer->ma;
+ ok= 1;
+ if((ma->mode & MA_SHADBUF)==0) ok= 0;
+ }
- /* note, these conditions are copied in shadowbuf_autoclip() */
- if(sseg.buffer->ma!= ma) {
- ma= sseg.buffer->ma;
- ok= 1;
- if((ma->mode & MA_SHADBUF)==0) ok= 0;
- }
+ if(ok && (sseg.buffer->lay & lay)) {
+ zbuf_project_cache_clear(cache, strand->totvert);
- if(ok && (sseg.buffer->lay & lay)) {
- zbuf_project_cache_clear(cache, strand->totvert);
+ for(b=0; b<strand->totvert-1; b++, svert++) {
+ sseg.v[0]= (b > 0)? (svert-1): svert;
+ sseg.v[1]= svert;
+ sseg.v[2]= svert+1;
+ sseg.v[3]= (b < strand->totvert-2)? svert+2: svert+1;
- for(b=0; b<strand->totvert-1; b++, svert++) {
- sseg.v[0]= (b > 0)? (svert-1): svert;
- sseg.v[1]= svert;
- sseg.v[2]= svert+1;
- sseg.v[3]= (b < strand->totvert-2)? svert+2: svert+1;
+ c1= zbuf_shadow_project(cache, sseg.v[0]-strand->vert, obwinmat, sseg.v[0]->co, ho1);
+ c2= zbuf_shadow_project(cache, sseg.v[1]-strand->vert, obwinmat, sseg.v[1]->co, ho2);
+ c3= zbuf_shadow_project(cache, sseg.v[2]-strand->vert, obwinmat, sseg.v[2]->co, ho3);
+ c4= zbuf_shadow_project(cache, sseg.v[3]-strand->vert, obwinmat, sseg.v[3]->co, ho4);
- c1= zbuf_shadow_project(cache, sseg.v[0]-strand->vert, obwinmat, sseg.v[0]->co, ho1);
- c2= zbuf_shadow_project(cache, sseg.v[1]-strand->vert, obwinmat, sseg.v[1]->co, ho2);
- c3= zbuf_shadow_project(cache, sseg.v[2]-strand->vert, obwinmat, sseg.v[2]->co, ho3);
- c4= zbuf_shadow_project(cache, sseg.v[3]-strand->vert, obwinmat, sseg.v[3]->co, ho4);
+ if(!(c1 & c2 & c3 & c4))
+ render_strand_segment(re, winmat, NULL, &zspan, 1, &sseg);
+ }
+ }
- if(!(c1 & c2 & c3 & c4))
- render_strand_segment(NULL, winmat, NULL, &zspan, &sseg);
+ if((a & 255)==255 && re->test_break())
+ break;
}
}
-
- if((a & 255)==255 && re->test_break())
- break;
}
if(re->test_break())
@@ -2495,11 +2683,17 @@ void zbuffer_sss(RenderPart *pa, unsigned int lay, void *handle, void (*func)(vo
for(i=0, obi=R.instancetable.first; obi; i++, obi=obi->next) {
obr= obi->obr;
+ if(!(obi->lay & lay))
+ continue;
+
if(obi->flag & R_TRANSFORMED)
zbuf_make_winmat(&R, obi->mat, winmat);
else
zbuf_make_winmat(&R, NULL, winmat);
+ if(clip_render_object(obi->obr->boundbox, bounds, winmat))
+ continue;
+
zbuf_project_cache_clear(cache, obr->totvert);
for(v=0; v<obr->totvlak; v++) {
@@ -2508,7 +2702,7 @@ void zbuffer_sss(RenderPart *pa, unsigned int lay, void *handle, void (*func)(vo
if(material_in_material(vlr->mat, sss_ma)) {
/* three cases, visible for render, only z values and nothing */
- if(vlr->lay & lay) {
+ if(obi->lay & lay) {
if(vlr->mat!=ma) {
ma= vlr->mat;
nofill= ma->mode & MA_ONLYCAST;
@@ -2762,14 +2956,46 @@ void antialias_tagbuf(int xsize, int ysize, char *rectmove)
}
}
+/* in: two vectors, first vector points from origin back in time, 2nd vector points to future */
+/* we make this into 3 points, center point is (0,0) */
+/* and offset the center point just enough to make curve go through midpoint */
+
+static void quad_bezier_2d(float *result, float *v1, float *v2, float *ipodata)
+{
+ float p1[2], p2[2], p3[2];
+
+ p3[0]= -v2[0];
+ p3[1]= -v2[1];
+
+ p1[0]= v1[0];
+ p1[1]= v1[1];
+
+ /* official formula 2*p2 - .5*p1 - .5*p3 */
+ p2[0]= -0.5*p1[0] - 0.5*p3[0];
+ p2[1]= -0.5*p1[1] - 0.5*p3[1];
+
+ result[0]= ipodata[0]*p1[0] + ipodata[1]*p2[0] + ipodata[2]*p3[0];
+ result[1]= ipodata[0]*p1[1] + ipodata[1]*p2[1] + ipodata[2]*p3[1];
+}
+
+static void set_quad_bezier_ipo(float fac, float *data)
+{
+ float mfac= (1.0f-fac);
+
+ data[0]= mfac*mfac;
+ data[1]= 2.0f*mfac*fac;
+ data[2]= fac*fac;
+}
+
void RE_zbuf_accumulate_vecblur(NodeBlurData *nbd, int xsize, int ysize, float *newrect, float *imgrect, float *vecbufrect, float *zbufrect)
{
ZSpan zspan;
DrawBufPixel *rectdraw, *dr;
- static float jit[16][2];
+ static float jit[256][2];
float v1[3], v2[3], v3[3], v4[3], fx, fy;
- float *rectvz, *dvz, *dimg, *dvec1, *dvec2, *dz1, *dz2, *rectz, *minvecbufrect= NULL;
- float maxspeedsq= (float)nbd->maxspeed*nbd->maxspeed;
+ float *rectvz, *dvz, *dimg, *dvec1, *dvec2, *dz, *dz1, *dz2, *rectz;
+ float *minvecbufrect= NULL, *rectweight, *rw, *rectmax, *rm, *ro;
+ float maxspeedsq= (float)nbd->maxspeed*nbd->maxspeed, totfac;
int y, x, step, maxspeed=nbd->maxspeed, samples= nbd->samples;
int tsktsk= 0;
static int firsttime= 1;
@@ -2788,6 +3014,9 @@ void RE_zbuf_accumulate_vecblur(NodeBlurData *nbd, int xsize, int ysize, float *
rectmove= MEM_mapallocN(xsize*ysize, "rectmove");
rectdraw= MEM_mapallocN(sizeof(DrawBufPixel)*xsize*ysize, "rect draw");
zspan.rectp= (int *)rectdraw;
+
+ rectweight= MEM_mapallocN(sizeof(float)*xsize*ysize, "rect weight");
+ rectmax= MEM_mapallocN(sizeof(float)*xsize*ysize, "rect max");
/* debug... check if PASS_VECTOR_MAX still is in buffers */
dvec1= vecbufrect;
@@ -2830,29 +3059,21 @@ void RE_zbuf_accumulate_vecblur(NodeBlurData *nbd, int xsize, int ysize, float *
}
/* make vertex buffer with averaged speed and zvalues */
- rectvz= MEM_mapallocN(5*sizeof(float)*(xsize+1)*(ysize+1), "vertices");
+ rectvz= MEM_mapallocN(4*sizeof(float)*(xsize+1)*(ysize+1), "vertices");
dvz= rectvz;
for(y=0; y<=ysize; y++) {
- if(y==0) {
+ if(y==0)
dvec1= vecbufrect + 4*y*xsize;
- dz1= zbufrect + y*xsize;
- }
- else {
+ else
dvec1= vecbufrect + 4*(y-1)*xsize;
- dz1= zbufrect + (y-1)*xsize;
- }
- if(y==ysize) {
+ if(y==ysize)
dvec2= vecbufrect + 4*(y-1)*xsize;
- dz2= zbufrect + (y-1)*xsize;
- }
- else {
+ else
dvec2= vecbufrect + 4*y*xsize;
- dz2= zbufrect + y*xsize;
- }
- for(x=0; x<=xsize; x++, dz1++, dz2++) {
+ for(x=0; x<=xsize; x++) {
/* two vectors, so a step loop */
for(step=0; step<2; step++, dvec1+=2, dvec2+=2, dvz+=2) {
@@ -2910,30 +3131,21 @@ void RE_zbuf_accumulate_vecblur(NodeBlurData *nbd, int xsize, int ysize, float *
}
}
}
- /* the z coordinate */
- if(x!=0) {
- if(x!=xsize)
- dvz[0]= 0.25f*(dz1[-1] + dz2[-1] + dz1[0] + dz2[0]);
- else dvz[0]= 0.5f*(dz1[0] + dz2[0]);
- }
- else dvz[0]= 0.5f*(dz1[-1] + dz2[-1]);
-
- dvz++;
}
}
/* set border speeds to keep border speeds on border */
dz1= rectvz;
- dz2= rectvz+5*(ysize)*(xsize+1);
- for(x=0; x<=xsize; x++, dz1+=5, dz2+=5) {
+ dz2= rectvz+4*(ysize)*(xsize+1);
+ for(x=0; x<=xsize; x++, dz1+=4, dz2+=4) {
dz1[1]= 0.0f;
dz2[1]= 0.0f;
dz1[3]= 0.0f;
dz2[3]= 0.0f;
}
dz1= rectvz;
- dz2= rectvz+5*(xsize);
- for(y=0; y<=ysize; y++, dz1+=5*(xsize+1), dz2+=5*(xsize+1)) {
+ dz2= rectvz+4*(xsize);
+ for(y=0; y<=ysize; y++, dz1+=4*(xsize+1), dz2+=4*(xsize+1)) {
dz1[0]= 0.0f;
dz2[0]= 0.0f;
dz1[2]= 0.0f;
@@ -2944,7 +3156,7 @@ void RE_zbuf_accumulate_vecblur(NodeBlurData *nbd, int xsize, int ysize, float *
dm= rectmove;
dvec1= vecbufrect;
for(x=xsize*ysize; x>0; x--, dm++, dvec1+=4) {
- if(dvec1[0]!=0.0f || dvec1[1]!=0.0f || dvec1[2]!=0.0f || dvec1[3]!=0.0f)
+ if((dvec1[0]!=0.0f || dvec1[1]!=0.0f || dvec1[2]!=0.0f || dvec1[3]!=0.0f))
*dm= 255;
}
@@ -2953,17 +3165,20 @@ void RE_zbuf_accumulate_vecblur(NodeBlurData *nbd, int xsize, int ysize, float *
/* has to become static, the init-jit calls a random-seed, screwing up texture noise node */
if(firsttime) {
firsttime= 0;
- BLI_initjit(jit[0], 16);
+ BLI_initjit(jit[0], 256);
}
+ memset(newrect, 0, sizeof(float)*xsize*ysize*4);
+ totfac= 0.0f;
+
/* accumulate */
samples/= 2;
for(step= 1; step<=samples; step++) {
float speedfac= 0.5f*nbd->fac*(float)step/(float)(samples+1);
- float blendfac= 1.0f/(ABS(step)+1);
- int side, z= 4;
+ int side;
for(side=0; side<2; side++) {
+ float blendfac, ipodata[4];
/* clear zbuf, if we draw future we fill in not moving pixels */
if(0)
@@ -2981,58 +3196,111 @@ void RE_zbuf_accumulate_vecblur(NodeBlurData *nbd, int xsize, int ysize, float *
dimg= imgrect;
dm= rectmove;
+ dz= zbufrect;
dz1= rectvz;
- dz2= rectvz + 5*(xsize + 1);
+ dz2= rectvz + 4*(xsize + 1);
if(side) {
- dz1+= 2;
- dz2+= 2;
- z= 2;
+ if(nbd->curved==0) {
+ dz1+= 2;
+ dz2+= 2;
+ }
speedfac= -speedfac;
}
-
- for(fy= -0.5f+jit[step & 15][0], y=0; y<ysize; y++, fy+=1.0f) {
- for(fx= -0.5f+jit[step & 15][1], x=0; x<xsize; x++, fx+=1.0f, dimg+=4, dz1+=5, dz2+=5, dm++) {
+
+ set_quad_bezier_ipo(0.5f + 0.5f*speedfac, ipodata);
+
+ for(fy= -0.5f+jit[step & 255][0], y=0; y<ysize; y++, fy+=1.0f) {
+ for(fx= -0.5f+jit[step & 255][1], x=0; x<xsize; x++, fx+=1.0f, dimg+=4, dz1+=4, dz2+=4, dm++, dz++) {
if(*dm>1) {
+ float jfx = fx + 0.5f;
+ float jfy = fy + 0.5f;
DrawBufPixel col;
/* make vertices */
- v1[0]= speedfac*dz1[0]+fx; v1[1]= speedfac*dz1[1]+fy; v1[2]= dz1[z];
- v2[0]= speedfac*dz1[5]+fx+1.0f; v2[1]= speedfac*dz1[6]+fy; v2[2]= dz1[z+5];
- v3[0]= speedfac*dz2[5]+fx+1.0f; v3[1]= speedfac*dz2[6]+fy+1.0f; v3[2]= dz2[z+5];
- v4[0]= speedfac*dz2[0]+fx; v4[1]= speedfac*dz2[1]+fy+1.0f; v4[2]= dz2[z];
-
+ if(nbd->curved) { /* curved */
+ quad_bezier_2d(v1, dz1, dz1+2, ipodata);
+ v1[0]+= jfx; v1[1]+= jfy; v1[2]= *dz;
+
+ quad_bezier_2d(v2, dz1+4, dz1+4+2, ipodata);
+ v2[0]+= jfx+1.0f; v2[1]+= jfy; v2[2]= *dz;
+
+ quad_bezier_2d(v3, dz2+4, dz2+4+2, ipodata);
+ v3[0]+= jfx+1.0f; v3[1]+= jfy+1.0f; v3[2]= *dz;
+
+ quad_bezier_2d(v4, dz2, dz2+2, ipodata);
+ v4[0]+= jfx; v4[1]+= jfy+1.0f; v4[2]= *dz;
+ }
+ else {
+ v1[0]= speedfac*dz1[0]+jfx; v1[1]= speedfac*dz1[1]+jfy; v1[2]= *dz;
+ v2[0]= speedfac*dz1[4]+jfx+1.0f; v2[1]= speedfac*dz1[5]+jfy; v2[2]= *dz;
+ v3[0]= speedfac*dz2[4]+jfx+1.0f; v3[1]= speedfac*dz2[5]+jfy+1.0f; v3[2]= *dz;
+ v4[0]= speedfac*dz2[0]+jfx; v4[1]= speedfac*dz2[1]+jfy+1.0f; v4[2]= *dz;
+ }
if(*dm==255) col.alpha= 1.0f;
else if(*dm<2) col.alpha= 0.0f;
else col.alpha= ((float)*dm)/255.0f;
col.colpoin= dimg;
-
+
zbuf_fill_in_rgba(&zspan, &col, v1, v2, v3, v4);
}
}
- dz1+=5;
- dz2+=5;
+ dz1+=4;
+ dz2+=4;
}
-
+
+ /* blend with a falloff. this fixes the ugly effect you get with
+ * a fast moving object. then it looks like a solid object overlayed
+ * over a very transparent moving version of itself. in reality, the
+ * whole object should become transparent if it is moving fast, be
+ * we don't know what is behind it so we don't do that. this hack
+ * overestimates the contribution of foreground pixels but looks a
+ * bit better without a sudden cutoff. */
+ blendfac= ((samples - step)/(float)samples);
+ /* smoothstep to make it look a bit nicer as well */
+ blendfac= 3.0f*pow(blendfac, 2.0f) - 2.0f*pow(blendfac, 3.0f);
+
/* accum */
- for(dr= rectdraw, dz2=newrect, x= xsize*ysize-1; x>=0; x--, dr++, dz2+=4) {
+ rw= rectweight;
+ rm= rectmax;
+ for(dr= rectdraw, dz2=newrect, x= xsize*ysize-1; x>=0; x--, dr++, dz2+=4, rw++, rm++) {
if(dr->colpoin) {
float bfac= dr->alpha*blendfac;
- float mf= 1.0f - bfac;
- dz2[0]= mf*dz2[0] + bfac*dr->colpoin[0];
- dz2[1]= mf*dz2[1] + bfac*dr->colpoin[1];
- dz2[2]= mf*dz2[2] + bfac*dr->colpoin[2];
- dz2[3]= mf*dz2[3] + bfac*dr->colpoin[3];
+ dz2[0] += bfac*dr->colpoin[0];
+ dz2[1] += bfac*dr->colpoin[1];
+ dz2[2] += bfac*dr->colpoin[2];
+ dz2[3] += bfac*dr->colpoin[3];
+
+ *rw += bfac;
+ *rm= MAX2(*rm, bfac);
}
}
}
}
+ /* blend between original images and accumulated image */
+ rw= rectweight;
+ rm= rectmax;
+ ro= imgrect;
+ dm= rectmove;
+ for(dz2=newrect, x= xsize*ysize-1; x>=0; x--, dz2+=4, ro+=4, rw++, rm++, dm++) {
+ float mfac = *rm;
+ float fac = (*rw == 0.0f)? 0.0f: mfac/(*rw);
+ float nfac = 1.0f - mfac;
+
+ dz2[0]= fac*dz2[0] + nfac*ro[0];
+ dz2[1]= fac*dz2[1] + nfac*ro[1];
+ dz2[2]= fac*dz2[2] + nfac*ro[2];
+ dz2[3]= fac*dz2[3] + nfac*ro[3];
+ }
+
MEM_freeN(rectz);
MEM_freeN(rectmove);
MEM_freeN(rectdraw);
MEM_freeN(rectvz);
+ MEM_freeN(rectweight);
+ MEM_freeN(rectmax);
if(minvecbufrect) MEM_freeN(vecbufrect); /* rects were swapped! */
zbuf_free_span(&zspan);
}
@@ -3043,18 +3311,21 @@ void RE_zbuf_accumulate_vecblur(NodeBlurData *nbd, int xsize, int ysize, float *
* Copy results from the solid face z buffering to the transparent
* buffer.
*/
-static void copyto_abufz(RenderPart *pa, int *arectz, int sample)
+static void copyto_abufz(RenderPart *pa, int *arectz, int *rectmask, int sample)
{
PixStr *ps;
- int x, y, *rza;
- long *rd;
+ int x, y, *rza, *rma;
+ intptr_t *rd;
if(R.osa==0) {
- memcpy(arectz, pa->rectz, 4*pa->rectx*pa->recty);
+ memcpy(arectz, pa->rectz, sizeof(int)*pa->rectx*pa->recty);
+ if(rectmask && pa->rectmask)
+ memcpy(rectmask, pa->rectmask, sizeof(int)*pa->rectx*pa->recty);
return;
}
rza= arectz;
+ rma= rectmask;
rd= pa->rectdaps;
sample= (1<<sample);
@@ -3063,17 +3334,19 @@ static void copyto_abufz(RenderPart *pa, int *arectz, int sample)
for(x=0; x<pa->rectx; x++) {
*rza= 0x7FFFFFFF;
+ if(rectmask) *rma= 0x7FFFFFFF;
if(*rd) {
/* when there's a sky pixstruct, fill in sky-Z, otherwise solid Z */
for(ps= (PixStr *)(*rd); ps; ps= ps->next) {
if(sample & ps->mask) {
*rza= ps->z;
+ if(rectmask) *rma= ps->maskz;
break;
}
}
}
- rd++; rza++;
+ rd++; rza++, rma++;
}
}
}
@@ -3085,7 +3358,7 @@ static void copyto_abufz(RenderPart *pa, int *arectz, int sample)
* Do accumulation z buffering.
*/
-static int zbuffer_abuf(RenderPart *pa, APixstr *APixbuf, ListBase *apsmbase, unsigned int lay)
+static int zbuffer_abuf(RenderPart *pa, APixstr *APixbuf, ListBase *apsmbase, RenderLayer *rl, unsigned int lay)
{
ZbufProjectCache cache[ZBUF_PROJECT_CACHE_SIZE];
ZSpan zspans[16], *zspan; /* MAX_OSA */
@@ -3116,11 +3389,14 @@ static int zbuffer_abuf(RenderPart *pa, APixstr *APixbuf, ListBase *apsmbase, un
zspan->apixbuf= APixbuf;
zspan->apsmbase= apsmbase;
+ if((rl->layflag & SCE_LAY_ZMASK) && (rl->layflag & SCE_LAY_NEG_ZMASK))
+ zspan->rectmask= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "Arectmask");
+
/* filling methods */
zspan->zbuffunc= zbuffillAc4;
zspan->zbuflinefunc= zbuflineAc;
- copyto_abufz(pa, zspan->arectz, zsample); /* init zbuffer */
+ copyto_abufz(pa, zspan->arectz, zspan->rectmask, zsample); /* init zbuffer */
zspan->mask= 1<<zsample;
if(R.osa) {
@@ -3138,7 +3414,6 @@ static int zbuffer_abuf(RenderPart *pa, APixstr *APixbuf, ListBase *apsmbase, un
/* to center the sample position */
zspan->zofsx -= 0.5f;
zspan->zofsy -= 0.5f;
-
}
/* we use this to test if nothing was filled in */
@@ -3147,11 +3422,17 @@ static int zbuffer_abuf(RenderPart *pa, APixstr *APixbuf, ListBase *apsmbase, un
for(i=0, obi=R.instancetable.first; obi; i++, obi=obi->next) {
obr= obi->obr;
+ if(!(obi->lay & lay))
+ continue;
+
if(obi->flag & R_TRANSFORMED)
zbuf_make_winmat(&R, obi->mat, winmat);
else
zbuf_make_winmat(&R, NULL, winmat);
+ if(clip_render_object(obi->obr->boundbox, bounds, winmat))
+ continue;
+
zbuf_project_cache_clear(cache, obr->totvert);
for(v=0; v<obr->totvlak; v++) {
@@ -3165,7 +3446,7 @@ static int zbuffer_abuf(RenderPart *pa, APixstr *APixbuf, ListBase *apsmbase, un
}
if(dofill) {
- if(!(vlr->flag & R_HIDDEN) && (vlr->lay & lay)) {
+ if(!(vlr->flag & R_HIDDEN) && (obi->lay & lay)) {
unsigned short partclip;
v1= vlr->v1;
@@ -3243,6 +3524,8 @@ static int zbuffer_abuf(RenderPart *pa, APixstr *APixbuf, ListBase *apsmbase, un
for(zsample=0; zsample<samples; zsample++) {
zspan= &zspans[zsample];
MEM_freeN(zspan->arectz);
+ if(zspan->rectmask)
+ MEM_freeN(zspan->rectmask);
zbuf_free_span(zspan);
}
@@ -3253,7 +3536,7 @@ static int zbuffer_abuf(RenderPart *pa, APixstr *APixbuf, ListBase *apsmbase, un
/* speed pointer NULL = sky, we clear */
/* else if either alpha is full or no solid was filled in: copy speed */
/* else fill in minimum speed */
-void add_transp_speed(RenderLayer *rl, int offset, float *speed, float alpha, long *rdrect)
+void add_transp_speed(RenderLayer *rl, int offset, float *speed, float alpha, intptr_t *rdrect)
{
RenderPass *rpass;
@@ -3287,20 +3570,15 @@ void add_transp_speed(RenderLayer *rl, int offset, float *speed, float alpha, lo
}
}
-static void add_transp_obindex(RenderLayer *rl, int offset, int obi, int facenr)
+static void add_transp_obindex(RenderLayer *rl, int offset, Object *ob)
{
- ObjectRen *obr= R.objectinstance[obi].obr;
- VlakRen *vlr= RE_findOrAddVlak(obr, (facenr-1) & RE_QUAD_MASK);
-
- if(vlr && obr->ob) {
- RenderPass *rpass;
-
- for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
- if(rpass->passtype == SCE_PASS_INDEXOB) {
- float *fp= rpass->rect + offset;
- *fp= (float)obr->ob->index;
- break;
- }
+ RenderPass *rpass;
+
+ for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
+ if(rpass->passtype == SCE_PASS_INDEXOB) {
+ float *fp= rpass->rect + offset;
+ *fp= (float)ob->index;
+ break;
}
}
}
@@ -3315,7 +3593,7 @@ void merge_transp_passes(RenderLayer *rl, ShadeResult *shr)
for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
float *col= NULL;
- int pixsize= 0;
+ int pixsize= 3;
switch(rpass->passtype) {
case SCE_PASS_RGBA:
@@ -3346,6 +3624,14 @@ void merge_transp_passes(RenderLayer *rl, ShadeResult *shr)
case SCE_PASS_NORMAL:
col= shr->nor;
break;
+ case SCE_PASS_MIST:
+ col= &shr->mist;
+ pixsize= 1;
+ break;
+ case SCE_PASS_Z:
+ col= &shr->z;
+ pixsize= 1;
+ break;
case SCE_PASS_VECTOR:
{
@@ -3378,14 +3664,18 @@ void merge_transp_passes(RenderLayer *rl, ShadeResult *shr)
for(samp= 1; samp<R.osa; samp++, fp+=delta) {
col[0]+= fp[0];
- col[1]+= fp[1];
- col[2]+= fp[2];
- if(pixsize) col[3]+= fp[3];
+ if(pixsize>1) {
+ col[1]+= fp[1];
+ col[2]+= fp[2];
+ if(pixsize==4) col[3]+= fp[3];
+ }
}
col[0]*= weight;
- col[1]*= weight;
- col[2]*= weight;
- if(pixsize) col[3]*= weight;
+ if(pixsize>1) {
+ col[1]*= weight;
+ col[2]*= weight;
+ if(pixsize==4) col[3]*= weight;
+ }
}
}
@@ -3397,8 +3687,14 @@ void add_transp_passes(RenderLayer *rl, int offset, ShadeResult *shr, float alph
for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
float *fp, *col= NULL;
+ int pixsize= 3;
switch(rpass->passtype) {
+ case SCE_PASS_Z:
+ fp= rpass->rect + offset;
+ if(shr->z < *fp)
+ *fp= shr->z;
+ break;
case SCE_PASS_RGBA:
fp= rpass->rect + 4*offset;
addAlphaOverFloat(fp, shr->col);
@@ -3427,23 +3723,30 @@ void add_transp_passes(RenderLayer *rl, int offset, ShadeResult *shr, float alph
case SCE_PASS_NORMAL:
col= shr->nor;
break;
+ case SCE_PASS_MIST:
+ col= &shr->mist;
+ pixsize= 1;
+ break;
}
if(col) {
- fp= rpass->rect + 3*offset;
- fp[0]= alpha*col[0] + (1.0f-alpha)*fp[0];
- fp[1]= alpha*col[1] + (1.0f-alpha)*fp[1];
- fp[2]= alpha*col[2] + (1.0f-alpha)*fp[2];
+ fp= rpass->rect + pixsize*offset;
+ fp[0]= col[0] + (1.0f-alpha)*fp[0];
+ if(pixsize==3) {
+ fp[1]= col[1] + (1.0f-alpha)*fp[1];
+ fp[2]= col[2] + (1.0f-alpha)*fp[2];
+ }
}
}
}
-
typedef struct ZTranspRow {
int obi;
int z;
int p;
int mask;
+ int segment;
+ float u, v;
} ZTranspRow;
static int vergzvlak(const void *a1, const void *a2)
@@ -3455,6 +3758,56 @@ static int vergzvlak(const void *a1, const void *a2)
return 0;
}
+static void shade_strand_samples(StrandShadeCache *cache, ShadeSample *ssamp, int x, int y, ZTranspRow *row, int addpassflag)
+{
+ StrandSegment sseg;
+ StrandVert *svert;
+ ObjectInstanceRen *obi;
+ ObjectRen *obr;
+
+ obi= R.objectinstance + row->obi;
+ obr= obi->obr;
+
+ sseg.obi= obi;
+ sseg.strand= RE_findOrAddStrand(obr, row->p-1);
+ sseg.buffer= sseg.strand->buffer;
+
+ svert= sseg.strand->vert + row->segment;
+ sseg.v[0]= (row->segment > 0)? (svert-1): svert;
+ sseg.v[1]= svert;
+ sseg.v[2]= svert+1;
+ sseg.v[3]= (row->segment < sseg.strand->totvert-2)? svert+2: svert+1;
+
+ ssamp->tot= 1;
+ strand_shade_segment(&R, cache, &sseg, ssamp, row->v, row->u, addpassflag);
+ ssamp->shi[0].mask= row->mask;
+}
+
+static void unref_strand_samples(StrandShadeCache *cache, ZTranspRow *row, int totface)
+{
+ StrandVert *svert;
+ ObjectInstanceRen *obi;
+ ObjectRen *obr;
+ StrandRen *strand;
+
+ /* remove references to samples that are not being rendered, but we still
+ * need to remove them so that the reference count of strand vertex shade
+ * samples correctly drops to zero */
+ while(totface > 0) {
+ totface--;
+
+ if(row[totface].segment != -1) {
+ obi= R.objectinstance + row[totface].obi;
+ obr= obi->obr;
+ strand= RE_findOrAddStrand(obr, row[totface].p-1);
+ svert= strand->vert + row[totface].segment;
+
+ strand_shade_unref(cache, svert);
+ strand_shade_unref(cache, svert+1);
+ }
+ }
+}
+
static void shade_tra_samples_fill(ShadeSample *ssamp, int x, int y, int z, int obi, int facenr, int curmask)
{
ShadeInput *shi= ssamp->shi;
@@ -3481,8 +3834,8 @@ static void shade_tra_samples_fill(ShadeSample *ssamp, int x, int y, int z, int
shi++;
}
shi->mask= (1<<samp);
- shi->samplenr= ssamp->samplenr++;
- shade_input_set_viewco(shi, xs, ys, (float)z);
+ shi->samplenr= R.shadowsamplenr[shi->thread]++;
+ shade_input_set_viewco(shi, x, y, xs, ys, (float)z);
shade_input_set_uv(shi);
shade_input_set_normals(shi);
@@ -3501,8 +3854,8 @@ static void shade_tra_samples_fill(ShadeSample *ssamp, int x, int y, int z, int
ys= (float)y + 0.5f;
}
shi->mask= curmask;
- shi->samplenr= ssamp->samplenr++;
- shade_input_set_viewco(shi, xs, ys, (float)z);
+ shi->samplenr= R.shadowsamplenr[shi->thread]++;
+ shade_input_set_viewco(shi, x, y, xs, ys, (float)z);
shade_input_set_uv(shi);
shade_input_set_normals(shi);
}
@@ -3512,8 +3865,13 @@ static void shade_tra_samples_fill(ShadeSample *ssamp, int x, int y, int z, int
}
}
-static int shade_tra_samples(ShadeSample *ssamp, int x, int y, ZTranspRow *row)
+static int shade_tra_samples(ShadeSample *ssamp, StrandShadeCache *cache, int x, int y, ZTranspRow *row, int addpassflag)
{
+ if(row->segment != -1) {
+ shade_strand_samples(cache, ssamp, x, y, row, addpassflag);
+ return 1;
+ }
+
shade_tra_samples_fill(ssamp, x, y, row->z, row->obi, row->p, row->mask);
if(ssamp->tot) {
@@ -3548,7 +3906,7 @@ static void addvecmul(float *v1, float *v2, float fac)
v1[2]= v1[2]+fac*v2[2];
}
-int addtosamp_shr(ShadeResult *samp_shr, ShadeSample *ssamp, int addpassflag)
+static int addtosamp_shr(ShadeResult *samp_shr, ShadeSample *ssamp, int addpassflag)
{
int a, sample, osa = (R.osa? R.osa: 1), retval = osa;
@@ -3563,6 +3921,8 @@ int addtosamp_shr(ShadeResult *samp_shr, ShadeSample *ssamp, int addpassflag)
addAlphaUnderFloat(samp_shr->combined, shr->combined);
+ samp_shr->z= MIN2(samp_shr->z, shr->z);
+
if(addpassflag & SCE_PASS_VECTOR) {
QUATCOPY(samp_shr->winspeed, shr->winspeed);
}
@@ -3595,6 +3955,10 @@ int addtosamp_shr(ShadeResult *samp_shr, ShadeSample *ssamp, int addpassflag)
if(addpassflag & SCE_PASS_RADIO)
addvecmul(samp_shr->rad, shr->rad, fac);
+
+ if(addpassflag & SCE_PASS_MIST)
+ samp_shr->mist= samp_shr->mist+fac*shr->mist;
+
}
}
}
@@ -3604,7 +3968,7 @@ int addtosamp_shr(ShadeResult *samp_shr, ShadeSample *ssamp, int addpassflag)
return retval;
}
-void reset_sky_speedvectors(RenderPart *pa, RenderLayer *rl, float *rectf)
+static void reset_sky_speedvectors(RenderPart *pa, RenderLayer *rl, float *rectf)
{
/* speed vector exception... if solid render was done, sky pixels are set to zero already */
/* for all pixels with alpha zero, we re-initialize speed again then */
@@ -3627,23 +3991,27 @@ void reset_sky_speedvectors(RenderPart *pa, RenderLayer *rl, float *rectf)
#define MAX_ZROW 2000
-/* main render call to fill in pass the full transparent layer */
+/* main render call to do the z-transparent layer */
/* returns a mask, only if a) transp rendered and b) solid was rendered */
-unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pass)
+unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pass, ListBase *psmlist)
{
RenderResult *rr= pa->result;
ShadeSample ssamp;
APixstr *APixbuf; /* Zbuffer: linked list of face samples */
+ APixstrand *APixbufstrand = NULL;
APixstr *ap, *aprect, *apn;
+ APixstrand *apstrand, *aprectstrand, *apnstrand;
ListBase apsmbase={NULL, NULL};
ShadeResult samp_shr[16]; /* MAX_OSA */
ZTranspRow zrow[MAX_ZROW];
- float sampalpha, *passrect= pass;
- long *rdrect;
- int x, y, crop=0, a, totface;
- int addpassflag, offs= 0, od, addzbuf;
- unsigned short *ztramask= NULL;
-
+ StrandShadeCache *sscache= NULL;
+ RenderLayer *rlpp[RE_MAX_OSA];
+ float sampalpha, alpha, *passrect= pass;
+ intptr_t *rdrect;
+ int x, y, crop=0, a, b, totface, totfullsample, totsample, doztra;
+ int addpassflag, offs= 0, od, osa = (R.osa? R.osa: 1);
+ unsigned short *ztramask= NULL, filled;
+
/* looks nicer for calling code */
if(R.test_break())
return NULL;
@@ -3655,14 +4023,14 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
}
APixbuf= MEM_callocN(pa->rectx*pa->recty*sizeof(APixstr), "APixbuf");
+ if(R.totstrand && (rl->layflag & SCE_LAY_STRAND)) {
+ APixbufstrand= MEM_callocN(pa->rectx*pa->recty*sizeof(APixstrand), "APixbufstrand");
+ sscache= strand_shade_cache_create();
+ }
/* general shader info, passes */
shade_sample_initialize(&ssamp, pa, rl);
- addpassflag= rl->passflag & ~(SCE_PASS_Z|SCE_PASS_COMBINED);
- if((rl->layflag & SCE_LAY_STRAND) && R.totstrand)
- addzbuf= 1; /* strands layer needs the z-buffer */
- else
- addzbuf= rl->passflag & SCE_PASS_Z;
+ addpassflag= rl->passflag & ~(SCE_PASS_COMBINED);
if(R.osa)
sampalpha= 1.0f/(float)R.osa;
@@ -3670,28 +4038,42 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
sampalpha= 1.0f;
/* fill the Apixbuf */
- if(0 == zbuffer_abuf(pa, APixbuf, &apsmbase, rl->lay)) {
+ doztra= 0;
+ if(rl->layflag & SCE_LAY_ZTRA)
+ doztra+= zbuffer_abuf(pa, APixbuf, &apsmbase, rl, rl->lay);
+ if((rl->layflag & SCE_LAY_STRAND) && APixbufstrand)
+ doztra+= zbuffer_strands_abuf(&R, pa, rl, APixbufstrand, &apsmbase, sscache);
+
+ if(doztra == 0) {
/* nothing filled in */
MEM_freeN(APixbuf);
+ if(APixbufstrand)
+ MEM_freeN(APixbufstrand);
+ if(sscache)
+ strand_shade_cache_free(sscache);
freepsA(&apsmbase);
return NULL;
}
aprect= APixbuf;
+ aprectstrand= APixbufstrand;
rdrect= pa->rectdaps;
+
+ /* needed for correct zbuf/index pass */
+ totfullsample= get_sample_layers(pa, rl, rlpp);
/* irregular shadowb buffer creation */
if(R.r.mode & R_SHADOW)
ISB_create(pa, APixbuf);
/* masks, to have correct alpha combine */
- if(R.osa && (rl->layflag & SCE_LAY_SOLID))
+ if(R.osa && (rl->layflag & SCE_LAY_SOLID) && pa->fullresult.first==NULL)
ztramask= MEM_callocN(pa->rectx*pa->recty*sizeof(short), "ztramask");
/* zero alpha pixels get speed vector max again */
if(addpassflag & SCE_PASS_VECTOR)
if(rl->layflag & SCE_LAY_SOLID)
- reset_sky_speedvectors(pa, rl, rl->acolrect);
+ reset_sky_speedvectors(pa, rl, rl->acolrect?rl->acolrect:rl->rectf); /* if acolrect is set we use it */
/* filtered render, for now we assume only 1 filter size */
if(pa->crop) {
@@ -3699,6 +4081,7 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
offs= pa->rectx + 1;
passrect+= 4*offs;
aprect+= offs;
+ aprectstrand+= offs;
}
/* init scanline updates */
@@ -3710,14 +4093,15 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
for(y=pa->disprect.ymin+crop; y<pa->disprect.ymax-crop; y++, rr->renrect.ymax++) {
pass= passrect;
ap= aprect;
+ apstrand= aprectstrand;
od= offs;
if(R.test_break())
break;
- for(x=pa->disprect.xmin+crop; x<pa->disprect.xmax-crop; x++, ap++, pass+=4, od++) {
+ for(x=pa->disprect.xmin+crop; x<pa->disprect.xmax-crop; x++, ap++, apstrand++, pass+=4, od++) {
- if(ap->p[0]==0) {
+ if(ap->p[0]==0 && (!APixbufstrand || apstrand->p[0]==0)) {
if(addpassflag & SCE_PASS_VECTOR)
add_transp_speed(rl, od, NULL, 0.0f, rdrect);
}
@@ -3732,6 +4116,7 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
zrow[totface].z= apn->z[a];
zrow[totface].p= apn->p[a];
zrow[totface].mask= apn->mask[a];
+ zrow[totface].segment= -1;
totface++;
if(totface>=MAX_ZROW) totface= MAX_ZROW-1;
}
@@ -3739,7 +4124,35 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
}
apn= apn->next;
}
-
+
+ apnstrand= (APixbufstrand)? apstrand: NULL;
+ while(apnstrand) {
+ for(a=0; a<4; a++) {
+ if(apnstrand->p[a]) {
+ zrow[totface].obi= apnstrand->obi[a];
+ zrow[totface].z= apnstrand->z[a];
+ zrow[totface].p= apnstrand->p[a];
+ zrow[totface].mask= apnstrand->mask[a];
+ zrow[totface].segment= apnstrand->seg[a];
+
+ if(R.osa) {
+ totsample= 0;
+ for(b=0; b<R.osa; b++)
+ if(zrow[totface].mask & (1<<b))
+ totsample++;
+ }
+ else
+ totsample= 1;
+
+ zrow[totface].u= apnstrand->u[a]/totsample;
+ zrow[totface].v= apnstrand->v[a]/totsample;
+ totface++;
+ if(totface>=MAX_ZROW) totface= MAX_ZROW-1;
+ }
+ }
+ apnstrand= apnstrand->next;
+ }
+
if(totface==2) {
if(zrow[0].z < zrow[1].z) {
SWAP(ZTranspRow, zrow[0], zrow[1]);
@@ -3750,70 +4163,110 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
qsort(zrow, totface, sizeof(ZTranspRow), vergzvlak);
}
- /* zbuffer and index pass for transparent, no AA or filters */
- if(addzbuf)
- if(pa->rectz[od]>zrow[totface-1].z)
- pa->rectz[od]= zrow[totface-1].z;
-
- if(addpassflag & SCE_PASS_INDEXOB)
- add_transp_obindex(rl, od, zrow[totface-1].obi, zrow[totface-1].p);
-
+ /* front face does index pass for transparent, no AA or filters, but yes FSA */
+ if(addpassflag & SCE_PASS_INDEXOB) {
+ ObjectRen *obr= R.objectinstance[zrow[totface-1].obi].obr;
+ if(obr->ob) {
+ for(a= 0; a<totfullsample; a++)
+ add_transp_obindex(rlpp[a], od, obr->ob);
+ }
+ }
+ /* for each mask-sample we alpha-under colors. then in end it's added using filter */
+ memset(samp_shr, 0, sizeof(ShadeResult)*osa);
+ for(a=0; a<osa; a++) {
+ samp_shr[a].z= 10e10f;
+ if(addpassflag & SCE_PASS_VECTOR) {
+ samp_shr[a].winspeed[0]= PASS_VECTOR_MAX;
+ samp_shr[a].winspeed[1]= PASS_VECTOR_MAX;
+ samp_shr[a].winspeed[2]= PASS_VECTOR_MAX;
+ samp_shr[a].winspeed[3]= PASS_VECTOR_MAX;
+ }
+ }
+
if(R.osa==0) {
while(totface>0) {
totface--;
- if(shade_tra_samples(&ssamp, x, y, &zrow[totface])) {
- if(addpassflag)
- add_transp_passes(rl, od, ssamp.shr, (1.0f-pass[3])*ssamp.shr[0].combined[3]);
-
+ if(shade_tra_samples(&ssamp, sscache, x, y, &zrow[totface], addpassflag)) {
+ filled= addtosamp_shr(samp_shr, &ssamp, addpassflag);
addAlphaUnderFloat(pass, ssamp.shr[0].combined);
- if(pass[3]>=0.999) break;
+
+ if(filled == 0) {
+ if(sscache)
+ unref_strand_samples(sscache, zrow, totface);
+ break;
+ }
}
}
- if(addpassflag & SCE_PASS_VECTOR)
- add_transp_speed(rl, od, ssamp.shr[0].winspeed, pass[3], rdrect);
+
+ alpha= samp_shr->combined[3];
+ if(alpha!=0.0f) {
+ add_transp_passes(rl, od, samp_shr, alpha);
+ if(addpassflag & SCE_PASS_VECTOR)
+ add_transp_speed(rl, od, samp_shr->winspeed, alpha, rdrect);
+ }
}
else {
- short filled, *sp= (short *)(ztramask+od);
-
- /* for each mask-sample we alpha-under colors. then in end it's added using filter */
- memset(samp_shr, 0, sizeof(ShadeResult)*R.osa);
-
- /* nice this memset, but speed vectors are not initialized OK then. it is sufficient to only clear 1 (see merge_transp_passes) */
- if(addpassflag & SCE_PASS_VECTOR)
- samp_shr->winspeed[0]= samp_shr->winspeed[1]= samp_shr->winspeed[2]= samp_shr->winspeed[3]= PASS_VECTOR_MAX;
+ short *sp= (short *)(ztramask+od);
while(totface>0) {
totface--;
- if(shade_tra_samples(&ssamp, x, y, &zrow[totface])) {
+ if(shade_tra_samples(&ssamp, sscache, x, y, &zrow[totface], addpassflag)) {
filled= addtosamp_shr(samp_shr, &ssamp, addpassflag);
if(ztramask)
*sp |= zrow[totface].mask;
- if(filled==0)
+ if(filled==0) {
+ if(sscache)
+ unref_strand_samples(sscache, zrow, totface);
break;
+ }
}
}
- for(a=0; a<R.osa; a++) {
- add_filt_fmask(1<<a, samp_shr[a].combined, pass, rr->rectx);
+ /* multisample buffers or filtered mask filling? */
+ if(pa->fullresult.first) {
+ for(a=0; a<R.osa; a++) {
+ alpha= samp_shr[a].combined[3];
+ if(alpha!=0.0f) {
+ RenderLayer *rl= ssamp.rlpp[a];
+
+ addAlphaOverFloat(rl->rectf + 4*od, samp_shr[a].combined);
+
+ add_transp_passes(rl, od, &samp_shr[a], alpha);
+ if(addpassflag & SCE_PASS_VECTOR)
+ add_transp_speed(rl, od, samp_shr[a].winspeed, alpha, rdrect);
+ }
+ }
}
-
- if(addpassflag) {
- /* merge all in one, and then add */
- merge_transp_passes(rl, samp_shr);
- add_transp_passes(rl, od, samp_shr, pass[3]);
+ else {
+ alpha= 0.0f;
- if(addpassflag & SCE_PASS_VECTOR)
- add_transp_speed(rl, od, samp_shr[0].winspeed, pass[3], rdrect);
+ /* note; cannot use pass[3] for alpha due to filtermask */
+ for(a=0; a<R.osa; a++) {
+ add_filt_fmask(1<<a, samp_shr[a].combined, pass, rr->rectx);
+ alpha+= samp_shr[a].combined[3];
+ }
+
+ if(addpassflag) {
+ alpha*= sampalpha;
+
+ /* merge all in one, and then add */
+ merge_transp_passes(rl, samp_shr);
+ add_transp_passes(rl, od, samp_shr, alpha);
+
+ if(addpassflag & SCE_PASS_VECTOR)
+ add_transp_speed(rl, od, samp_shr[0].winspeed, alpha, rdrect);
+ }
}
}
}
}
aprect+= pa->rectx;
+ aprectstrand+= pa->rectx;
passrect+= 4*pa->rectx;
offs+= pa->rectx;
}
@@ -3822,6 +4275,10 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
rr->renlay= NULL;
MEM_freeN(APixbuf);
+ if(APixbufstrand)
+ MEM_freeN(APixbufstrand);
+ if(sscache)
+ strand_shade_cache_free(sscache);
freepsA(&apsmbase);
if(R.r.mode & R_SHADOW)
@@ -3830,45 +4287,6 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
return ztramask;
}
-/* *************** */
-
-/* uses part zbuffer values to convert into distances from camera in renderlayer */
-void convert_zbuf_to_distbuf(RenderPart *pa, RenderLayer *rl)
-{
- RenderPass *rpass;
- float *rectzf, zco;
- int a, *rectz, ortho= R.r.mode & R_ORTHO;
-
- if(pa->rectz==NULL) return;
- for(rpass= rl->passes.first; rpass; rpass= rpass->next)
- if(rpass->passtype==SCE_PASS_Z)
- break;
-
- if(rpass==NULL) {
- printf("called convert zbuf wrong...\n");
- return;
- }
-
- rectzf= rpass->rect;
- rectz= pa->rectz;
-
- for(a=pa->rectx*pa->recty; a>0; a--, rectz++, rectzf++) {
- if(*rectz>=0x7FFFFFF0)
- *rectzf= 10e10;
- else {
- /* inverse of zbuf calc: zbuf = MAXZ*hoco_z/hoco_w */
- /* or: (R.winmat[3][2] - zco*R.winmat[3][3])/(R.winmat[2][2] - R.winmat[2][3]*zco); */
- /* if ortho [2][3] is zero, else [3][3] is zero */
-
- zco= ((float)*rectz)/2147483647.0f;
- if(ortho)
- *rectzf= (R.winmat[3][2] - zco*R.winmat[3][3])/(R.winmat[2][2]);
- else
- *rectzf= (R.winmat[3][2])/(R.winmat[2][2] - R.winmat[2][3]*zco);
- }
- }
-}
-
/* end of zbuf.c */
diff --git a/source/blender/windowmanager/SConscript b/source/blender/windowmanager/SConscript
index e70a7207c11..cdc5edfeaa6 100644
--- a/source/blender/windowmanager/SConscript
+++ b/source/blender/windowmanager/SConscript
@@ -11,5 +11,5 @@ incs += ' ../nodes ../imbuf ../blenloader ../render/extern/include'
incs += ' ../ftfont ../radiosity/extern/include ../../kernel/gen_system'
incs += ' #/intern/guardedalloc #/intern/memutil #/intern/ghost #/intern/bmfont'
-incs += ' #/intern/elbeem'
+incs += ' #/intern/elbeem #/extern/glew/include'
env.BlenderLib ( 'bf_windowmanager', sources, Split(incs), [], libtype=['core','intern'], priority=[45, 45] )
diff --git a/source/blender/windowmanager/intern/Makefile b/source/blender/windowmanager/intern/Makefile
index 3eb4ef7a028..cbd0b3afa87 100644
--- a/source/blender/windowmanager/intern/Makefile
+++ b/source/blender/windowmanager/intern/Makefile
@@ -36,6 +36,7 @@ include nan_compile.mk
CFLAGS += $(LEVEL_1_C_WARNINGS)
# OpenGL and Python
+CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += $(OGL_CPPFLAGS)
CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION)
diff --git a/source/blender/windowmanager/intern/wm_init_exit.c b/source/blender/windowmanager/intern/wm_init_exit.c
index 67670383060..422a655f53a 100644
--- a/source/blender/windowmanager/intern/wm_init_exit.c
+++ b/source/blender/windowmanager/intern/wm_init_exit.c
@@ -240,8 +240,8 @@ void WM_exit(bContext *C)
MEM_freeN(C);
- if(totblock!=0) {
- printf("Error Totblock: %d\n",totblock);
+ if(MEM_get_memory_blocks_in_use()!=0) {
+ printf("Error Totblock: %d\n", MEM_get_memory_blocks_in_use());
MEM_printmemlist();
}
// delete_autosave();
diff --git a/source/blender/yafray/intern/export_File.cpp b/source/blender/yafray/intern/export_File.cpp
index 40992513c8e..ea700965826 100644
--- a/source/blender/yafray/intern/export_File.cpp
+++ b/source/blender/yafray/intern/export_File.cpp
@@ -1,6 +1,7 @@
#include "export_File.h"
#include <math.h>
+
#include <cstring>
using namespace std;
@@ -95,7 +96,7 @@ static void addDrive(string &path)
static string unixYafrayPath()
{
- static char *alternative[]=
+ static const char *alternative[]=
{
"/usr/local/bin/",
"/usr/bin/",
@@ -125,7 +126,7 @@ static void adjustPath(string &path)
// if relative, expand to full path
char cpath[MAXPATHLEN];
strcpy(cpath, path.c_str());
- BLI_convertstringcode(cpath, G.sce, 0);
+ BLI_convertstringcode(cpath, G.sce);
path = cpath;
#ifdef WIN32
// add drive char if not there
@@ -880,7 +881,7 @@ void yafrayFileRender_t::writeShader(const string &shader_name, Material* matr,
ostr << "\t\t<input value=\"" << shader_name << "_map" << m2 << "\" />\n";
// blendtype, would have been nice if the order would have been the same as for ramps...
- const string blendtype[9] = {"mix", "mul", "add", "sub", "divide", "darken", "difference", "lighten", "screen"};
+ const string blendtype[MTEX_NUM_BLENDTYPES] = {"mix", "mul", "add", "sub", "divide", "darken", "difference", "lighten", "screen", "hue", "sat", "val", "color"};
ostr << "\t\t<mode value=\"" << blendtype[(int)mtex->blendtype] << "\" />\n";
// texture color (for use with MUL and/or no_rgb etc..)
@@ -1189,7 +1190,7 @@ void yafrayFileRender_t::writeMaterialsAndModulators()
}
-void yafrayFileRender_t::writeObject(Object* obj, const vector<VlakRen*> &VLR_list, const float obmat[4][4])
+void yafrayFileRender_t::writeObject(Object* obj, ObjectRen *obr, const vector<VlakRen*> &VLR_list, const float obmat[4][4])
{
ostr.str("");
// transform first (not necessarily actual obj->obmat, can be duplivert see below)
@@ -1231,7 +1232,6 @@ void yafrayFileRender_t::writeObject(Object* obj, const vector<VlakRen*> &VLR_li
string matname(face0mat->id.name);
// use name in imgtex_shader list if 'TexFace' enabled for this material
if (face0mat->mode & MA_FACETEXTURE) {
- ObjectRen *obr = face0->obr;
MTFace* tface = RE_vlakren_get_tface(obr, face0, obr->actmtface, NULL, 0);
if (tface) {
Image* fimg = (Image*)tface->tpage;
@@ -1409,7 +1409,6 @@ void yafrayFileRender_t::writeObject(Object* obj, const vector<VlakRen*> &VLR_li
fci2!=VLR_list.end();++fci2)
{
VlakRen* vlr = *fci2;
- ObjectRen *obr = vlr->obr;
Material* fmat = vlr->mat;
bool EXPORT_VCOL = ((fmat->mode & (MA_VERTEXCOL|MA_VERTEXCOLP))!=0);
string fmatname(fmat->id.name);
@@ -1511,13 +1510,13 @@ void yafrayFileRender_t::writeAllObjects()
{
// first all objects except dupliverts (and main instance object for dups)
- for (map<Object*, vector<VlakRen*> >::const_iterator obi=all_objects.begin();
+ for (map<Object*, yafrayObjectRen >::const_iterator obi=all_objects.begin();
obi!=all_objects.end(); ++obi)
{
// skip main duplivert object if in dupliMtx_list, written later
Object* obj = obi->first;
if (dupliMtx_list.find(string(obj->id.name))!=dupliMtx_list.end()) continue;
- writeObject(obj, obi->second, obj->obmat);
+ writeObject(obj, obi->second.obr, obi->second.faces, obj->obmat);
}
// Now all duplivert objects (if any) as instances of main object
@@ -1537,7 +1536,7 @@ void yafrayFileRender_t::writeAllObjects()
// first object written as normal (but with transform of first duplivert)
Object* obj = dup_srcob[dupMtx->first];
- writeObject(obj, all_objects[obj], obmat);
+ writeObject(obj, all_objects[obj].obr, all_objects[obj].faces, obmat);
// all others instances of first
for (unsigned int curmtx=16;curmtx<dupMtx->second.size();curmtx+=16) { // number of 4x4 matrices
@@ -2018,7 +2017,7 @@ bool yafrayFileRender_t::executeYafray(const string &xmlpath)
{
ostr.str("");
if (re->r.mode & R_BORDER) {
- ostr << command_path << "yafray -c " << re->r.YF_numprocs
+ ostr << command_path << "yafray -c " << re->r.threads
<< " -r " << (2.f*re->r.border.xmin - 1.f)
<< ":" << (2.f*re->r.border.xmax - 1.f)
<< ":" << (2.f*re->r.border.ymin - 1.f)
@@ -2026,7 +2025,7 @@ bool yafrayFileRender_t::executeYafray(const string &xmlpath)
<< " \"" << xmlpath << "\"";
}
else
- ostr << command_path << "yafray -c " << re->r.YF_numprocs << " \"" << xmlpath << "\"";
+ ostr << command_path << "yafray -c " << re->r.threads << " \"" << xmlpath << "\"";
string command = ostr.str();
cout << "COMMAND: " << command << endl;
diff --git a/source/blender/yafray/intern/export_File.h b/source/blender/yafray/intern/export_File.h
index 5d2e0c53a21..0eb1bfec1ed 100644
--- a/source/blender/yafray/intern/export_File.h
+++ b/source/blender/yafray/intern/export_File.h
@@ -18,7 +18,7 @@ class yafrayFileRender_t : public yafrayRender_t
virtual void writeTextures();
virtual void writeShader(const std::string &shader_name, Material* matr, const std::string &facetexname="");
virtual void writeMaterialsAndModulators();
- virtual void writeObject(Object* obj, const std::vector<VlakRen*> &VLR_list, const float obmat[4][4]);
+ virtual void writeObject(Object* obj, ObjectRen *obr, const std::vector<VlakRen*> &VLR_list, const float obmat[4][4]);
virtual void writeAllObjects();
virtual void writeAreaLamp(LampRen* lamp, int num, float iview[4][4]);
virtual void writeLamps();
diff --git a/source/blender/yafray/intern/export_Plugin.cpp b/source/blender/yafray/intern/export_Plugin.cpp
index 16ae2d97f62..db9fb7ccc72 100644
--- a/source/blender/yafray/intern/export_Plugin.cpp
+++ b/source/blender/yafray/intern/export_Plugin.cpp
@@ -1,7 +1,9 @@
#include "export_Plugin.h"
#include <math.h>
+
#include <cstring>
+
using namespace std;
@@ -72,7 +74,7 @@ extern "C" { extern char bprogname[]; }
// add drive character if not in path string, using blender executable location as reference
static void addDrive(string &path)
{
- int sp = path.find_first_of(":");
+ size_t sp = path.find_first_of(":");
if (sp==-1) {
string blpath = bprogname;
sp = blpath.find_first_of(":");
@@ -96,9 +98,12 @@ static string YafrayPath()
string path=find_path();
return path;
#else
- static char *alternative[]=
+ static const char *alternative[]=
{
"/usr/local/lib/",
+#ifdef __x86_64__
+ "/usr/lib64/",
+#endif
"/usr/lib/",
NULL
};
@@ -119,9 +124,12 @@ static string YafrayPluginPath()
#ifdef WIN32
return find_path()+"\\plugins";
#else
- static char *alternative[]=
+ static const char *alternative[]=
{
"/usr/local/lib/yafray",
+#ifdef __x86_64__
+ "/usr/lib64/yafray",
+#endif
"/usr/lib/yafray",
NULL
};
@@ -163,7 +171,9 @@ bool yafrayPluginRender_t::initExport()
corehandle = PIL_dynlib_open((char *)(location + "\\yafraycore.dll").c_str());
if (corehandle==NULL)
{
- cerr << "Error loading yafray plugin: " << PIL_dynlib_get_error_as_string(corehandle) << endl;
+ char *err = PIL_dynlib_get_error_as_string(corehandle);
+ if (err) cerr << "Error loading yafray plugin: " << err << endl;
+ else cerr << "Error loading yafray plugin: Unknown." << endl;
return false;
}
location += "\\yafrayplugin.dll";
@@ -184,7 +194,7 @@ bool yafrayPluginRender_t::initExport()
cerr << "Error loading yafray plugin: " << PIL_dynlib_get_error_as_string(handle) << endl;
return false;
}
- yafrayGate = constructor(re->r.YF_numprocs, YafrayPluginPath());
+ yafrayGate = constructor(re->r.threads, YafrayPluginPath());
cout << "YafRay plugin loaded" << endl;
plugin_loaded = true;
@@ -244,7 +254,7 @@ bool yafrayPluginRender_t::writeRender()
params["bias"] = yafray::parameter_t(re->r.YF_raybias);
params["clamp_rgb"] = yafray::parameter_t((re->r.YF_clamprgb==0) ? "on" : "off");
// lynx request
- params["threads"] = yafray::parameter_t((int)re->r.YF_numprocs);
+ params["threads"] = yafray::parameter_t((int)re->r.threads);
blenderYafrayOutput_t output(re);
yafrayGate->render(params, output);
cout << "render finished" << endl;
@@ -270,7 +280,7 @@ static void adjustPath(string &path)
// if relative, expand to full path
char cpath[MAXPATHLEN];
strcpy(cpath, path.c_str());
- BLI_convertstringcode(cpath, G.sce, 0);
+ BLI_convertstringcode(cpath, G.sce);
path = cpath;
#ifdef WIN32
// add drive char if not there
@@ -774,7 +784,7 @@ void yafrayPluginRender_t::writeShader(const string &shader_name, Material* matr
mparams["input"] = yafray::parameter_t(shader_name + temp);
// blendtype, would have been nice if the order would have been the same as for ramps...
- const string blendtype[9] = {"mix", "mul", "add", "sub", "divide", "darken", "difference", "lighten", "screen"};
+ const string blendtype[MTEX_NUM_BLENDTYPES] = {"mix", "mul", "add", "sub", "divide", "darken", "difference", "lighten", "screen", "hue", "sat", "val", "color"};
mparams["mode"] = yafray::parameter_t(blendtype[(int)mtex->blendtype]);
// texture color (for use with MUL and/or no_rgb etc..)
@@ -1080,7 +1090,7 @@ void yafrayPluginRender_t::writeMaterialsAndModulators()
}
-void yafrayPluginRender_t::genUVcoords(vector<yafray::GFLOAT> &uvcoords, VlakRen *vlr, MTFace* uvc, bool comple)
+void yafrayPluginRender_t::genUVcoords(vector<yafray::GFLOAT> &uvcoords, ObjectRen *obr, VlakRen *vlr, MTFace* uvc, bool comple)
{
if (uvc)
{
@@ -1108,9 +1118,8 @@ void yafrayPluginRender_t::genUVcoords(vector<yafray::GFLOAT> &uvcoords, VlakRen
}
}
-void yafrayPluginRender_t::genVcol(vector<yafray::CFLOAT> &vcol, VlakRen *vlr, bool comple)
+void yafrayPluginRender_t::genVcol(vector<yafray::CFLOAT> &vcol, ObjectRen *obr, VlakRen *vlr, bool comple)
{
- ObjectRen *obr= vlr->obr;
MCol *mcol= RE_vlakren_get_mcol(obr, vlr, obr->actmcol, NULL, 0);
if (mcol)
@@ -1144,10 +1153,9 @@ void yafrayPluginRender_t::genVcol(vector<yafray::CFLOAT> &vcol, VlakRen *vlr, b
void yafrayPluginRender_t::genFace(vector<int> &faces,vector<string> &shaders,vector<int> &faceshader,
vector<yafray::GFLOAT> &uvcoords,vector<yafray::CFLOAT> &vcol,
- map<VertRen*, int> &vert_idx,VlakRen *vlr,
+ map<VertRen*, int> &vert_idx,ObjectRen *obr,VlakRen *vlr,
int has_orco,bool has_uv)
{
- ObjectRen *obr= vlr->obr;
Material* fmat = vlr->mat;
bool EXPORT_VCOL = ((fmat->mode & (MA_VERTEXCOL|MA_VERTEXCOLP))!=0);
string fmatname(fmat->id.name);
@@ -1186,16 +1194,15 @@ void yafrayPluginRender_t::genFace(vector<int> &faces,vector<string> &shaders,ve
faces.push_back(idx1); faces.push_back(idx2); faces.push_back(idx3);
- if(has_uv) genUVcoords(uvcoords, vlr, uvc);
- if (EXPORT_VCOL) genVcol(vcol, vlr);
+ if(has_uv) genUVcoords(uvcoords, obr, vlr, uvc);
+ if (EXPORT_VCOL) genVcol(vcol, obr, vlr);
}
void yafrayPluginRender_t::genCompleFace(vector<int> &faces,/*vector<string> &shaders,*/vector<int> &faceshader,
vector<yafray::GFLOAT> &uvcoords,vector<yafray::CFLOAT> &vcol,
- map<VertRen*, int> &vert_idx,VlakRen *vlr,
+ map<VertRen*, int> &vert_idx,ObjectRen *obr,VlakRen *vlr,
int has_orco,bool has_uv)
{
- ObjectRen *obr= vlr->obr;
Material* fmat = vlr->mat;
bool EXPORT_VCOL = ((fmat->mode & (MA_VERTEXCOL|MA_VERTEXCOLP))!=0);
@@ -1211,12 +1218,12 @@ void yafrayPluginRender_t::genCompleFace(vector<int> &faces,/*vector<string> &sh
faces.push_back(idx1); faces.push_back(idx2); faces.push_back(idx3);
- if (has_uv) genUVcoords(uvcoords, vlr, uvc, true);
- if (EXPORT_VCOL) genVcol(vcol, vlr, true);
+ if (has_uv) genUVcoords(uvcoords, obr, vlr, uvc, true);
+ if (EXPORT_VCOL) genVcol(vcol, obr, vlr, true);
}
void yafrayPluginRender_t::genVertices(vector<yafray::point3d_t> &verts, int &vidx,
- map<VertRen*, int> &vert_idx, VlakRen* vlr, int has_orco, Object* obj)
+ map<VertRen*, int> &vert_idx, ObjectRen *obr, VlakRen* vlr, int has_orco, Object* obj)
{
VertRen* ver;
float tvec[3]; // for back2world transform
@@ -1281,7 +1288,7 @@ void yafrayPluginRender_t::genVertices(vector<yafray::point3d_t> &verts, int &vi
}
}
-void yafrayPluginRender_t::writeObject(Object* obj, const vector<VlakRen*> &VLR_list, const float obmat[4][4])
+void yafrayPluginRender_t::writeObject(Object* obj, ObjectRen *obr, const vector<VlakRen*> &VLR_list, const float obmat[4][4])
{
float mtr[4*4];
mtr[0*4+0]=obmat[0][0]; mtr[0*4+1]=obmat[1][0]; mtr[0*4+2]=obmat[2][0]; mtr[0*4+3]=obmat[3][0];
@@ -1342,8 +1349,7 @@ void yafrayPluginRender_t::writeObject(Object* obj, const vector<VlakRen*> &VLR_
fci!=VLR_list.end();++fci)
{
VlakRen* vlr = *fci;
- ObjectRen *obr = vlr->obr;
- genVertices(verts, vidx, vert_idx, vlr, has_orco, obj);
+ genVertices(verts, vidx, vert_idx, obr, vlr, has_orco, obj);
if(RE_vlakren_get_tface(obr, vlr, obr->actmtface, NULL, 0)) has_uv=true;
}
// all faces using the index list created above
@@ -1355,9 +1361,9 @@ void yafrayPluginRender_t::writeObject(Object* obj, const vector<VlakRen*> &VLR_
fci2!=VLR_list.end();++fci2)
{
VlakRen* vlr = *fci2;
- genFace(faces, shaders, faceshader, uvcoords, vcol, vert_idx, vlr, has_orco, has_uv);
+ genFace(faces, shaders, faceshader, uvcoords, vcol, vert_idx, obr, vlr, has_orco, has_uv);
if (vlr->v4)
- genCompleFace(faces, faceshader, uvcoords, vcol, vert_idx, vlr, has_orco, has_uv);
+ genCompleFace(faces, faceshader, uvcoords, vcol, vert_idx, obr, vlr, has_orco, has_uv);
}
// using the ObjectRen database, contruct a new name if object has a parent.
@@ -1388,13 +1394,13 @@ void yafrayPluginRender_t::writeObject(Object* obj, const vector<VlakRen*> &VLR_
void yafrayPluginRender_t::writeAllObjects()
{
// first all objects except dupliverts (and main instance object for dups)
- for (map<Object*, vector<VlakRen*> >::const_iterator obi=all_objects.begin();
+ for (map<Object*, yafrayObjectRen >::const_iterator obi=all_objects.begin();
obi!=all_objects.end(); ++obi)
{
// skip main duplivert object if in dupliMtx_list, written later
Object* obj = obi->first;
if (dupliMtx_list.find(string(obj->id.name))!=dupliMtx_list.end()) continue;
- writeObject(obj, obi->second, obj->obmat);
+ writeObject(obj, obi->second.obr, obi->second.faces, obj->obmat);
}
// Now all duplivert objects (if any) as instances of main object
@@ -1412,7 +1418,7 @@ void yafrayPluginRender_t::writeAllObjects()
// first object written as normal (but with transform of first duplivert)
Object* obj = dup_srcob[dupMtx->first];
- writeObject(obj, all_objects[obj], obmat);
+ writeObject(obj, all_objects[obj].obr, all_objects[obj].faces, obmat);
// all others instances of first
for (unsigned int curmtx=16;curmtx<dupMtx->second.size();curmtx+=16)
diff --git a/source/blender/yafray/intern/export_Plugin.h b/source/blender/yafray/intern/export_Plugin.h
index 1ce4988a260..660271daf96 100644
--- a/source/blender/yafray/intern/export_Plugin.h
+++ b/source/blender/yafray/intern/export_Plugin.h
@@ -35,7 +35,7 @@ class yafrayPluginRender_t : public yafrayRender_t
virtual void writeTextures();
virtual void writeShader(const std::string &shader_name, Material* matr, const std::string &facetexname="");
virtual void writeMaterialsAndModulators();
- virtual void writeObject(Object* obj,
+ virtual void writeObject(Object* obj, ObjectRen *obr,
const std::vector<VlakRen*> &VLR_list, const float obmat[4][4]);
virtual void writeAllObjects();
virtual void writeAreaLamp(LampRen* lamp, int num, float iview[4][4]);
@@ -48,18 +48,18 @@ class yafrayPluginRender_t : public yafrayRender_t
virtual bool initExport();
virtual bool finishExport();
- void genUVcoords(std::vector<yafray::GFLOAT> &uvcoords,VlakRen *vlr,MTFace* uvc, bool comple=false);
- void genVcol(std::vector<yafray::CFLOAT> &vcol, VlakRen *vlr, bool comple=false);
+ void genUVcoords(std::vector<yafray::GFLOAT> &uvcoords,ObjectRen *obr,VlakRen *vlr,MTFace* uvc, bool comple=false);
+ void genVcol(std::vector<yafray::CFLOAT> &vcol, ObjectRen *obr, VlakRen *vlr, bool comple=false);
void genFace(std::vector<int> &faces,std::vector<std::string> &shaders,std::vector<int> &faceshader,
std::vector<yafray::GFLOAT> &uvcoords,std::vector<yafray::CFLOAT> &vcol,
- std::map<VertRen*, int> &vert_idx,VlakRen *vlr,
+ std::map<VertRen*, int> &vert_idx,ObjectRen *obr,VlakRen *vlr,
int has_orco,bool has_uv);
void genCompleFace(std::vector<int> &faces,/*std::vector<std::string> &shaders,*/std::vector<int> &faceshader,
std::vector<yafray::GFLOAT> &uvcoords,std::vector<yafray::CFLOAT> &vcol,
- std::map<VertRen*, int> &vert_idx,VlakRen *vlr,
+ std::map<VertRen*, int> &vert_idx,ObjectRen *obr, VlakRen *vlr,
int has_orco,bool has_uv);
void genVertices(std::vector<yafray::point3d_t> &verts, int &vidx,
- std::map<VertRen*, int> &vert_idx, VlakRen* vlr, int has_orco, Object* obj);
+ std::map<VertRen*, int> &vert_idx, ObjectRen *obr, VlakRen* vlr, int has_orco, Object* obj);
};
class blenderYafrayOutput_t : public yafray::colorOutput_t
diff --git a/source/blender/yafray/intern/yafray_Render.cpp b/source/blender/yafray/intern/yafray_Render.cpp
index 90229575235..01da4683d71 100644
--- a/source/blender/yafray/intern/yafray_Render.cpp
+++ b/source/blender/yafray/intern/yafray_Render.cpp
@@ -7,6 +7,7 @@
#include "yafray_Render.h"
#include <math.h>
+
#include <cstring>
using namespace std;
@@ -142,15 +143,15 @@ bool yafrayRender_t::getAllMatTexObs()
// Make list of faces per object, ignore <3 vert faces, duplicate vertex sorting done later.
// ignore null object pointers.
// Also make list of facetexture images (material 'TexFace').
- if (vlr->obr->ob) {
+ if (obr->ob) {
int nv = 0; // number of vertices
MTFace *tface;
if (vlr->v4) nv=4; else if (vlr->v3) nv=3;
if (nv) {
- ObjectRen *obr= vlr->obr;
renderobs[obr->ob->id.name] = obr->ob;
- all_objects[obr->ob].push_back(vlr);
+ all_objects[obr->ob].obr= obr;
+ all_objects[obr->ob].faces.push_back(vlr);
tface= RE_vlakren_get_tface(obr, vlr, obr->actmtface, NULL, 0);
if (tface && tface->tpage) {
@@ -185,7 +186,7 @@ bool yafrayRender_t::getAllMatTexObs()
// in all_objects with the name given in dupliMtx_list
if (!dupliMtx_list.empty()) {
- for (map<Object*, vector<VlakRen*> >::const_iterator obn=all_objects.begin();
+ for (map<Object*, yafrayObjectRen>::const_iterator obn=all_objects.begin();
obn!=all_objects.end();++obn)
{
Object* obj = obn->first;
diff --git a/source/blender/yafray/intern/yafray_Render.h b/source/blender/yafray/intern/yafray_Render.h
index 0debb0009fa..43d2c6c602a 100644
--- a/source/blender/yafray/intern/yafray_Render.h
+++ b/source/blender/yafray/intern/yafray_Render.h
@@ -52,6 +52,12 @@ extern void error (char *fmt, ...);
#include <vector>
#include <set>
+class yafrayObjectRen {
+ public:
+ std::vector<VlakRen*> faces;
+ ObjectRen *obr;
+};
+
class yafrayRender_t
{
public:
@@ -72,7 +78,7 @@ class yafrayRender_t
bool hasworld;
- std::map<Object*, std::vector<VlakRen*> > all_objects;
+ std::map<Object*, yafrayObjectRen> all_objects;
std::map<std::string, Material*> used_materials;
std::map<std::string, MTex*> used_textures;
std::map<std::string, std::vector<float> > dupliMtx_list;
@@ -86,7 +92,7 @@ class yafrayRender_t
virtual void writeTextures()=0;
virtual void writeShader(const std::string &shader_name, Material* matr, const std::string &facetexname)=0;
virtual void writeMaterialsAndModulators()=0;
- virtual void writeObject(Object* obj, const std::vector<VlakRen*> &VLR_list, const float obmat[4][4])=0;
+ virtual void writeObject(Object* obj, ObjectRen *obr, const std::vector<VlakRen*> &VLR_list, const float obmat[4][4])=0;
virtual void writeAllObjects()=0;
virtual void writeLamps()=0;
virtual void writeCamera()=0;