Merged changes in the trunk up to revision 42116.
authorTamito Kajiyama <rd6t-kjym@asahi-net.or.jp>
Sat, 26 Nov 2011 13:11:55 +0000 (13:11 +0000)
committerTamito Kajiyama <rd6t-kjym@asahi-net.or.jp>
Sat, 26 Nov 2011 13:11:55 +0000 (13:11 +0000)
131 files changed:
1  2 
build_files/buildbot/master.cfg
build_files/buildbot/slave_pack.py
build_files/scons/tools/Blender.py
build_files/scons/tools/btools.py
doc/python_api/examples/bge.texture.1.py
doc/python_api/sphinx_doc_gen.py
extern/libmv/SConscript
intern/cycles/SConscript
intern/cycles/blender/CMakeLists.txt
intern/cycles/blender/addon/properties.py
intern/cycles/blender/addon/ui.py
intern/cycles/blender/addon/xml.py
release/scripts/modules/addon_utils.py
release/scripts/modules/bpy/utils.py
release/scripts/modules/console/complete_calltip.py
release/scripts/presets/camera/Nikon_D3S.py
release/scripts/startup/bl_operators/clip.py
release/scripts/startup/bl_ui/properties_data_modifier.py
release/scripts/startup/bl_ui/properties_render.py
release/scripts/startup/bl_ui/space_clip.py
release/scripts/startup/bl_ui/space_view3d.py
source/blender/blenfont/intern/blf_dir.c
source/blender/blenkernel/BKE_DerivedMesh.h
source/blender/blenkernel/BKE_image.h
source/blender/blenkernel/BKE_material.h
source/blender/blenkernel/BKE_particle.h
source/blender/blenkernel/BKE_pointcache.h
source/blender/blenkernel/intern/CCGSubSurf.c
source/blender/blenkernel/intern/DerivedMesh.c
source/blender/blenkernel/intern/blender.c
source/blender/blenkernel/intern/curve.c
source/blender/blenkernel/intern/dynamicpaint.c
source/blender/blenkernel/intern/image.c
source/blender/blenkernel/intern/material.c
source/blender/blenkernel/intern/movieclip.c
source/blender/blenkernel/intern/object.c
source/blender/blenkernel/intern/packedFile.c
source/blender/blenkernel/intern/particle.c
source/blender/blenkernel/intern/pointcache.c
source/blender/blenkernel/intern/scene.c
source/blender/blenkernel/intern/sequencer.c
source/blender/blenkernel/intern/subsurf_ccg.c
source/blender/blenkernel/intern/text.c
source/blender/blenlib/intern/DLRB_tree.c
source/blender/blenlib/intern/path_util.c
source/blender/blenlib/intern/pbvh.c
source/blender/blenlib/intern/storage.c
source/blender/blenlib/intern/winstuff.c
source/blender/blenloader/intern/readfile.c
source/blender/blenloader/intern/readfile.h
source/blender/blenloader/intern/writefile.c
source/blender/editors/gpencil/drawgpencil.c
source/blender/editors/gpencil/gpencil_paint.c
source/blender/editors/include/UI_interface.h
source/blender/editors/interface/interface.c
source/blender/editors/interface/interface_draw.c
source/blender/editors/interface/interface_handlers.c
source/blender/editors/interface/interface_icons.c
source/blender/editors/interface/interface_regions.c
source/blender/editors/interface/interface_style.c
source/blender/editors/mesh/editmesh_tools.c
source/blender/editors/object/object_add.c
source/blender/editors/physics/physics_fluid.c
source/blender/editors/physics/physics_pointcache.c
source/blender/editors/render/render_opengl.c
source/blender/editors/render/render_shading.c
source/blender/editors/screen/screendump.c
source/blender/editors/space_console/space_console.c
source/blender/editors/space_file/filelist.c
source/blender/editors/space_file/fsmenu.c
source/blender/editors/space_image/image_ops.c
source/blender/editors/space_nla/nla_buttons.c
source/blender/editors/space_node/node_draw.c
source/blender/editors/space_outliner/outliner_tools.c
source/blender/editors/space_sequencer/sequencer_draw.c
source/blender/editors/space_text/text_ops.c
source/blender/editors/space_view3d/drawobject.c
source/blender/editors/space_view3d/view3d_buttons.c
source/blender/editors/space_view3d/view3d_draw.c
source/blender/editors/transform/transform.c
source/blender/editors/util/ed_util.c
source/blender/editors/uvedit/uvedit_draw.c
source/blender/freestyle/intern/blender_interface/BlenderStrokeRenderer.cpp
source/blender/freestyle/intern/python/BPy_Convert.cpp
source/blender/freestyle/intern/python/BPy_Freestyle.cpp
source/blender/gpu/CMakeLists.txt
source/blender/imbuf/intern/IMB_indexer.h
source/blender/imbuf/intern/indexer.c
source/blender/imbuf/intern/jpeg.c
source/blender/makesdna/DNA_curve_types.h
source/blender/makesdna/DNA_scene_types.h
source/blender/makesdna/DNA_userdef_types.h
source/blender/makesdna/intern/makesdna.c
source/blender/makesrna/RNA_access.h
source/blender/makesrna/RNA_define.h
source/blender/makesrna/RNA_enum_types.h
source/blender/makesrna/intern/rna_define.c
source/blender/makesrna/intern/rna_image_api.c
source/blender/makesrna/intern/rna_main_api.c
source/blender/makesrna/intern/rna_mesh.c
source/blender/makesrna/intern/rna_object_force.c
source/blender/makesrna/intern/rna_scene.c
source/blender/makesrna/intern/rna_tracking.c
source/blender/makesrna/intern/rna_userdef.c
source/blender/modifiers/intern/MOD_fluidsim_util.c
source/blender/nodes/composite/nodes/node_composite_mixrgb.c
source/blender/nodes/shader/nodes/node_shader_mixRgb.c
source/blender/nodes/texture/nodes/node_texture_bricks.c
source/blender/nodes/texture/nodes/node_texture_mixRgb.c
source/blender/nodes/texture/nodes/node_texture_proc.c
source/blender/nodes/texture/nodes/node_texture_texture.c
source/blender/python/intern/bpy_interface.c
source/blender/python/intern/bpy_rna.c
source/blender/python/mathutils/mathutils_Euler.c
source/blender/python/mathutils/mathutils_Matrix.c
source/blender/python/mathutils/mathutils_Quaternion.c
source/blender/render/extern/include/RE_pipeline.h
source/blender/render/intern/source/pipeline.c
source/blender/render/intern/source/pixelshading.c
source/blender/render/intern/source/render_texture.c
source/blender/render/intern/source/shadeoutput.c
source/blender/windowmanager/intern/wm_files.c
source/blender/windowmanager/intern/wm_gesture.c
source/blender/windowmanager/intern/wm_operators.c
source/blenderplayer/bad_level_call_stubs/stubs.c
source/creator/CMakeLists.txt
source/creator/creator.c
source/gameengine/GamePlayer/ghost/GPG_ghost.cpp
source/gameengine/Ketsji/KX_PythonInit.cpp
source/gameengine/VideoTexture/Texture.cpp
source/tests/pep8.py

index 5aa5a43abf75785768ea9330572f083f727cfe09,5aa5a43abf75785768ea9330572f083f727cfe09..23751f7dcd49a6a072c58a70fac979580cb2d791
@@@ -75,14 -75,14 +75,14 @@@ def svn_step(branch='')
          return SVN(baseURL='https://svn.blender.org/svnroot/bf-blender/%%BRANCH%%/blender', mode='update', defaultBranch='trunk', workdir='blender')
  
  
--def lib_svn_step(dir):
--    return SVN(name='lib svn', baseURL='https://svn.blender.org/svnroot/bf-blender/%%BRANCH%%/lib/' + dir, mode='update', defaultBranch='trunk', workdir='lib/' + dir)
++def lib_svn_step(libdir):
++    return SVN(name='lib svn', baseURL='https://svn.blender.org/svnroot/bf-blender/%%BRANCH%%/lib/' + libdir, mode='update', defaultBranch='trunk', workdir='lib/' + libdir)
  
  # generic builder
  
  
--def generic_builder(id, libdir='', branch=''):
--    filename = 'buildbot_upload_' + id + '.zip'
++def generic_builder(idname, libdir='', branch=''):
++    filename = 'buildbot_upload_' + idname + '.zip'
      compile_script = '../blender/build_files/buildbot/slave_compile.py'
      test_script = '../blender/build_files/buildbot/slave_test.py'
      pack_script = '../blender/build_files/buildbot/slave_pack.py'
      if libdir != '':
          f.addStep(lib_svn_step(libdir))
  
--    f.addStep(Compile(command=['python', compile_script, id]))
--    f.addStep(Test(command=['python', test_script, id]))
--    f.addStep(ShellCommand(name='package', command=['python', pack_script, id, branch], description='packaging', descriptionDone='packaged'))
--    if id.find('cmake') != -1:
++    f.addStep(Compile(command=['python', compile_script, idname]))
++    f.addStep(Test(command=['python', test_script, idname]))
++    f.addStep(ShellCommand(name='package', command=['python', pack_script, idname, branch], description='packaging', descriptionDone='packaged'))
++    if 'cmake' in idname:
          f.addStep(FileUpload(name='upload', slavesrc='buildbot_upload.zip', masterdest=filename, maxsize=100 * 1024 * 1024))
      else:
          f.addStep(FileUpload(name='upload', slavesrc='buildbot_upload.zip', masterdest=filename, maxsize=100 * 1024 * 1024, workdir='install'))
index af8d99893b4409687529e9fd984e5b2ed2864dc6,af8d99893b4409687529e9fd984e5b2ed2864dc6..94640803aae8e564d86b0a565afaeb13606c091a
@@@ -84,12 -84,12 +84,12 @@@ if builder.find('scons') != -1
          sys.exit(retcode)
  
  # clean release directory if it already exists
--dir = 'release'
++release_dir = 'release'
  
--if os.path.exists(dir):
--    for f in os.listdir(dir):
--        if os.path.isfile(os.path.join(dir, f)):
--            os.remove(os.path.join(dir, f))
++if os.path.exists(release_dir):
++    for f in os.listdir(release_dir):
++        if os.path.isfile(os.path.join(release_dir, f)):
++            os.remove(os.path.join(release_dir, f))
  
  # create release package
  try:
@@@ -99,16 -99,16 +99,16 @@@ except Exception, ex
      sys.exit(1)
  
  # find release directory, must exist this time
--if not os.path.exists(dir):
--    sys.stderr.write("Failed to find release directory.\n")
++if not os.path.exists(release_dir):
++    sys.stderr.write("Failed to find release directory %r.\n" % release_dir)
      sys.exit(1)
  
  # find release package
  file = None
  filepath = None
  
--for f in os.listdir(dir):
--    rf = os.path.join(dir, f)
++for f in os.listdir(release_dir):
++    rf = os.path.join(release_dir, f)
      if os.path.isfile(rf) and f.startswith('blender'):
          file = f
          filepath = rf
index 809f197c8632af97e94a85dc023a4b2a079362e3,38cd960ebe15f4595b34987ca275037789c65ed1..a63dfaa3fc92f80c52011781b546e5f2a11e8cb6
@@@ -316,23 -316,14 +316,14 @@@ def propose_priorities()
  def creator(env):
      sources = ['creator.c']# + Blender.buildinfo(env, "dynamic") + Blender.resources
  
 -    incs = ['#/intern/guardedalloc', '#/source/blender/blenlib', '#/source/blender/blenkernel', '#/source/blender/editors/include', '#/source/blender/blenloader', '#/source/blender/imbuf', '#/source/blender/renderconverter', '#/source/blender/render/extern/include', '#/source/blender/windowmanager', '#/source/blender/makesdna', '#/source/blender/makesrna', '#/source/gameengine/BlenderRoutines', '#/extern/glew/include', '#/source/blender/gpu', env['BF_OPENGL_INC']]
 +    incs = ['#/intern/guardedalloc', '#/source/blender/blenlib', '#/source/blender/blenkernel', '#/source/blender/editors/include', '#/source/blender/blenloader', '#/source/blender/imbuf', '#/source/blender/renderconverter', '#/source/blender/render/extern/include', '#/source/blender/windowmanager', '#/source/blender/makesdna', '#/source/blender/makesrna', '#/source/gameengine/BlenderRoutines', '#/extern/glew/include', '#/source/blender/gpu', '#/source/blender/freestyle', env['BF_OPENGL_INC']]
  
      defs = []
-     if env['WITH_BF_QUICKTIME']:
-         incs.append(env['BF_QUICKTIME_INC'])
-         defs.append('WITH_QUICKTIME')
  
      if env['WITH_BF_BINRELOC']:
          incs.append('#/extern/binreloc/include')
          defs.append('WITH_BINRELOC')
  
-     if env['WITH_BF_OPENEXR']:
-         defs.append('WITH_OPENEXR')
-     if env['WITH_BF_TIFF']:
-         defs.append('WITH_TIFF')
      if env['WITH_BF_SDL']:
          defs.append('WITH_SDL')
  
index 4c826b12e89b850f094913d05cd57a5602b5efad,4c826b12e89b850f094913d05cd57a5602b5efad..1ddbfcb96082332980b56f6195f3846e640e021d
@@@ -544,6 -544,6 +544,7 @@@ def read_opts(env, cfg, args)
  
      localopts.AddVariables(
          (BoolVariable('WITH_BF_CYCLES', 'Build with the Cycles engine', True)),
++        (BoolVariable('WITH_BF_CYCLES_BINARIES', 'Build with precompiled CUDA binaries', False)),
  
          (BoolVariable('WITH_BF_OIIO', 'Build with OpenImageIO', False)),
          (BoolVariable('WITH_BF_STATICOIIO', 'Staticly link to OpenImageIO', False)),
index 4be6f51de67cf2aefed4333f3f15e7bdcfe891ec,4be6f51de67cf2aefed4333f3f15e7bdcfe891ec..918ffc9772d66e9a8ae33d09841588c424651b5a
@@@ -11,13 -11,13 +11,13 @@@ from bge import textur
  
  def createTexture(cont):
      """Create a new Dynamic Texture"""
--    object = cont.owner
++    obj = cont.owner
  
      # get the reference pointer (ID) of the internal texture
--    ID = texture.materialID(object, 'IMoriginal.png')
++    ID = texture.materialID(obj, 'IMoriginal.png')
  
      # create a texture object
--    object_texture = texture.Texture(object, ID)
++    object_texture = texture.Texture(obj, ID)
  
      # create a new source with an external image
      url = logic.expandPath("//newtexture.jpg")
index 4959fc8a664a665186c333ba13268a070f1c3b68,fc17b9a24a5ce7d9d1479d7af911dc90c72152fd..0a07e03b9ae7c627a922746f92cd548952823206
@@@ -87,7 -87,6 +87,7 @@@ else
          "gpu",
          "mathutils",
          "mathutils.geometry",
 +        "Freestyle",
      )
  
      FILTER_BPY_TYPES = ("bpy_struct", "Operator", "ID")  # allow
@@@ -111,6 -110,6 +111,12 @@@ INFO_DOCS = 
      ("info_gotcha.rst", "Gotcha's: some of the problems you may come up against when writing scripts"),
      )
  
++# only support for properties atm.
++RNA_BLACKLIST = {
++    # messes up PDF!, really a bug but for now just workaround.
++    "UserPreferencesSystem": {"language", },
++    }
++
  
  # -----------------------------------------------------------------------------
  # configure compile time options
@@@ -132,7 -131,6 +138,7 @@@ import rna_inf
  ClassMethodDescriptorType = type(dict.__dict__['fromkeys'])
  MethodDescriptorType = type(dict.get)
  GetSetDescriptorType = type(int.real)
 +StaticMethodType = type(staticmethod(lambda: None))
  from types import MemberDescriptorType
  
  EXAMPLE_SET = set()
@@@ -555,12 -553,6 +561,12 @@@ def pymodule2sphinx(BASEPATH, module_na
              if type(descr) == GetSetDescriptorType:
                  py_descr2sphinx("   ", fw, descr, module_name, type_name, key)
  
 +        for key, descr in descr_items:
 +            if type(descr) == StaticMethodType:
 +                descr = getattr(value, key)
 +                write_indented_lines("   ", fw, descr.__doc__ or "Undocumented", False)
 +                fw("\n")
 +
          fw("\n\n")
  
      file.close()
@@@ -765,22 -757,22 +771,23 @@@ def pyrna2sphinx(BASEPATH)
          fw = file.write
  
          base_id = getattr(struct.base, "identifier", "")
++        struct_id = struct.identifier
  
          if _BPY_STRUCT_FAKE:
              if not base_id:
                  base_id = _BPY_STRUCT_FAKE
  
          if base_id:
--            title = "%s(%s)" % (struct.identifier, base_id)
++            title = "%s(%s)" % (struct_id, base_id)
          else:
--            title = struct.identifier
++            title = struct_id
  
          write_title(fw, title, "=")
  
          fw(".. module:: bpy.types\n\n")
  
          # docs first?, ok
--        write_example_ref("", fw, "bpy.types.%s" % struct.identifier)
++        write_example_ref("", fw, "bpy.types.%s" % struct_id)
  
          base_ids = [base.identifier for base in struct.get_bases()]
  
                  base_id = _BPY_STRUCT_FAKE
  
          if base_id:
--            fw(".. class:: %s(%s)\n\n" % (struct.identifier, base_id))
++            fw(".. class:: %s(%s)\n\n" % (struct_id, base_id))
          else:
--            fw(".. class:: %s\n\n" % struct.identifier)
++            fw(".. class:: %s\n\n" % struct_id)
  
          fw("   %s\n\n" % struct.description)
  
          sorted_struct_properties = struct.properties[:]
          sorted_struct_properties.sort(key=lambda prop: prop.identifier)
  
++        # support blacklisting props
++        struct_blacklist = RNA_BLACKLIST.get(struct_id, ())
++
          for prop in sorted_struct_properties:
++
++            # support blacklisting props
++            if prop.identifier in struct_blacklist:
++                continue
++
              type_descr = prop.get_type_description(class_fmt=":class:`%s`", collection_id=_BPY_PROP_COLLECTION_ID)
              # readonly properties use "data" directive, variables properties use "attribute" directive
              if 'readonly' in type_descr:
                          descr = prop.name
                      fw("         `%s`, %s, %s\n\n" % (prop.identifier, descr, type_descr))
  
--            write_example_ref("      ", fw, "bpy.types." + struct.identifier + "." + func.identifier)
++            write_example_ref("      ", fw, "bpy.types." + struct_id + "." + func.identifier)
  
              fw("\n")
  
          py_func = None
  
          for identifier, py_func in py_funcs:
--            py_c_func2sphinx("   ", fw, "bpy.types", struct.identifier, identifier, py_func, is_class=True)
++            py_c_func2sphinx("   ", fw, "bpy.types", struct_id, identifier, py_func, is_class=True)
  
          lines = []
  
              fw("\n")
  
          # docs last?, disable for now
--        # write_example_ref("", fw, "bpy.types.%s" % struct.identifier)
++        # write_example_ref("", fw, "bpy.types.%s" % struct_id)
          file.close()
  
      if "bpy.types" not in EXCLUDE_MODULES:
@@@ -1183,8 -1175,6 +1198,8 @@@ def rna2sphinx(BASEPATH)
          fw("   mathutils.rst\n\n")
      if "mathutils.geometry" not in EXCLUDE_MODULES:
          fw("   mathutils.geometry.rst\n\n")
 +    if "Freestyle" not in EXCLUDE_MODULES:
 +        fw("   Freestyle.rst\n\n")
      if "bgl" not in EXCLUDE_MODULES:
          fw("   bgl.rst\n\n")
      if "blf" not in EXCLUDE_MODULES:
          import mathutils.geometry as module
          pymodule2sphinx(BASEPATH, "mathutils.geometry", module, "Geometry Utilities")
  
 +    if "Freestyle" not in EXCLUDE_MODULES:
 +        import Freestyle as module
 +        pymodule2sphinx(BASEPATH, "Freestyle", module, "Freestyle Data Types & Operators")
 +
      if "blf" not in EXCLUDE_MODULES:
          import blf as module
          pymodule2sphinx(BASEPATH, "blf", module, "Font Drawing")
diff --combined extern/libmv/SConscript
index 60705e913f78b5ae51561e5fcc6c4d7a9f077f74,60705e913f78b5ae51561e5fcc6c4d7a9f077f74..9c134934fa0f81e60a623ba1285cbd1c2d689d87
@@@ -46,16 -46,16 +46,16 @@@ if env['OURPLATFORM'] in ('win32-vc', '
              defs.append('NDEBUG')
      else:
          if not env['BF_DEBUG']:
--            cflags_libmv = Split(env['REL_CFLAGS'])
--            ccflags_libmv = Split(env['REL_CCFLAGS'])
--            cxxflags_libmv = Split(env['REL_CXXFLAGS'])
++            cflags_libmv += Split(env['REL_CFLAGS'])
++            ccflags_libmv += Split(env['REL_CCFLAGS'])
++            cxxflags_libmv += Split(env['REL_CXXFLAGS'])
  else:
      src += env.Glob("third_party/glog/src/*.cc")
      incs += ' ./third_party/glog/src'
      if not env['BF_DEBUG']:
--        cflags_libmv = Split(env['REL_CFLAGS'])
--        ccflags_libmv = Split(env['REL_CCFLAGS'])
--        cxxflags_libmv = Split(env['REL_CXXFLAGS'])
++        cflags_libmv += Split(env['REL_CFLAGS'])
++        ccflags_libmv += Split(env['REL_CCFLAGS'])
++        cxxflags_libmv += Split(env['REL_CXXFLAGS'])
  
  incs += ' ./third_party/ssba ./third_party/ldl/Include ../colamd/Include'
  
diff --combined intern/cycles/SConscript
index 4d45a6875a97f097b0c5d1912a09fd7f88c5ead4,4d45a6875a97f097b0c5d1912a09fd7f88c5ead4..ecd22f654e8fc6030ebdac5bf9b9ac35c8d9fe22
@@@ -22,6 -22,6 +22,9 @@@ defs.append('WITH_OPENCL'
  defs.append('WITH_MULTI')
  defs.append('WITH_CUDA')
  
++if env['WITH_BF_CYCLES_BINARIES']:
++    defs.append('WITH_CUDA_BINARIES')
++
  incs.extend('. bvh render device kernel kernel/osl kernel/svm util subd'.split())
  incs.extend('#intern/guardedalloc #source/blender/makesrna #source/blender/makesdna'.split())
  incs.extend('#source/blender/blenloader ../../source/blender/makesrna/intern'.split())
index e81f02f2090f7287520feb848ba22e5ba4989b99,e81f02f2090f7287520feb848ba22e5ba4989b99..b96048acf054fb1db502b5e21465dc759cb0afbb
@@@ -6,7 -6,7 +6,7 @@@ set(IN
        ../kernel/svm
        ../util
        ../subd
--      ../../../intern/guardedalloc
++      ../../guardedalloc
        ../../../source/blender/makesdna
        ../../../source/blender/makesrna
        ../../../source/blender/blenloader
index 0c7deb01ed8c4ab25edee700fc734edc37796886,0c7deb01ed8c4ab25edee700fc734edc37796886..95f898f3ca5482b2c435279a1c4c0c4826e8633d
  # <pep8 compliant>
  
  import bpy
--from bpy.props import *
++from bpy.props import (BoolProperty,
++                       EnumProperty,
++                       FloatProperty,
++                       IntProperty,
++                       PointerProperty)
  
  import math
  
index f3ed3b677fb5f35055181c615aef2e4b16781cdd,f3ed3b677fb5f35055181c615aef2e4b16781cdd..224e44c287aa2c0785006d0f14da413aa3435bae
@@@ -349,7 -349,7 +349,7 @@@ def find_node(material, nodetype)
          ntree = material.node_tree
  
          for node in ntree.nodes:
--            if hasattr(node, 'type') and node.type == nodetype:
++            if getattr(node, "type", None) == nodetype:
                  return node
  
      return None
@@@ -363,14 -363,14 +363,14 @@@ def find_node_input(node, name)
      return None
  
  
--def panel_node_draw(layout, id, output_type, input_name):
--    if not id.node_tree:
--        layout.prop(id, "use_nodes", icon='NODETREE')
++def panel_node_draw(layout, id_data, output_type, input_name):
++    if not id_data.node_tree:
++        layout.prop(id_data, "use_nodes", icon='NODETREE')
          return False
  
--    ntree = id.node_tree
++    ntree = id_data.node_tree
  
--    node = find_node(id, output_type)
++    node = find_node(id_data, output_type)
      if not node:
          layout.label(text="No output node.")
      else:
index e64023f046b8031a11c85e7db7861daa56f9ce5f,e64023f046b8031a11c85e7db7861daa56f9ce5f..f17051d92dc18a5d97d0eb31576600301953bbdd
@@@ -61,12 -61,12 +61,12 @@@ class ExportCyclesXML(bpy.types.Operato
  
          # get mesh
          scene = context.scene
--        object = context.object
++        obj = context.object
  
--        if not object:
++        if not obj:
              raise Exception("No active object")
  
--        mesh = object.to_mesh(scene, True, 'PREVIEW')
++        mesh = obj.to_mesh(scene, True, 'PREVIEW')
  
          if not mesh:
              raise Exception("No mesh data in active object")
index 1bd218ad92aa7cf6192115e221cd351a76d5dde3,bcde4ce1e18d36451e947e5d6376236934953831..de662b47c4dc65444724c6f38d7daccefd34c22d
@@@ -146,7 -146,10 +146,10 @@@ def modules(module_cache)
      for path in path_list:
  
          # force all contrib addons to be 'TESTING'
-         force_support = 'TESTING' if path.endswith("addons_contrib") else None
+         if path.endswith("addons_contrib") or path.endswith("addons_extern"):
+             force_support = 'TESTING'
+         else:
+             force_support = None
  
          for mod_name, mod_path in _bpy.path.module_names(path):
              modules_stale -= {mod_name}
                      mod = None
  
              if mod is None:
--                mod = fake_module(mod_name, mod_path, force_support=force_support)
++                mod = fake_module(mod_name,
++                                  mod_path,
++                                  force_support=force_support)
                  if mod:
                      module_cache[mod_name] = mod
  
index 6eb16bd7e7ac53cbc719ad3c83c6e0fdf8ae9c9a,6eb16bd7e7ac53cbc719ad3c83c6e0fdf8ae9c9a..cf3e92bdcbfe7834864bc5b7aa821e0fc5798e63
@@@ -263,7 -263,7 +263,7 @@@ def user_script_path()
          return None
  
  
--def script_paths(subdir=None, user_pref=True, all=False):
++def script_paths(subdir=None, user_pref=True, check_all=False):
      """
      Returns a list of valid script paths.
  
      :type subdir: string
      :arg user_pref: Include the user preference script path.
      :type user_pref: bool
--    :arg all: Include local, user and system paths rather just the paths
++    :arg check_all: Include local, user and system paths rather just the paths
         blender uses.
--    :type all: bool
++    :type check_all: bool
      :return: script paths.
      :rtype: list
      """
      else:
          user_script_path = None
  
--    if all:
++    if check_all:
          # all possible paths
          base_paths = tuple(_os.path.join(resource_path(res), "scripts")
                             for res in ('LOCAL', 'USER', 'SYSTEM'))
@@@ -343,7 -343,7 +343,7 @@@ def preset_paths(subdir)
      :rtype: list
      """
      dirs = []
--    for path in script_paths("presets", all=True):
++    for path in script_paths("presets", check_all=True):
          directory = _os.path.join(path, subdir)
          if not directory.startswith(path):
              raise Exception("invalid subdir given %r" % subdir)
@@@ -432,9 -432,9 +432,9 @@@ def keyconfig_set(filepath)
      keyconfigs_old = keyconfigs[:]
  
      try:
--        file = open(filepath)
--        exec(compile(file.read(), filepath, 'exec'), {"__file__": filepath})
--        file.close()
++        keyfile = open(filepath)
++        exec(compile(keyfile.read(), filepath, 'exec'), {"__file__": filepath})
++        keyfile.close()
      except:
          import traceback
          traceback.print_exc()
index 29187297707eafb96d7ee5f3c6ec7efc9f043a04,29187297707eafb96d7ee5f3c6ec7efc9f043a04..3404bb792faad8b92583cb557ce1cd34df78ef18
@@@ -72,7 -72,7 +72,7 @@@ def reduce_spaces(text)
      return RE_SPACE.sub(' ', text)
  
  
--def get_doc(object):
++def get_doc(obj):
      """Get the doc string or comments for an object.
  
      :param object: object
@@@ -82,7 -82,7 +82,7 @@@
      >>> get_doc(abs)
      'abs(number) -> number\\n\\nReturn the absolute value of the argument.'
      """
--    result = inspect.getdoc(object) or inspect.getcomments(object)
++    result = inspect.getdoc(obj) or inspect.getcomments(obj)
      return result and RE_EMPTY_LINE.sub('', result.rstrip()) or ''
  
  
index 59c4f88251d39cd4b1245f9fc23b0aa1cf916dc3,5b7245654819bef5be4fd14cf171bfa8bf6b7e00..269871b72305b5e5afc12892c5b20bad2330e2d2
  # <pep8 compliant>
  import bpy
  import os
--import shutil
  from bpy.types import Operator
- from bpy_extras.io_utils import unpack_list
 -from bpy_extras.io_utils import unpack_list, unpack_face_list
+ from mathutils import Vector, Matrix
+ def CLIP_spacees_walk(context, all_screens, tarea, tspace, callback, *args):
+     screens = bpy.data.screens if all_screens else [context.screen]
+     for screen in screens:
+         for area in screen.areas:
+             if area.type == tarea:
+                 for space in area.spaces:
+                     if space.type == tspace:
+                         callback(space, *args)
+ def CLIP_set_viewport_background(context, all_screens, clip, clip_user):
+     def set_background(space_v3d, clip, user):
+         bgpic = None
+         for x in space_v3d.background_images:
+             if x.source == 'MOVIE':
+                 bgpic = x
+                 break
+         if not bgpic:
+             bgpic = space_v3d.background_images.new()
+         bgpic.source = 'MOVIE'
+         bgpic.clip = clip
+         bgpic.clip_user.proxy_render_size = user.proxy_render_size
+         bgpic.clip_user.use_render_undistorted = True
+         bgpic.use_camera_clip = False
+         bgpic.view_axis = 'CAMERA'
+         space_v3d.show_background_images = True
+     CLIP_spacees_walk(context, all_screens, 'VIEW_3D', 'VIEW_3D',
+                       set_background, clip, clip_user)
  
  
  def CLIP_track_view_selected(sc, track):
@@@ -51,8 -89,8 +87,8 @@@ class CLIP_OT_track_to_empty(Operator)
  
          ob = bpy.data.objects.new(name=track.name, object_data=None)
          ob.select = True
-         bpy.context.scene.objects.link(ob)
-         bpy.context.scene.objects.active = ob
+         context.scene.objects.link(ob)
+         context.scene.objects.active = ob
  
          for con in ob.constraints:
              if con.type == 'FOLLOW_TRACK':
          return {'FINISHED'}
  
  
- class CLIP_OT_tracks_to_mesh(Operator):
-     """Create vertex cloud using coordinates of tracks"""
+ class CLIP_OT_bundles_to_mesh(Operator):
+     """Create vertex cloud using coordinates of reconstructed tracks"""
  
-     bl_idname = "clip.tracks_to_mesh"
-     bl_label = "Tracks to Mesh"
+     bl_idname = "clip.bundles_to_mesh"
+     bl_label = "3D Markers to Mesh"
      bl_options = {'UNDO', 'REGISTER'}
  
      @classmethod
          return (sc.type == 'CLIP_EDITOR') and sc.clip
  
      def execute(self, context):
++        from bpy_extras.io_utils import unpack_list
++
          sc = context.space_data
          clip = sc.clip
  
  
          ob = bpy.data.objects.new(name="Tracks", object_data=mesh)
  
-         bpy.context.scene.objects.link(ob)
+         context.scene.objects.link(ob)
  
          return {'FINISHED'}
  
@@@ -133,6 -171,6 +171,8 @@@ class CLIP_OT_delete_proxy(Operator)
          return wm.invoke_confirm(self, event)
  
      def _rmproxy(self, abspath):
++        import shutil
++
          if not os.path.exists(abspath):
              return
  
@@@ -202,35 -240,9 +242,9 @@@ class CLIP_OT_set_viewport_background(O
  
          return sc.clip
  
-     def _set_background(self, space_v3d, clip, user):
-         bgpic = None
-         for x in space_v3d.background_images:
-             if x.source == 'MOVIE':
-                 bgpic = x
-                 break
-         if not bgpic:
-             bgpic = space_v3d.background_images.new()
-         bgpic.source = 'MOVIE'
-         bgpic.clip = clip
-         bgpic.clip_user.proxy_render_size = user.proxy_render_size
-         bgpic.clip_user.use_render_undistorted = user.use_render_undistorted
-         bgpic.use_camera_clip = False
-         bgpic.view_axis = 'CAMERA'
-         space_v3d.show_background_images = True
      def execute(self, context):
          sc = context.space_data
-         clip = sc.clip
-         for area in context.window.screen.areas:
-             if area.type == 'VIEW_3D':
-                 for space in area.spaces:
-                     if space.type == 'VIEW_3D':
-                         self._set_background(space, clip, sc.clip_user)
+         CLIP_set_viewport_background(context, False, sc.clip, sc.clip_user)
  
          return {'FINISHED'}
  
@@@ -332,3 -344,430 +346,432 @@@ object's movement caused by this constr
                  self._bake_object(scene, ob)
  
          return {'FINISHED'}
+ class CLIP_OT_setup_tracking_scene(Operator):
+     """Prepare scene for compositing 3D objects into this footage"""
+     bl_idname = "clip.setup_tracking_scene"
+     bl_label = "Setup Tracking Scene"
+     bl_options = {'UNDO', 'REGISTER'}
+     @classmethod
+     def poll(cls, context):
+         sc = context.space_data
+         if sc.type != 'CLIP_EDITOR':
+             return False
+         clip = sc.clip
+         return clip and clip.tracking.reconstruction.is_valid
+     @staticmethod
+     def _setupScene(context):
+         scene = context.scene
+         scene.active_clip = context.space_data.clip
+     @staticmethod
+     def _setupWorld(context):
+         scene = context.scene
+         world = scene.world
+         if not world:
+             world = bpy.data.worlds.new(name="World")
+             scene.world = world
+         world.light_settings.use_ambient_occlusion = True
+         world.light_settings.ao_blend_type = 'MULTIPLY'
+         world.light_settings.use_environment_light = True
+         world.light_settings.environment_energy = 0.1
+         world.light_settings.distance = 1.0
+         world.light_settings.sample_method = 'ADAPTIVE_QMC'
+         world.light_settings.samples = 7
+         world.light_settings.threshold = 0.005
+     @staticmethod
+     def _findOrCreateCamera(context):
+         scene = context.scene
+         if scene.camera:
+             return scene.camera
+         cam = bpy.data.cameras.new(name="Camera")
+         camob = bpy.data.objects.new(name="Camera", object_data=cam)
+         scene.objects.link(camob)
+         scene.camera = camob
+         camob.matrix_local = (Matrix.Translation((7.481, -6.508, 5.344)) *
+             Matrix.Rotation(0.815, 4, 'Z') *
+             Matrix.Rotation(0.011, 4, 'Y') *
+             Matrix.Rotation(1.109, 4, 'X'))
+         return camob
+     @staticmethod
+     def _setupCamera(context):
+         camob = CLIP_OT_setup_tracking_scene._findOrCreateCamera(context)
+         # Remove all constraints to be sure motion is fine
+         camob.constraints.clear()
+         # Append camera solver constraint
+         con = camob.constraints.new(type='CAMERA_SOLVER')
+         con.use_active_clip = True
+         con.influence = 1.0
+     @staticmethod
+     def _setupViewport(context):
+         sc = context.space_data
+         CLIP_set_viewport_background(context, True, sc.clip, sc.clip_user)
+     @staticmethod
+     def _setupRenderLayers(context):
+         scene = context.scene
+         rlayers = scene.render.layers
+         if not scene.render.layers.get("Foreground"):
+             if len(rlayers) == 1:
+                 fg = rlayers[0]
+                 fg.name = 'Foreground'
+             else:
+                 fg = scene.render.layers.new('Foreground')
+             fg.use_sky = False
+             fg.layers = [True] + [False] * 19
+             fg.layers_zmask = [False] * 10 + [True] + [False] * 9
+             fg.use_pass_vector = True
+         if not scene.render.layers.get("Background"):
+             bg = scene.render.layers.new('Background')
+             bg.use_pass_shadow = True
+             bg.use_pass_ambient_occlusion = True
+             bg.layers = [False] * 10 + [True] + [False] * 9
+     @staticmethod
+     def _findNode(tree, type):
+         for node in tree.nodes:
+             if node.type == type:
+                 return node
+         return None
+     @staticmethod
+     def _findOrCreateNode(tree, type):
+         node = CLIP_OT_setup_tracking_scene._findNode(tree, type)
+         if not node:
+             node = tree.nodes.new(type=type)
+         return node
+     @staticmethod
+     def _needSetupNodes(context):
+         scene = context.scene
+         tree = scene.node_tree
+         if not tree:
+             # No compositor node tree found, time to create it!
+             return True
+         for node in tree.nodes:
+             if node.type in {'MOVIECLIP', 'MOVIEDISTORTION'}:
+                 return False
+         return True
+     @staticmethod
+     def _offsetNodes(tree):
+         for a in tree.nodes:
+             for b in tree.nodes:
+                 if a != b and a.location == b.location:
+                     b.location += Vector((40.0, 20.0))
+     def _setupNodes(self, context):
+         if not self._needSetupNodes(context):
+             # compositor nodes were already setup or even changes already
+             # do nothing to prevent nodes damage
+             return
+         # Enable backdrop for all compositor spaces
+         def setup_space(space):
+             space.show_backdrop = True
+         CLIP_spacees_walk(context, True, 'NODE_EDITOR', 'NODE_EDITOR',
+                           setup_space)
+         sc = context.space_data
+         scene = context.scene
+         scene.use_nodes = True
+         tree = scene.node_tree
+         clip = sc.clip
+         need_stabilization = False
+         # create nodes
+         rlayer_fg = self._findOrCreateNode(tree, 'R_LAYERS')
+         rlayer_bg = tree.nodes.new(type='R_LAYERS')
+         composite = self._findOrCreateNode(tree, 'COMPOSITE')
+         movieclip = tree.nodes.new(type='MOVIECLIP')
+         distortion = tree.nodes.new(type='MOVIEDISTORTION')
+         if need_stabilization:
+             stabilize = tree.nodes.new(type='STABILIZE2D')
+         scale = tree.nodes.new(type='SCALE')
+         invert = tree.nodes.new(type='INVERT')
+         add_ao = tree.nodes.new(type='MIX_RGB')
+         add_shadow = tree.nodes.new(type='MIX_RGB')
+         mul_shadow = tree.nodes.new(type='MIX_RGB')
+         mul_image = tree.nodes.new(type='MIX_RGB')
+         vector_blur = tree.nodes.new(type='VECBLUR')
+         alphaover = tree.nodes.new(type='ALPHAOVER')
+         viewer = tree.nodes.new(type='VIEWER')
+         # setup nodes
+         movieclip.clip = clip
+         distortion.clip = clip
+         distortion.distortion_type = 'UNDISTORT'
+         if need_stabilization:
+             stabilize.clip = clip
+         scale.space = 'RENDER_SIZE'
+         rlayer_bg.scene = scene
+         rlayer_bg.layer = "Background"
+         rlayer_fg.scene = scene
+         rlayer_fg.layer = "Foreground"
+         add_ao.blend_type = 'ADD'
+         add_shadow.blend_type = 'ADD'
+         mul_shadow.blend_type = 'MULTIPLY'
+         mul_shadow.inputs['Fac'].default_value = 0.8
+         mul_image.blend_type = 'MULTIPLY'
+         mul_image.inputs['Fac'].default_value = 0.8
+         vector_blur.factor = 0.75
+         # create links
+         tree.links.new(movieclip.outputs['Image'], distortion.inputs['Image'])
+         if need_stabilization:
+             tree.links.new(distortion.outputs['Image'],
+                 stabilize.inputs['Image'])
+             tree.links.new(stabilize.outputs['Image'], scale.inputs['Image'])
+         else:
+             tree.links.new(distortion.outputs['Image'], scale.inputs['Image'])
+         tree.links.new(rlayer_bg.outputs['Alpha'], invert.inputs['Color'])
+         tree.links.new(invert.outputs['Color'], add_shadow.inputs[1])
+         tree.links.new(rlayer_bg.outputs['Shadow'], add_shadow.inputs[2])
+         tree.links.new(invert.outputs['Color'], add_ao.inputs[1])
+         tree.links.new(rlayer_bg.outputs['AO'], add_ao.inputs[2])
+         tree.links.new(add_ao.outputs['Image'], mul_shadow.inputs[1])
+         tree.links.new(add_shadow.outputs['Image'], mul_shadow.inputs[2])
+         tree.links.new(scale.outputs['Image'], mul_image.inputs[1])
+         tree.links.new(mul_shadow.outputs['Image'], mul_image.inputs[2])
+         tree.links.new(rlayer_fg.outputs['Image'], vector_blur.inputs['Image'])
+         tree.links.new(rlayer_fg.outputs['Z'], vector_blur.inputs['Z'])
+         tree.links.new(rlayer_fg.outputs['Speed'], vector_blur.inputs['Speed'])
+         tree.links.new(mul_image.outputs['Image'], alphaover.inputs[1])
+         tree.links.new(vector_blur.outputs['Image'], alphaover.inputs[2])
+         tree.links.new(alphaover.outputs['Image'], composite.inputs['Image'])
+         tree.links.new(alphaover.outputs['Image'], viewer.inputs['Image'])
+         # place nodes
+         movieclip.location = Vector((-300.0, 350.0))
+         distortion.location = movieclip.location
+         distortion.location += Vector((200.0, 0.0))
+         if need_stabilization:
+             stabilize.location = distortion.location
+             stabilize.location += Vector((200.0, 0.0))
+             scale.location = stabilize.location
+             scale.location += Vector((200.0, 0.0))
+         else:
+             scale.location = distortion.location
+             scale.location += Vector((200.0, 0.0))
+         rlayer_bg.location = movieclip.location
+         rlayer_bg.location -= Vector((0.0, 350.0))
+         invert.location = rlayer_bg.location
+         invert.location += Vector((250.0, 50.0))
+         add_ao.location = invert.location
+         add_ao.location[0] += 200
+         add_ao.location[1] = rlayer_bg.location[1]
+         add_shadow.location = add_ao.location
+         add_shadow.location -= Vector((0.0, 250.0))
+         mul_shadow.location = add_ao.location
+         mul_shadow.location += Vector((200.0, -50.0))
+         mul_image.location = mul_shadow.location
+         mul_image.location += Vector((300.0, 200.0))
+         rlayer_fg.location = rlayer_bg.location
+         rlayer_fg.location -= Vector((0.0, 500.0))
+         vector_blur.location[0] = mul_image.location[0]
+         vector_blur.location[1] = rlayer_fg.location[1]
+         alphaover.location[0] = vector_blur.location[0] + 350
+         alphaover.location[1] = \
+             (vector_blur.location[1] + mul_image.location[1]) / 2
+         composite.location = alphaover.location
+         composite.location += Vector((200.0, -100.0))
+         viewer.location = composite.location
+         composite.location += Vector((0.0, 200.0))
+         # ensure no nodes were creates on position of existing node
+         self._offsetNodes(tree)
+     @staticmethod
+     def _createMesh(scene, name, vertices, faces):
++        from bpy_extras.io_utils import unpack_list, unpack_face_list
++
+         mesh = bpy.data.meshes.new(name=name)
+         mesh.vertices.add(len(vertices))
+         mesh.vertices.foreach_set("co", unpack_list(vertices))
+         mesh.faces.add(len(faces))
+         mesh.faces.foreach_set("vertices_raw", unpack_face_list(faces))
+         mesh.update(calc_edges=True)
+         ob = bpy.data.objects.new(name=name, object_data=mesh)
+         scene.objects.link(ob)
+         return ob
+     @staticmethod
+     def _getPlaneVertices(half_size, z):
+         return [(-half_size, -half_size, z),
+                 (-half_size, half_size, z),
+                 (half_size, half_size, z),
+                 (half_size, -half_size, z)]
+     def _createGround(self, scene):
+         vertices = self._getPlaneVertices(4.0, 0.0)
+         faces = [(0, 1, 2, 3)]
+         ob = self._createMesh(scene, "Ground", vertices, faces)
+         ob["is_ground"] = True
+         return ob
+     @staticmethod
+     def _findGround(context):
+         scene = context.scene
+         for ob in scene.objects:
+             if ob.type == 'MESH' and "is_ground" in ob:
+                 return ob
+         return None
+     @staticmethod
+     def _mergeLayers(layers_a, layers_b):
+         return [(layers_a[i] | layers_b[i]) for i in range(len(layers_a))]
+     @staticmethod
+     def _createLamp(scene):
+         lamp = bpy.data.lamps.new(name="Lamp", type='POINT')
+         lampob = bpy.data.objects.new(name="Lamp", object_data=lamp)
+         scene.objects.link(lampob)
+         lampob.matrix_local = Matrix.Translation((4.076, 1.005, 5.904))
+         lamp.distance = 30
+         lamp.shadow_method = 'RAY_SHADOW'
+         return lampob
+     def _createSampleObject(self, scene):
+         vertices = self._getPlaneVertices(1.0, -1.0) + \
+             self._getPlaneVertices(1.0, 1.0)
+         faces = ((0, 1, 2, 3),
+                  (4, 7, 6, 5),
+                  (0, 4, 5, 1),
+                  (1, 5, 6, 2),
+                  (2, 6, 7, 3),
+                  (3, 7, 4, 0))
+         return self._createMesh(scene, "Cube", vertices, faces)
+     def _setupObjects(self, context):
+         scene = context.scene
+         fg = scene.render.layers.get("Foreground")
+         bg = scene.render.layers.get("Background")
+         all_layers = self._mergeLayers(fg.layers, bg.layers)
+         # enshure all lamps are active on foreground and background
+         has_lamp = False
+         has_mesh = False
+         for ob in scene.objects:
+             if ob.type == 'LAMP':
+                 ob.layers = all_layers
+                 has_lamp = True
+             elif ob.type == 'MESH' and "is_ground" not in ob:
+                 has_mesh = True
+         # create sample lamp if there's no lamps in the scene
+         if not has_lamp:
+             lamp = self._createLamp(scene)
+             lamp.layers = all_layers
+         # create sample object if there's no meshes in the scene
+         if not has_mesh:
+             ob = self._createSampleObject(scene)
+             ob.layers = fg.layers
+         # create ground object if needed
+         ground = self._findGround(context)
+         if not ground:
+             ground = self._createGround(scene)
+             ground.layers = bg.layers
+         else:
+             # make sure ground is available on Background layer
+             ground.layers = self._mergeLayers(ground.layers, bg.layers)
+         # layers with background and foreground should be rendered
+         scene.layers = self._mergeLayers(scene.layers, all_layers)
+     def execute(self, context):
+         self._setupScene(context)
+         self._setupWorld(context)
+         self._setupCamera(context)
+         self._setupViewport(context)
+         self._setupRenderLayers(context)
+         self._setupNodes(context)
+         self._setupObjects(context)
+         return {'FINISHED'}
index 288f04b084e5340e2d93b7a279a36c0f33dc9987,d5b8b9d110d8159b918ff224966f902c3a495719..5e9f863d22bccb7d113b89cbb3f5abae74797e54
@@@ -454,15 -454,15 +454,15 @@@ class DATA_PT_modifiers(ModifierButtons
          layout.separator()
  
          layout.prop(md, "use_normals")
--        
++
          split = layout.split()
--        
++
          col = split.column()
          col.prop(md, "use_foam")
          sub = col.row()
          sub.active = md.use_foam
          sub.prop(md, "foam_coverage", text="Coverage")
--        
++
          col = split.column()
          col.active = md.use_foam
          col.label("Foam Data Layer Name:")
          col.prop(md, "image", text="")
  
          col = split.column()
-         col.label(text="UV Layer:")
+         col.label(text="UV Map:")
          col.prop_search(md, "uv_layer", ob.data, "uv_textures", text="")
  
          split = layout.split()
index 85b5f3f0dd47cd18b96d74f4616a080dd98e622d,57df602f19a08492b2a783ca1ec63f5ec4a7d12e..aa6e2ce7cffaf37043de148000bbad14b89926e6
@@@ -123,12 -123,11 +123,12 @@@ class RENDER_PT_layers(RenderButtonsPan
          col.prop(rl, "use_solid")
          col.prop(rl, "use_halo")
          col.prop(rl, "use_ztransp")
 +        col.prop(rl, "use_sky")
  
          col = split.column()
 -        col.prop(rl, "use_sky")
          col.prop(rl, "use_edge_enhance")
          col.prop(rl, "use_strand")
 +        col.prop(rl, "use_freestyle")
  
          layout.separator()
  
          row.prop(rl, "exclude_refraction", text="")
  
  
 +class RENDER_MT_lineset_specials(Menu):
 +    bl_label = "Lineset Specials"
 +
 +    def draw(self, context):
 +        layout = self.layout
 +        layout.operator("scene.freestyle_lineset_copy", icon='COPYDOWN')
 +        layout.operator("scene.freestyle_lineset_paste", icon='PASTEDOWN')
 +
 +
 +class RENDER_PT_freestyle(RenderButtonsPanel, Panel):
 +    bl_label = "Freestyle"
 +    COMPAT_ENGINES = {'BLENDER_RENDER'}
 +
 +    @classmethod
 +    def poll(cls, context):
 +        rd = context.scene.render
 +        rl = rd.layers.active
 +        return rl and rl.use_freestyle
 +
 +    def draw(self, context):
 +        layout = self.layout
 +
 +        rd = context.scene.render
 +        rl = rd.layers.active
 +        freestyle = rl.freestyle_settings
 +
 +        split = layout.split()
 +
 +        col = split.column()
 +        col.prop(freestyle, "raycasting_algorithm", text="Raycasting Algorithm")
 +        col.prop(freestyle, "mode", text="Control Mode")
 +
 +        if freestyle.mode == "EDITOR":
 +            col.label(text="Edge Detection Options:")
 +            col.prop(freestyle, "use_smoothness")
 +            col.prop(freestyle, "crease_angle")
 +            col.prop(freestyle, "sphere_radius")
 +            col.prop(freestyle, "kr_derivative_epsilon")
 +
 +            lineset = freestyle.linesets.active
 +
 +            col.label(text="Line Sets:")
 +            row = col.row()
 +            rows = 2
 +            if lineset:
 +                rows = 5
 +            row.template_list(freestyle, "linesets", freestyle.linesets, "active_index", rows=rows)
 +
 +            sub = row.column()
 +            subsub = sub.column(align=True)
 +            subsub.operator("scene.freestyle_lineset_add", icon='ZOOMIN', text="")
 +            subsub.operator("scene.freestyle_lineset_remove", icon='ZOOMOUT', text="")
 +            subsub.menu("RENDER_MT_lineset_specials", icon='DOWNARROW_HLT', text="")
 +            if lineset:
 +                sub.separator()
 +                subsub = sub.column(align=True)
 +                subsub.operator("scene.freestyle_lineset_move", icon='TRIA_UP', text="").direction = 'UP'
 +                subsub.operator("scene.freestyle_lineset_move", icon='TRIA_DOWN', text="").direction = 'DOWN'
 +
 +        else: # freestyle.mode == "SCRIPT"
 +
 +            col.prop(freestyle, "use_smoothness")
 +            col.prop(freestyle, "crease_angle")
 +            col.prop(freestyle, "sphere_radius")
 +            col.prop(freestyle, "use_ridges_and_valleys")
 +            col.prop(freestyle, "use_suggestive_contours")
 +            sub = col.row()
 +            sub.prop(freestyle, "kr_derivative_epsilon")
 +            sub.active = freestyle.use_suggestive_contours
 +            col.prop(freestyle, "use_material_boundaries")
 +            col.operator("scene.freestyle_module_add")
 +
 +            for i, module in enumerate(freestyle.modules):
 +                box = layout.box()
 +                box.context_pointer_set("freestyle_module", module)
 +                row = box.row(align=True)
 +                row.prop(module, "use", text="")
 +                row.prop(module, "module_path", text="")
 +                row.operator("scene.freestyle_module_remove", icon='X', text="")
 +                row.operator("scene.freestyle_module_move", icon='TRIA_UP', text="").direction = 'UP'
 +                row.operator("scene.freestyle_module_move", icon='TRIA_DOWN', text="").direction = 'DOWN'
 +
 +
 +class RENDER_PT_freestyle_lineset(RenderButtonsPanel, Panel):
 +    bl_label = "Freestyle: Line Set"
 +    COMPAT_ENGINES = {'BLENDER_RENDER'}
 +
 +    @classmethod
 +    def poll(cls, context):
 +        rd = context.scene.render
 +        rl = rd.layers.active
 +        if rl and rl.use_freestyle:
 +            freestyle = rl.freestyle_settings
 +            return freestyle.mode == "EDITOR" and freestyle.linesets.active
 +        return False
 +
 +    def draw_edge_type_buttons(self, box, lineset, edge_type):
 +        # property names
 +        select_edge_type = "select_" + edge_type
 +        exclude_edge_type = "exclude_" + edge_type
 +        # draw edge type buttons
 +        row = box.row(align=True)
 +        row.prop(lineset, select_edge_type)
 +        sub = row.column()
 +        sub.prop(lineset, exclude_edge_type, text="")
 +        sub.enabled = getattr(lineset, select_edge_type)
 +
 +    def draw(self, context):
 +        layout = self.layout
 +
 +        rd = context.scene.render
 +        rl = rd.layers.active
 +        freestyle = rl.freestyle_settings
 +        lineset = freestyle.linesets.active
 +
 +        split = layout.split()
 +
 +        col = split.column()
 +        col.prop(lineset, "name")
 +
 +        col.prop(lineset, "select_by_visibility")
 +        if lineset.select_by_visibility:
 +            sub = col.row(align=True)
 +            sub.prop(lineset, "visibility", expand=True)
 +            if lineset.visibility == "RANGE":
 +                sub = col.row(align=True)
 +                sub.prop(lineset, "qi_start")
 +                sub.prop(lineset, "qi_end")
 +            col.separator() # XXX
 +
 +        col.prop(lineset, "select_by_edge_types")
 +        if lineset.select_by_edge_types:
 +            row = col.row()
 +            row.prop(lineset, "edge_type_negation", expand=True)
 +            row = col.row()
 +            row.prop(lineset, "edge_type_combination", expand=True)
 +
 +            row = col.row()
 +            sub = row.column()
 +            self.draw_edge_type_buttons(sub, lineset, "silhouette")
 +            self.draw_edge_type_buttons(sub, lineset, "border")
 +
 +            self.draw_edge_type_buttons(sub, lineset, "crease")
 +            self.draw_edge_type_buttons(sub, lineset, "ridge")
 +            self.draw_edge_type_buttons(sub, lineset, "valley")
 +            self.draw_edge_type_buttons(sub, lineset, "suggestive_contour")
 +            self.draw_edge_type_buttons(sub, lineset, "material_boundary")
 +            self.draw_edge_type_buttons(sub, lineset, "edge_mark")
 +            sub = row.column()
 +            self.draw_edge_type_buttons(sub, lineset, "contour")
 +            self.draw_edge_type_buttons(sub, lineset, "external_contour")
 +            col.separator() # XXX
 +
 +        col.prop(lineset, "select_by_face_marks")
 +        if lineset.select_by_face_marks:
 +            row = col.row()
 +            row.prop(lineset, "face_mark_negation", expand=True)
 +            row = col.row()
 +            row.prop(lineset, "face_mark_condition", expand=True)
 +            col.separator() # XXX
 +
 +        col.prop(lineset, "select_by_group")
 +        if lineset.select_by_group:
 +            col.prop(lineset, "group")
 +            row = col.row()
 +            row.prop(lineset, "group_negation", expand=True)
 +            col.separator() # XXX
 +
 +        col.prop(lineset, "select_by_image_border")
 +
 +
 +class RENDER_PT_freestyle_linestyle(RenderButtonsPanel, Panel):
 +    bl_label = "Freestyle: Line Style"
 +    COMPAT_ENGINES = {'BLENDER_RENDER'}
 +
 +    @classmethod
 +    def poll(cls, context):
 +        rd = context.scene.render
 +        rl = rd.layers.active
 +        if rl and rl.use_freestyle:
 +            freestyle = rl.freestyle_settings
 +            return freestyle.mode == "EDITOR" and freestyle.linesets.active
 +        return False
 +
 +    def draw_modifier_box_header(self, box, modifier):
 +        row = box.row()
 +        row.context_pointer_set("modifier", modifier)
 +        if modifier.expanded:
 +            icon = "TRIA_DOWN"
 +        else:
 +            icon = "TRIA_RIGHT"
 +        row.prop(modifier, "expanded", text="", icon=icon, emboss=False)
 +        row.label(text=modifier.rna_type.name)
 +        row.prop(modifier, "name", text="")
 +        row.prop(modifier, "use", text="")
 +        sub = row.row(align=True)
 +        sub.operator("scene.freestyle_modifier_move", icon='TRIA_UP', text="").direction = 'UP'
 +        sub.operator("scene.freestyle_modifier_move", icon='TRIA_DOWN', text="").direction = 'DOWN'
 +        row.operator("scene.freestyle_modifier_remove", icon='X', text="")
 +
 +    def draw_modifier_common(self, box, modifier):
 +        row = box.row()
 +        row.prop(modifier, "blend", text="")
 +        row.prop(modifier, "influence")
 +
 +    def draw_modifier_color_ramp_common(self, box, modifier, has_range):
 +        box.template_color_ramp(modifier, "color_ramp", expand=True)
 +        if has_range:
 +            row = box.row(align=True)
 +            row.prop(modifier, "range_min")
 +            row.prop(modifier, "range_max")
 +
 +    def draw_modifier_curve_common(self, box, modifier, has_range, has_value):
 +        row = box.row()
 +        row.prop(modifier, "mapping", text="")
 +        sub = row.column()
 +        sub.prop(modifier, "invert")
 +        if modifier.mapping == "CURVE":
 +            sub.enabled = False
 +            box.template_curve_mapping(modifier, "curve")
 +        if has_range:
 +            row = box.row(align=True)
 +            row.prop(modifier, "range_min")
 +            row.prop(modifier, "range_max")
 +        if has_value:
 +            row = box.row(align=True)
 +            row.prop(modifier, "value_min")
 +            row.prop(modifier, "value_max")
 +
 +    def draw_color_modifier(self, context, modifier):
 +        layout = self.layout
 +
 +        col = layout.column(align=True)
 +        self.draw_modifier_box_header(col.box(), modifier)
 +        if modifier.expanded:
 +            box = col.box()
 +            self.draw_modifier_common(box, modifier)
 +
 +            if modifier.type == "ALONG_STROKE":
 +                self.draw_modifier_color_ramp_common(box, modifier, False)
 +
 +            elif modifier.type == "DISTANCE_FROM_OBJECT":
 +                box.prop(modifier, "target")
 +                self.draw_modifier_color_ramp_common(box, modifier, True)
 +                prop = box.operator("scene.freestyle_fill_range_by_selection")
 +                prop.type = 'COLOR'
 +                prop.name = modifier.name
 +
 +            elif modifier.type == "DISTANCE_FROM_CAMERA":
 +                self.draw_modifier_color_ramp_common(box, modifier, True)
 +                prop = box.operator("scene.freestyle_fill_range_by_selection")
 +                prop.type = 'COLOR'
 +                prop.name = modifier.name
 +
 +            elif modifier.type == "MATERIAL":
 +                row = box.row()
 +                row.prop(modifier, "material_attr", text="")
 +                sub = row.column()
 +                sub.prop(modifier, "use_ramp")
 +                if modifier.material_attr in ["DIFF", "SPEC"]:
 +                    sub.enabled = True
 +                    show_ramp = modifier.use_ramp
 +                else:
 +                    sub.enabled = False
 +                    show_ramp = True
 +                if show_ramp:
 +                    self.draw_modifier_color_ramp_common(box, modifier, False)
 +
 +    def draw_alpha_modifier(self, context, modifier):
 +        layout = self.layout
 +
 +        col = layout.column(align=True)
 +        self.draw_modifier_box_header(col.box(), modifier)
 +        if modifier.expanded:
 +            box = col.box()
 +            self.draw_modifier_common(box, modifier)
 +
 +            if modifier.type == "ALONG_STROKE":
 +                self.draw_modifier_curve_common(box, modifier, False, False)
 +
 +            elif modifier.type == "DISTANCE_FROM_OBJECT":
 +                box.prop(modifier, "target")
 +                self.draw_modifier_curve_common(box, modifier, True, False)
 +                prop = box.operator("scene.freestyle_fill_range_by_selection")
 +                prop.type = 'ALPHA'
 +                prop.name = modifier.name
 +
 +            elif modifier.type == "DISTANCE_FROM_CAMERA":
 +                self.draw_modifier_curve_common(box, modifier, True, False)
 +                prop = box.operator("scene.freestyle_fill_range_by_selection")
 +                prop.type = 'ALPHA'
 +                prop.name = modifier.name
 +
 +            elif modifier.type == "MATERIAL":
 +                box.prop(modifier, "material_attr", text="")
 +                self.draw_modifier_curve_common(box, modifier, False, False)
 +
 +    def draw_thickness_modifier(self, context, modifier):
 +        layout = self.layout
 +
 +        col = layout.column(align=True)
 +        self.draw_modifier_box_header(col.box(), modifier)
 +        if modifier.expanded:
 +            box = col.box()
 +            self.draw_modifier_common(box, modifier)
 +
 +            if modifier.type == "ALONG_STROKE":
 +                self.draw_modifier_curve_common(box, modifier, False, True)
 +
 +            elif modifier.type == "DISTANCE_FROM_OBJECT":
 +                box.prop(modifier, "target")
 +                self.draw_modifier_curve_common(box, modifier, True, True)
 +                prop = box.operator("scene.freestyle_fill_range_by_selection")
 +                prop.type = 'THICKNESS'
 +                prop.name = modifier.name
 +
 +            elif modifier.type == "DISTANCE_FROM_CAMERA":
 +                self.draw_modifier_curve_common(box, modifier, True, True)
 +                prop = box.operator("scene.freestyle_fill_range_by_selection")
 +                prop.type = 'THICKNESS'
 +                prop.name = modifier.name
 +
 +            elif modifier.type == "MATERIAL":
 +                box.prop(modifier, "material_attr", text="")
 +                self.draw_modifier_curve_common(box, modifier, False, True)
 +
 +            elif modifier.type == "CALLIGRAPHY":
 +                col = box.column()
 +                col.prop(modifier, "orientation")
 +                col.prop(modifier, "min_thickness")
 +                col.prop(modifier, "max_thickness")
 +
 +    def draw_geometry_modifier(self, context, modifier):
 +        layout = self.layout
 +
 +        col = layout.column(align=True)
 +        self.draw_modifier_box_header(col.box(), modifier)
 +        if modifier.expanded:
 +            box = col.box()
 +
 +            if modifier.type == "SAMPLING":
 +                box.prop(modifier, "sampling")
 +
 +            elif modifier.type == "BEZIER_CURVE":
 +                box.prop(modifier, "error")
 +
 +            elif modifier.type == "SINUS_DISPLACEMENT":
 +                box.prop(modifier, "wavelength")
 +                box.prop(modifier, "amplitude")
 +                box.prop(modifier, "phase")
 +
 +            elif modifier.type == "SPATIAL_NOISE":
 +                box.prop(modifier, "amplitude")
 +                box.prop(modifier, "scale")
 +                box.prop(modifier, "octaves")
 +                sub = box.row()
 +                sub.prop(modifier, "smooth")
 +                sub.prop(modifier, "pure_random")
 +
 +            elif modifier.type == "PERLIN_NOISE_1D":
 +                box.prop(modifier, "frequency")
 +                box.prop(modifier, "amplitude")
 +                box.prop(modifier, "octaves")
 +                box.prop(modifier, "angle")
 +                box.prop(modifier, "seed")
 +
 +            elif modifier.type == "PERLIN_NOISE_2D":
 +                box.prop(modifier, "frequency")
 +                box.prop(modifier, "amplitude")
 +                box.prop(modifier, "octaves")
 +                box.prop(modifier, "angle")
 +                box.prop(modifier, "seed")
 +
 +            elif modifier.type == "BACKBONE_STRETCHER":
 +                box.prop(modifier, "backbone_length")
 +
 +            elif modifier.type == "TIP_REMOVER":
 +                box.prop(modifier, "tip_length")
 +
 +            elif modifier.type == "POLYGONIZATION":
 +                box.prop(modifier, "error")
 +
 +            elif modifier.type == "GUIDING_LINES":
 +                box.prop(modifier, "offset")
 +
 +            elif modifier.type == "BLUEPRINT":
 +                row = box.row()
 +                row.prop(modifier, "shape", expand=True)
 +                box.prop(modifier, "rounds")
 +                if modifier.shape in ["CIRCLES", "ELLIPSES"]:
 +                    box.prop(modifier, "random_radius")
 +                    box.prop(modifier, "random_center")
 +                elif modifier.shape == "SQUARES":
 +                    box.prop(modifier, "backbone_length")
 +                    box.prop(modifier, "random_backbone")
 +
 +    def draw(self, context):
 +        layout = self.layout
 +
 +        rd = context.scene.render
 +        rl = rd.layers.active
 +        lineset = rl.freestyle_settings.linesets.active
 +        linestyle = lineset.linestyle
 +
 +        layout.template_ID(lineset, "linestyle", new="scene.freestyle_linestyle_new")
 +        row = layout.row(align=True)
 +        row.prop(linestyle, "panel", expand=True)
 +        if linestyle.panel == "STROKES":
 +            # Chaining
 +            col = layout.column()
 +            col.prop(linestyle, "use_chaining", text="Chaining:")
 +            sub = col.column()
 +            sub.enabled = linestyle.use_chaining
 +            sub.prop(linestyle, "chaining", text="")
 +            if linestyle.chaining == "PLAIN":
 +                sub.prop(linestyle, "same_object")
 +            elif linestyle.chaining == "SKETCHY":
 +                subsub = sub.row()
 +                subsub.prop(linestyle, "same_object")
 +                subsub.prop(linestyle, "rounds")
 +            # Splitting
 +            col = layout.column()
 +            col.label(text="Splitting:")
 +            sub = col.row()
 +            subcol = sub.column()
 +            subcol.prop(linestyle, "use_min_angle", text="Min Angle")
 +            subsub = subcol.split()
 +            subsub.prop(linestyle, "min_angle", text="")
 +            subsub.enabled = linestyle.use_min_angle
 +            subcol = sub.column()
 +            subcol.prop(linestyle, "use_max_angle", text="Max Angle")
 +            subsub = subcol.split()
 +            subsub.prop(linestyle, "max_angle", text="")
 +            subsub.enabled = linestyle.use_max_angle
 +            row = col.row()
 +            row.prop(linestyle, "material_boundary")
 +            # Selection
 +            col = layout.column()
 +            col.label(text="Selection:")
 +            sub = col.row()
 +            subcol = sub.column()
 +            subcol.prop(linestyle, "use_min_length", text="Min Length")
 +            subsub = subcol.split()
 +            subsub.prop(linestyle, "min_length", text="")
 +            subsub.enabled = linestyle.use_min_length
 +            subcol = sub.column()
 +            subcol.prop(linestyle, "use_max_length", text="Max Length")
 +            subsub = subcol.split()
 +            subsub.prop(linestyle, "max_length", text="")
 +            subsub.enabled = linestyle.use_max_length
 +            # Caps
 +            col = layout.column()
 +            col.label(text="Caps:")
 +            row = col.row(align=True)
 +            row.prop(linestyle, "caps", expand=True)
 +            col = layout.column()
 +            col.prop(linestyle, "use_dashed_line")
 +            split = col.split()
 +            split.enabled = linestyle.use_dashed_line
 +            sub = split.column()
 +            sub.label(text="Dash")
 +            sub.prop(linestyle, "dash1", text="")
 +            sub = split.column()
 +            sub.label(text="Gap")
 +            sub.prop(linestyle, "gap1", text="")
 +            sub = split.column()
 +            sub.label(text="Dash")
 +            sub.prop(linestyle, "dash2", text="")
 +            sub = split.column()
 +            sub.label(text="Gap")
 +            sub.prop(linestyle, "gap2", text="")
 +            sub = split.column()
 +            sub.label(text="Dash")
 +            sub.prop(linestyle, "dash3", text="")
 +            sub = split.column()
 +            sub.label(text="Gap")
 +            sub.prop(linestyle, "gap3", text="")
 +        elif linestyle.panel == "COLOR":
 +            col = layout.column()
 +            col.label(text="Base Color:")
 +            col.prop(linestyle, "color", text="")
 +            col = layout.column()
 +            col.label(text="Modifiers:")
 +            col.operator_menu_enum("scene.freestyle_color_modifier_add", "type", text="Add Modifier")
 +            for modifier in linestyle.color_modifiers:
 +                self.draw_color_modifier(context, modifier)
 +        elif linestyle.panel == "ALPHA":
 +            col = layout.column()
 +            col.label(text="Base Transparency:")
 +            col.prop(linestyle, "alpha")
 +            col = layout.column()
 +            col.label(text="Modifiers:")
 +            col.operator_menu_enum("scene.freestyle_alpha_modifier_add", "type", text="Add Modifier")
 +            for modifier in linestyle.alpha_modifiers:
 +                self.draw_alpha_modifier(context, modifier)
 +        elif linestyle.panel == "THICKNESS":
 +            col = layout.column()
 +            col.label(text="Base Thickness:")
 +            col.prop(linestyle, "thickness")
 +            col = layout.column()
 +            col.label(text="Modifiers:")
 +            col.operator_menu_enum("scene.freestyle_thickness_modifier_add", "type", text="Add Modifier")
 +            for modifier in linestyle.thickness_modifiers:
 +                self.draw_thickness_modifier(context, modifier)
 +        elif linestyle.panel == "GEOMETRY":
 +            col = layout.column()
 +            col.label(text="Modifiers:")
 +            col.operator_menu_enum("scene.freestyle_geometry_modifier_add", "type", text="Add Modifier")
 +            for modifier in linestyle.geometry_modifiers:
 +                self.draw_geometry_modifier(context, modifier)
 +        elif linestyle.panel == "MISC":
 +            pass
 +
 +
  class RENDER_PT_dimensions(RenderButtonsPanel, Panel):
      bl_label = "Dimensions"
      COMPAT_ENGINES = {'BLENDER_RENDER'}
@@@ -913,11 -398,6 +913,11 @@@ class RENDER_PT_post_processing(RenderB
          sub.prop(rd, "edge_threshold", text="Threshold", slider=True)
          sub.prop(rd, "edge_color", text="")
  
 +        layout.separator()
 +
 +        split = layout.split()
 +        col = split.column()
 +        col.prop(rd, "use_freestyle", text="Freestyle")
  
  class RENDER_PT_stamp(RenderButtonsPanel, Panel):
      bl_label = "Stamp"
@@@ -972,66 -452,19 +972,19 @@@ class RENDER_PT_output(RenderButtonsPan
          layout = self.layout
  
          rd = context.scene.render
-         file_format = rd.file_format
+         image_settings = rd.image_settings
+         file_format = rd.image_settings.file_format
  
          layout.prop(rd, "filepath", text="")
 -        
 +
-         split = layout.split()
-         col = split.column()
-         col.prop(rd, "file_format", text="")
-         col.row().prop(rd, "color_mode", text="Color", expand=True)
-         col = split.column()
-         col.prop(rd, "use_file_extension")
-         col.prop(rd, "use_overwrite")
-         col.prop(rd, "use_placeholder")
-         if file_format in {'AVI_JPEG', 'JPEG'}:
-             layout.prop(rd, "file_quality", slider=True)
-         if file_format == 'PNG':
-             layout.prop(rd, "file_quality", slider=True, text="Compression")
-         if file_format in {'OPEN_EXR', 'MULTILAYER'}:
-             row = layout.row()
-             row.prop(rd, "exr_codec", text="Codec")
-             if file_format == 'OPEN_EXR':
-                 row = layout.row()
-                 row.prop(rd, "use_exr_half")
-                 row.prop(rd, "exr_zbuf")
-                 row.prop(rd, "exr_preview")
-         elif file_format == 'JPEG2000':
-             split = layout.split()
-             col = split.column()
-             col.label(text="Depth:")
-             col.row().prop(rd, "jpeg2k_depth", expand=True)
-             col = split.column()
-             col.prop(rd, "jpeg2k_preset", text="")
-             col.prop(rd, "jpeg2k_ycc")
-         elif file_format in {'CINEON', 'DPX'}:
-             split = layout.split()
-             split.label("FIXME: hard coded Non-Linear, Gamma:1.0")
-             '''
-             col = split.column()
-             col.prop(rd, "use_cineon_log", text="Convert to Log")
-             col = split.column(align=True)
-             col.active = rd.use_cineon_log
-             col.prop(rd, "cineon_black", text="Black")
-             col.prop(rd, "cineon_white", text="White")
-             col.prop(rd, "cineon_gamma", text="Gamma")
-             '''
+         flow = layout.column_flow()
+         flow.prop(rd, "use_overwrite")
+         flow.prop(rd, "use_placeholder")
+         flow.prop(rd, "use_file_extension")
  
-         elif file_format == 'TIFF':
-             layout.prop(rd, "use_tiff_16bit")
+         layout.template_image_settings(rd.image_settings)
  
-         elif file_format == 'QUICKTIME_CARBON':
+         if file_format == 'QUICKTIME_CARBON':
              layout.operator("scene.render_data_set_quicktime_codec")
  
          elif file_format == 'QUICKTIME_QTKIT':
@@@ -1072,7 -505,7 +1025,7 @@@ class RENDER_PT_encoding(RenderButtonsP
      @classmethod
      def poll(cls, context):
          rd = context.scene.render
-         return rd.file_format in {'FFMPEG', 'XVID', 'H264', 'THEORA'}
+         return rd.image_settings.file_format in {'FFMPEG', 'XVID', 'H264', 'THEORA'}
  
      def draw(self, context):
          layout = self.layout
index a70d632e8b0691b57b6cffa0ddc968e238742ca1,e0e7e88f620a4f1a2af7f5f29ad05d54a71c23c9..b04d81b6b2a6aeaab2b24bb3e239796a30ac8a7e
@@@ -210,7 -210,7 +210,7 @@@ class CLIP_PT_tools_geometry(Panel)
      def draw(self, context):
          layout = self.layout
  
-         layout.operator("clip.tracks_to_mesh")
+         layout.operator("clip.bundles_to_mesh")
          layout.operator("clip.track_to_empty")
  
  
@@@ -402,15 -402,15 +402,15 @@@ class CLIP_PT_display(Panel)
          col.prop(sc, "show_marker_search", text="Search")
          col.prop(sc, "show_pyramid_levels", text="Pyramid")
  
-         col.prop(sc, "show_track_path", text="Track Path")
+         col.prop(sc, "show_track_path", text="Path")
          row = col.row()
          row.active = sc.show_track_path
          row.prop(sc, "path_length", text="Length")
  
          col.prop(sc, "show_disabled", "Disabled Tracks")
-         col.prop(sc, "show_bundles", text="Bundles")
+         col.prop(sc, "show_bundles", text="3D Markers")
  
-         col.prop(sc, "show_names", text="Track Names and Status")
+         col.prop(sc, "show_names", text="Names and Status")
          col.prop(sc, "show_tiny_markers", text="Compact Markers")
  
          col.prop(sc, "show_grease_pencil", text="Grease Pencil")
@@@ -475,7 -475,7 +475,7 @@@ class CLIP_PT_stabilization(Panel)
  
      def draw_header(self, context):
          stab = context.space_data.clip.tracking.stabilization
--        
++
          self.layout.prop(stab, "use_2d_stabilization", text="")
  
      def draw(self, context):
@@@ -640,6 -640,7 +640,7 @@@ class CLIP_PT_tools_clip(Panel)
          layout = self.layout
  
          layout.operator("clip.set_viewport_background")
+         layout.operator("clip.setup_tracking_scene")
  
  
  class CLIP_MT_view(Menu):
index 0753b49f69fe383a00f9f81e112cc7fd349a1d4e,e090b338a7dac0bef9c8743d59025c48a034c526..67a8c28ddb815a00e452be1c91a016acce27b3bb
@@@ -262,6 -262,7 +262,7 @@@ class VIEW3D_MT_uv_map(Menu)
  
          layout.separator()
  
+         layout.operator_context = 'EXEC_REGION_WIN'
          layout.operator("uv.project_from_view")
          layout.operator("uv.project_from_view", text="Project from View (Bounds)").scale_to_bounds = True
  
@@@ -1622,11 -1623,6 +1623,11 @@@ class VIEW3D_MT_edit_mesh_edges(Menu)
  
          layout.separator()
  
 +        layout.operator("mesh.mark_freestyle_edge")
 +        layout.operator("mesh.mark_freestyle_edge", text="Clear Freestyle Edge").clear = True
 +
 +        layout.separator()
 +
          layout.operator("mesh.edge_rotate", text="Rotate Edge CW").direction = 'CW'
          layout.operator("mesh.edge_rotate", text="Rotate Edge CCW").direction = 'CCW'
  
@@@ -1669,11 -1665,6 +1670,11 @@@ class VIEW3D_MT_edit_mesh_faces(Menu)
  
          layout.separator()
  
 +        layout.operator("mesh.mark_freestyle_face")
 +        layout.operator("mesh.mark_freestyle_face", text="Clear Freestyle Face").clear = True
 +
 +        layout.separator()
 +
          layout.operator("mesh.quads_convert_to_tris")
          layout.operator("mesh.tris_convert_to_quads")
          layout.operator("mesh.edge_flip")
@@@ -1767,7 -1758,7 +1768,7 @@@ class VIEW3D_MT_edit_curve_ctrlpoints(M
          edit_object = context.edit_object
  
          if edit_object.type == 'CURVE':
--            layout.operator("transform.transform", text="Tilt").mode = 'TILT'
++            layout.operator("transform.tilt")
              layout.operator("curve.tilt_clear")
              layout.operator("curve.separate")
  
@@@ -2213,7 -2204,7 +2214,7 @@@ class VIEW3D_PT_view3d_motion_tracking(
  
          col = layout.column()
          col.active = view.show_reconstruction
-         col.prop(view, "show_tracks_name")
+         col.prop(view, "show_bundle_names")
          col.prop(view, "show_camera_path")
          col.label(text="Tracks:")
          col.prop(view, "tracks_draw_type", text="")
@@@ -2243,8 -2234,6 +2244,8 @@@ class VIEW3D_PT_view3d_meshdisplay(Pane
          col.prop(mesh, "show_edge_bevel_weight", text="Bevel Weights")
          col.prop(mesh, "show_edge_seams", text="Seams")
          col.prop(mesh, "show_edge_sharp", text="Sharp")
 +        col.prop(mesh, "show_freestyle_edge_marks", text="Freestyle Edge Marks")
 +        col.prop(mesh, "show_freestyle_face_marks", text="Freestyle Face Marks")
  
          col.separator()
          col.label(text="Normals:")
index 4da67f59ff75f8fb08924d38cbd74d60c2b6cfe1,4da67f59ff75f8fb08924d38cbd74d60c2b6cfe1..b82393fad92d4547ddd681b67365d00823ebd87f
@@@ -129,7 -129,7 +129,7 @@@ void BLF_dir_free(char **dirs, int coun
  char *blf_dir_search(const char *file)
  {
        DirBLF *dir;
--      char full_path[FILE_MAXDIR+FILE_MAXFILE];
++      char full_path[FILE_MAX];
        char *s= NULL;
  
        for(dir=global_font_dir.first; dir; dir= dir->next) {
index 15fdc2fe30759e921f8fbc4ad6f5cbb29eba988d,15fdc2fe30759e921f8fbc4ad6f5cbb29eba988d..84f1bf75a3f2e64ed69b4cdbc9c323a822512e58
@@@ -526,7 -526,7 +526,7 @@@ int editmesh_get_first_deform_matrices(
  int sculpt_get_deform_matrices(struct Scene *scene, struct Object *ob,
                                                                float (**deformmats)[3][3], float (**deformcos)[3]);
  
--void weight_to_rgb(float input, float *fr, float *fg, float *fb);
++void weight_to_rgb(float r_rgb[3], const float weight);
  
  /* 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 */
index a3e0b5b6d5a9dfe221ed69ce2b9e97ca709759fe,96c0371baf33895fa6752f4addd71744ae21a23c..c829fc69b051b0b493234c18938991257acb7fd0
@@@ -43,6 -43,7 +43,7 @@@ struct Tex
  struct anim;
  struct Scene;
  struct Object;
+ struct ImageFormatData;
  
  /* call from library */
  void  free_image(struct Image *me);
  void  BKE_stamp_info(struct Scene *scene, struct Object *camera, struct ImBuf *ibuf);
  void  BKE_stamp_buf(struct Scene *scene, struct Object *camera, unsigned char *rect, float *rectf, int width, int height, int channels);
  int           BKE_alphatest_ibuf(struct ImBuf *ibuf);
- int           BKE_write_ibuf_stamp(struct Scene *scene, struct Object *camera, struct ImBuf *ibuf, const char *name, int imtype, int subimtype, int quality);
- int           BKE_write_ibuf(struct ImBuf *ibuf, const char *name, int imtype, int subimtype, int quality);
- void  BKE_makepicstring(char *string, const char *base, const char *relbase, int frame, int imtype, const short use_ext, const short use_frames);
- int           BKE_add_image_extension(char *string, int imtype);
- int           BKE_ftype_to_imtype(int ftype);
- int           BKE_imtype_to_ftype(int imtype);
- int           BKE_imtype_is_movie(int imtype);
+ int           BKE_write_ibuf_stamp(struct Scene *scene, struct Object *camera, struct ImBuf *ibuf, const char *name, struct ImageFormatData *imf);
+ int           BKE_write_ibuf(struct ImBuf *ibuf, const char *name, struct ImageFormatData *imf);
++int     BKE_write_ibuf_as(struct ImBuf *ibuf, const char *name, struct ImageFormatData *imf, const short is_copy);
+ void  BKE_makepicstring(char *string, const char *base, const char *relbase, int frame, char imtype, const short use_ext, const short use_frames);
+ int           BKE_add_image_extension(char *string, const char imtype);
+ char  BKE_ftype_to_imtype(const int ftype);
+ int           BKE_imtype_to_ftype(char imtype);
+ int           BKE_imtype_is_movie(const char imtype);
 -int           BKE_imtype_supports_alpha(const char imtype);
+ int           BKE_imtype_supports_zbuf(const char imtype);
+ int           BKE_imtype_supports_compress(const char imtype);
+ int           BKE_imtype_supports_quality(const char imtype);
++char    BKE_imtype_valid_channels(const char imtype);
+ char  BKE_imtype_valid_depths(const char imtype);
+ char    BKE_imtype_from_arg(const char *arg);
  
  struct anim *openanim(const char *name, int flags, int streamindex);
  
@@@ -105,6 -114,6 +115,10 @@@ struct RenderResult
        /* image-user gets a new image, check settings */
  #define IMA_SIGNAL_USER_NEW_IMAGE     6
  
++#define IMA_CHAN_FLAG_BW    1
++#define IMA_CHAN_FLAG_RGB   2
++#define IMA_CHAN_FLAG_ALPHA 4
++
  /* depending Image type, and (optional) ImageUser setting it returns ibuf */
  /* always call to make signals work */
  struct ImBuf *BKE_image_get_ibuf(struct Image *ima, struct ImageUser *iuser);
index 8e7645d721ead589c6ad6d82c06f2ef09a1c303f,8e7645d721ead589c6ad6d82c06f2ef09a1c303f..0079ecb7d9c37739de541be9364c5c4ee97c1439
@@@ -91,7 -91,7 +91,7 @@@ void end_render_materials(struct Main *
  
  int material_in_material(struct Material *parmat, struct Material *mat);
  
--void ramp_blend(int type, float *r, float *g, float *b, float fac, const float col[3]);
++void  ramp_blend(int type, float r_col[3], const float fac, const float col[3]);
  
  /* copy/paste */
  void clear_matcopybuf(void);
index c66e49f29069e499cc1964e18aae1902048da0b6,c66e49f29069e499cc1964e18aae1902048da0b6..f491761f3f2abd64e12fc6266f36b8b38f6d6f8f
@@@ -217,7 -217,7 +217,7 @@@ typedef struct ParticleDrawData 
        float *ndata, *nd;              /* normal data */
        float *cdata, *cd;              /* color data */
        float *vedata, *ved;    /* velocity data */
--      float *ma_r, *ma_g, *ma_b;
++      float *ma_col;
        int tot_vec_size, flag;
        int totpoint, totve;
  } ParticleDrawData;
index 9f4fae7dc2e3bfbf9c2198bf2e4919c2db1dfecc,9f4fae7dc2e3bfbf9c2198bf2e4919c2db1dfecc..d1b0acf7142d5b36ab7c2251a33d922891c64fda
@@@ -127,6 -127,6 +127,9 @@@ typedef struct PTCacheID 
        unsigned int stack_index;
        unsigned int flag;
  
++      unsigned int default_step;
++      unsigned int max_step;
++
        /* flags defined in DNA_object_force.h */
        unsigned int data_types, info_types;
  
index 4793e83df53f1a308dce5f235878e695573f56f3,4793e83df53f1a308dce5f235878e695573f56f3..140f596f78c0a3f052f8d1ffa6494c67a60636b1
@@@ -2301,14 -2301,14 +2301,16 @@@ CCGError ccgSubSurf_stitchFaces(CCGSubS
        /* zero */
        for (i=0; i<numEffectedV; i++) {
                CCGVert *v = effectedV[i];
--              VertDataZero(VERT_getCo(v, lvl));
++              if(v->numFaces)
++                      VertDataZero(VERT_getCo(v, lvl));
        }
  
        for (i=0; i<numEffectedE; i++) {
                CCGEdge *e = effectedE[i];
  
--              for (x=0; x<edgeSize; x++)
--                      VertDataZero(EDGE_getCo(e, lvl, x));
++              if(e->numFaces)
++                      for (x=0; x<edgeSize; x++)
++                              VertDataZero(EDGE_getCo(e, lvl, x));
        }
  
        /* add */
        /* average */
        for (i=0; i<numEffectedV; i++) {
                CCGVert *v = effectedV[i];
--              VertDataMulN(VERT_getCo(v, lvl), 1.0f/v->numFaces);
++              if(v->numFaces)
++                      VertDataMulN(VERT_getCo(v, lvl), 1.0f/v->numFaces);
        }
  
        for (i=0; i<numEffectedE; i++) {
                VertDataCopy(EDGE_getCo(e, lvl, 0), VERT_getCo(e->v0, lvl));
                VertDataCopy(EDGE_getCo(e, lvl, edgeSize-1), VERT_getCo(e->v1, lvl));
  
--              for (x=1; x<edgeSize-1; x++)
--                      VertDataMulN(EDGE_getCo(e, lvl, x), 1.0f/e->numFaces);
++              if(e->numFaces)
++                      for (x=1; x<edgeSize-1; x++)
++                              VertDataMulN(EDGE_getCo(e, lvl, x), 1.0f/e->numFaces);
        }
  
        /* copy */
index a76ea1852ded4f636c20712ff65c2bc05e86d3ba,d03e01ffca7af3d383ad210dfee85af19e6feb4d..216dbf8b2c269f40a55c1ff2385df5b56a1c6cf3
@@@ -1341,7 -1341,6 +1341,7 @@@ static void emDM_getEdge(DerivedMesh *d
        edge_r->flag = ME_EDGEDRAW|ME_EDGERENDER;
        if (ee->seam) edge_r->flag |= ME_SEAM;
        if (ee->sharp) edge_r->flag |= ME_SHARP;
 +      if (ee->freestyle) edge_r->flag |= ME_FREESTYLE_EDGE;
  #if 0
        /* this needs setup of f2 field */
        if (!ee->f2) edge_r->flag |= ME_LOOSEEDGE;
@@@ -1442,7 -1441,6 +1442,7 @@@ static void emDM_copyEdgeArray(DerivedM
                edge_r->flag = ME_EDGEDRAW|ME_EDGERENDER;
                if (ee->seam) edge_r->flag |= ME_SEAM;
                if (ee->sharp) edge_r->flag |= ME_SHARP;
 +              if (ee->freestyle) edge_r->flag |= ME_FREESTYLE_EDGE;
  #if 0
                /* this needs setup of f2 field */
                if (!ee->f2) edge_r->flag |= ME_LOOSEEDGE;
@@@ -1777,31 -1775,31 +1777,29 @@@ static void add_orco_dm(Object *ob, Edi
   * happens on enter/exit wpaint.
   */
  
--void weight_to_rgb(float input, float *fr, float *fg, float *fb)
++void weight_to_rgb(float r_rgb[3], const float weight)
  {
--      float blend;
--      
--      blend= ((input/2.0f)+0.5f);
--      
--      if (input<=0.25f){      // blue->cyan
--              *fr= 0.0f;
--              *fg= blend*input*4.0f;
--              *fb= blend;
++      const float blend= ((weight/2.0f)+0.5f);
++
++      if (weight<=0.25f){     // blue->cyan
++              r_rgb[0]= 0.0f;
++              r_rgb[1]= blend*weight*4.0f;
++              r_rgb[2]= blend;
        }
--      else if (input<=0.50f){ // cyan->green
--              *fr= 0.0f;
--              *fg= blend;
--              *fb= blend*(1.0f-((input-0.25f)*4.0f)); 
++      else if (weight<=0.50f){        // cyan->green
++              r_rgb[0]= 0.0f;
++              r_rgb[1]= blend;
++              r_rgb[2]= blend*(1.0f-((weight-0.25f)*4.0f));
        }
--      else if (input <= 0.75f){       // green->yellow
--              *fr= blend * ((input-0.50f)*4.0f);
--              *fg= blend;
--              *fb= 0.0f;
++      else if (weight <= 0.75f){      // green->yellow
++              r_rgb[0]= blend * ((weight-0.50f)*4.0f);
++              r_rgb[1]= blend;
++              r_rgb[2]= 0.0f;
        }
--      else if (input <= 1.0f){ // yellow->red
--              *fr= blend;
--              *fg= blend * (1.0f-((input-0.75f)*4.0f)); 
--              *fb= 0.0f;
++      else if (weight <= 1.0f){ // yellow->red
++              r_rgb[0]= blend;
++              r_rgb[1]= blend * (1.0f-((weight-0.75f)*4.0f));
++              r_rgb[2]= 0.0f;
        }
  }
  
@@@ -1866,7 -1864,7 +1864,7 @@@ static void calc_weightpaint_vert_color
        if(coba)
                do_colorband(coba, input, colf);
        else
--              weight_to_rgb(input, colf, colf+1, colf+2);
++              weight_to_rgb(colf, input);
        
        col[3] = (unsigned char)(colf[0] * 255.0f);
        col[2] = (unsigned char)(colf[1] * 255.0f);
@@@ -2131,9 -2129,9 +2129,9 @@@ static void mesh_calc_modifiers(Scene *
                                        DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
                                        DM_add_face_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
  
-                                       range_vni(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0);
-                                       range_vni(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0);
-                                       range_vni(DM_get_face_data_layer(dm, CD_ORIGINDEX), dm->numFaceData, 0);
+                                       range_vn_i(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0);
+                                       range_vn_i(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0);
+                                       range_vn_i(DM_get_face_data_layer(dm, CD_ORIGINDEX), dm->numFaceData, 0);
                                }
                        }
  
index 0e8d598da3d5ac63107bf498680aeba33941c5e0,0e8d598da3d5ac63107bf498680aeba33941c5e0..a8644618945ee58aa459f77b24b545b5e0c0d26e
@@@ -451,7 -451,7 +451,7 @@@ int blender_test_break(void
  #define MAXUNDONAME   64
  typedef struct UndoElem {
        struct UndoElem *next, *prev;
--      char str[FILE_MAXDIR+FILE_MAXFILE];
++      char str[FILE_MAX];
        char name[MAXUNDONAME];
        MemFile memfile;
        uintptr_t undosize;
@@@ -536,7 -536,7 +536,7 @@@ void BKE_write_undo(bContext *C, const 
        /* disk save version */
        if(UNDO_DISK) {
                static int counter= 0;
--              char filepath[FILE_MAXDIR+FILE_MAXFILE];
++              char filepath[FILE_MAX];
                char numstr[32];
                int fileflags = G.fileflags & ~(G_FILE_HISTORY); /* don't do file history on undo */
  
@@@ -702,7 -702,7 +702,7 @@@ void BKE_undo_save_quit(void
        UndoElem *uel;
        MemFileChunk *chunk;
        int file;
--      char str[FILE_MAXDIR+FILE_MAXFILE];
++      char str[FILE_MAX];
        
        if( (U.uiflag & USER_GLOBALUNDO)==0) return;
        
index 8a6e8faf29af2055e15715ab6c397d8fa4266460,8a6e8faf29af2055e15715ab6c397d8fa4266460..358c63b4f9f819384d02a8847f5c14b124eeabcd
@@@ -169,6 -169,6 +169,7 @@@ Curve *add_curve(const char *name, int 
        cu->texflag= CU_AUTOSPACE;
        cu->smallcaps_scale= 0.75f;
        cu->twist_mode= CU_TWIST_MINIMUM;       // XXX: this one seems to be the best one in most cases, at least for curve deform...
++      cu->type= type;
        
        cu->bb= unit_boundbox();
        
@@@ -303,16 -303,16 +304,23 @@@ ListBase *curve_editnurbs(Curve *cu
  short curve_type(Curve *cu)
  {
        Nurb *nu;
++      int type= cu->type;
++
        if(cu->vfont) {
                return OB_FONT;
        }
--      for (nu= cu->nurb.first; nu; nu= nu->next) {
--              if(nu->pntsv>1) {
--                      return OB_SURF;
++
++      if(!cu->type) {
++              type= OB_CURVE;
++
++              for (nu= cu->nurb.first; nu; nu= nu->next) {
++                      if(nu->pntsv>1) {
++                              type= OB_SURF;
++                      }
                }
        }
--      
--      return OB_CURVE;
++
++      return type;
  }
  
  void update_curve_dimension(Curve *cu)
index 36ae764198a6935d117f016dcd21ec5015fc06da,b5b345c04a13444cc07dbb3b69ccaba634b1b1bf..519ac1cf53417068688c6a37b33c5377a23f5f76
@@@ -976,7 -976,7 +976,7 @@@ struct DynamicPaintSurface *dynamicPain
        surface->wave_timescale = 1.0f;
        surface->wave_spring = 0.20f;
  
-       modifier_path_init(surface->image_output_path, sizeof(surface->image_output_path), "dynamicpaint");
+       modifier_path_init(surface->image_output_path, sizeof(surface->image_output_path), "cache_dynamicpaint");
  
        dynamicPaintSurface_setUniqueName(surface, "Surface");
  
@@@ -1307,7 -1307,7 +1307,7 @@@ void dynamicPaint_setInitialColor(Dynam
  
                if (!tex) return;
  
-               /* get uv layer */
+               /* get uv map */
                CustomData_validate_layer_name(&dm->faceData, CD_MTFACE, surface->init_layername, uvname);
                tface = CustomData_get_layer_named(&dm->faceData, CD_MTFACE, uvname);
                if (!tface) return;
@@@ -1681,7 -1681,7 +1681,7 @@@ static struct DerivedMesh *dynamicPaint
                                                                        for (; j<((mface[i].v4)?4:3); j++) {
                                                                                int index = (j==0)?mface[i].v1: (j==1)?mface[i].v2: (j==2)?mface[i].v3: mface[i].v4;
  
--                                                                              weight_to_rgb(weight[index], temp_color, temp_color+1, temp_color+2);
++                                                                              weight_to_rgb(temp_color, weight[index]);
                                                                                col[i*4+j].r = FTOCHAR(temp_color[2]);
                                                                                col[i*4+j].g = FTOCHAR(temp_color[1]);
                                                                                col[i*4+j].b = FTOCHAR(temp_color[0]);
@@@ -2094,7 -2094,7 +2094,7 @@@ int dynamicPaint_createUVSurface(Dynami
        numOfFaces = dm->getNumFaces(dm);
        mface = dm->getFaceArray(dm);
  
-       /* get uv layer */
+       /* get uv map */
        CustomData_validate_layer_name(&dm->faceData, CD_MTFACE, surface->uvlayer_name, uvname);
        tface = CustomData_get_layer_named(&dm->faceData, CD_MTFACE, uvname);
  
@@@ -2527,13 -2527,13 +2527,13 @@@ void dynamicPaint_outputSurfaceImage(Dy
        PaintSurfaceData *sData = surface->data;
        ImgSeqFormatData *f_data = (ImgSeqFormatData*)sData->format_data;
        /* OpenEXR or PNG       */
-       int format = (surface->image_fileformat & MOD_DPAINT_IMGFORMAT_OPENEXR) ? R_OPENEXR : R_PNG;
+       int format = (surface->image_fileformat & MOD_DPAINT_IMGFORMAT_OPENEXR) ? R_IMF_IMTYPE_OPENEXR : R_IMF_IMTYPE_PNG;
        char output_file[FILE_MAX];
  
        if (!sData || !sData->type_data) {setError(surface->canvas, "Image save failed: Invalid surface.");return;}
        /* if selected format is openexr, but current build doesnt support one */
        #ifndef WITH_OPENEXR
-       if (format == R_OPENEXR) format = R_PNG;
+       if (format == R_IMF_IMTYPE_OPENEXR) format = R_IMF_IMTYPE_PNG;
        #endif
        BLI_strncpy(output_file, filename, sizeof(output_file));
        BKE_add_image_extension(output_file, format);
        /* Set output format, png in case exr isnt supported */
        ibuf->ftype= PNG|95;
  #ifdef WITH_OPENEXR
-       if (format == R_OPENEXR) {      /* OpenEXR 32-bit float */
+       if (format == R_IMF_IMTYPE_OPENEXR) {   /* OpenEXR 32-bit float */
                ibuf->ftype = OPENEXR | OPENEXR_COMPRESS;
        }
  #endif
index a61ae70502024a8ee9b6bab442b9b6f7aecca8a7,964e15f494d3f00682e2e144805452fe141d3727..c7f74f37a2d83604561c50f9212ff716fcf0788c
@@@ -556,13 -556,13 +556,13 @@@ Image *BKE_add_image_size(unsigned int 
        if (ima) {
                ImBuf *ibuf;
                
-               BLI_strncpy(ima->name, name, FILE_MAX);
+               /* BLI_strncpy(ima->name, name, FILE_MAX); */ /* dont do this, this writes in ain invalid filepath! */
                ima->gen_x= width;
                ima->gen_y= height;
                ima->gen_type= uvtestgrid;
                ima->gen_flag |= (floatbuf ? IMA_GEN_FLOAT : 0);
                
-               ibuf= add_ibuf_size(width, height, name, depth, floatbuf, uvtestgrid, color);
+               ibuf= add_ibuf_size(width, height, ima->name, depth, floatbuf, uvtestgrid, color);
                image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
                
                ima->ok= IMA_OK_LOADED;
@@@ -601,7 -601,7 +601,7 @@@ void BKE_image_memorypack(Image *ima
        }
        
        ibuf->ftype= PNG;
-       ibuf->depth= 32;
+       ibuf->planes= R_IMF_PLANES_RGBA;
        
        IMB_saveiff(ibuf, ibuf->name, IB_rect | IB_mem);
        if(ibuf->encodedbuffer==NULL) {
@@@ -800,175 -800,287 +800,302 @@@ void BKE_image_all_free_anim_ibufs(int 
  
  /* *********** READ AND WRITE ************** */
  
- int BKE_imtype_to_ftype(int imtype)
+ int BKE_imtype_to_ftype(const char imtype)
  {
-       if(imtype==R_TARGA)
+       if(imtype==R_IMF_IMTYPE_TARGA)
                return TGA;
-       else if(imtype==R_RAWTGA)
+       else if(imtype==R_IMF_IMTYPE_RAWTGA)
                return RAWTGA;
-       else if(imtype== R_IRIS) 
+       else if(imtype== R_IMF_IMTYPE_IRIS) 
                return IMAGIC;
  #ifdef WITH_HDR
-       else if (imtype==R_RADHDR)
+       else if (imtype==R_IMF_IMTYPE_RADHDR)
                return RADHDR;
  #endif
-       else if (imtype==R_PNG)
+       else if (imtype==R_IMF_IMTYPE_PNG)
                return PNG;
  #ifdef WITH_DDS
-       else if (imtype==R_DDS)
+       else if (imtype==R_IMF_IMTYPE_DDS)
                return DDS;
  #endif
-       else if (imtype==R_BMP)
+       else if (imtype==R_IMF_IMTYPE_BMP)
                return BMP;
  #ifdef WITH_TIFF
-       else if (imtype==R_TIFF)
+       else if (imtype==R_IMF_IMTYPE_TIFF)
                return TIF;
  #endif
-       else if (imtype==R_OPENEXR || imtype==R_MULTILAYER)
+       else if (imtype==R_IMF_IMTYPE_OPENEXR || imtype==R_IMF_IMTYPE_MULTILAYER)
                return OPENEXR;
  #ifdef WITH_CINEON
-       else if (imtype==R_CINEON)
+       else if (imtype==R_IMF_IMTYPE_CINEON)
                return CINEON;
-       else if (imtype==R_DPX)
+       else if (imtype==R_IMF_IMTYPE_DPX)
                return DPX;
  #endif
  #ifdef WITH_OPENJPEG
-       else if(imtype==R_JP2)
+       else if(imtype==R_IMF_IMTYPE_JP2)
                return JP2;
  #endif
        else
                return JPG|90;
  }
  
int BKE_ftype_to_imtype(int ftype)
char BKE_ftype_to_imtype(const int ftype)
  {
        if(ftype==0)
-               return TGA;
+               return R_IMF_IMTYPE_TARGA;
        else if(ftype == IMAGIC) 
-               return R_IRIS;
+               return R_IMF_IMTYPE_IRIS;
  #ifdef WITH_HDR
        else if (ftype & RADHDR)
-               return R_RADHDR;
+               return R_IMF_IMTYPE_RADHDR;
  #endif
        else if (ftype & PNG)
-               return R_PNG;
+               return R_IMF_IMTYPE_PNG;
  #ifdef WITH_DDS
        else if (ftype & DDS)
-               return R_DDS;
+               return R_IMF_IMTYPE_DDS;
  #endif
        else if (ftype & BMP)
-               return R_BMP;
+               return R_IMF_IMTYPE_BMP;
  #ifdef WITH_TIFF
        else if (ftype & TIF)
-               return R_TIFF;
+               return R_IMF_IMTYPE_TIFF;
  #endif
        else if (ftype & OPENEXR)
-               return R_OPENEXR;
+               return R_IMF_IMTYPE_OPENEXR;
  #ifdef WITH_CINEON
        else if (ftype & CINEON)
-               return R_CINEON;
+               return R_IMF_IMTYPE_CINEON;
        else if (ftype & DPX)
-               return R_DPX;
+               return R_IMF_IMTYPE_DPX;
  #endif
        else if (ftype & TGA)
-               return R_TARGA;
+               return R_IMF_IMTYPE_TARGA;
        else if(ftype & RAWTGA)
-               return R_RAWTGA;
+               return R_IMF_IMTYPE_RAWTGA;
  #ifdef WITH_OPENJPEG
        else if(ftype & JP2)
-               return R_JP2;
+               return R_IMF_IMTYPE_JP2;
  #endif
        else
-               return R_JPEG90;
+               return R_IMF_IMTYPE_JPEG90;
+ }
+ int BKE_imtype_is_movie(const char imtype)
+ {
+       switch(imtype) {
+       case R_IMF_IMTYPE_AVIRAW:
+       case R_IMF_IMTYPE_AVIJPEG:
+       case R_IMF_IMTYPE_AVICODEC:
+       case R_IMF_IMTYPE_QUICKTIME:
+       case R_IMF_IMTYPE_FFMPEG:
+       case R_IMF_IMTYPE_H264:
+       case R_IMF_IMTYPE_THEORA:
+       case R_IMF_IMTYPE_XVID:
+       case R_IMF_IMTYPE_FRAMESERVER:
+                       return 1;
+       }
+       return 0;
+ }
 -int BKE_imtype_supports_alpha(const char imtype)
 -{
 -      switch(imtype) {
 -      case R_IMF_IMTYPE_TARGA:
 -      case R_IMF_IMTYPE_IRIS:
 -      case R_IMF_IMTYPE_PNG:
 -      /* case R_IMF_IMTYPE_BMP: */ /* read but not write */
 -      case R_IMF_IMTYPE_RADHDR:
 -      case R_IMF_IMTYPE_TIFF:
 -      case R_IMF_IMTYPE_OPENEXR:
 -      case R_IMF_IMTYPE_MULTILAYER:
 -      case R_IMF_IMTYPE_DDS:
 -      case R_IMF_IMTYPE_JP2:
 -                      return 1;
 -      }
 -      return 0;
 -}
 -
+ int BKE_imtype_supports_zbuf(const char imtype)
+ {
+       switch(imtype) {
+       case R_IMF_IMTYPE_IRIZ:
+       case R_IMF_IMTYPE_OPENEXR: /* but not R_IMF_IMTYPE_MULTILAYER */
+                       return 1;
+       }
+       return 0;
  }
  
+ int BKE_imtype_supports_compress(const char imtype)
+ {
+       switch(imtype) {
+       case R_IMF_IMTYPE_PNG:
+                       return 1;
+       }
+       return 0;
+ }
  
- int BKE_imtype_is_movie(int imtype)
+ int BKE_imtype_supports_quality(const char imtype)
  {
        switch(imtype) {
-       case R_AVIRAW:
-       case R_AVIJPEG:
-       case R_AVICODEC:
-       case R_QUICKTIME:
-       case R_FFMPEG:
-       case R_H264:
-       case R_THEORA:
-       case R_XVID:
-       case R_FRAMESERVER:
+       case R_IMF_IMTYPE_JPEG90:
+       case R_IMF_IMTYPE_JP2:
+       case R_IMF_IMTYPE_AVIJPEG:
                        return 1;
        }
        return 0;
  }
  
- int BKE_add_image_extension(char *string, int imtype)
++char BKE_imtype_valid_channels(const char imtype)
++{
++      char chan_flag= IMA_CHAN_FLAG_RGB; /* assume all support rgb */
++
++      /* alpha */
++      switch(imtype) {
++      case R_IMF_IMTYPE_TARGA:
++      case R_IMF_IMTYPE_IRIS:
++      case R_IMF_IMTYPE_PNG:
++      /* case R_IMF_IMTYPE_BMP: */ /* read but not write */
++      case R_IMF_IMTYPE_RADHDR:
++      case R_IMF_IMTYPE_TIFF:
++      case R_IMF_IMTYPE_OPENEXR:
++      case R_IMF_IMTYPE_MULTILAYER:
++      case R_IMF_IMTYPE_DDS:
++      case R_IMF_IMTYPE_JP2:
++                      chan_flag |= IMA_CHAN_FLAG_ALPHA;
++      }
++
++      /* bw */
++      switch(imtype) {
++      case R_IMF_IMTYPE_PNG:
++      case R_IMF_IMTYPE_JPEG90:
++      case R_IMF_IMTYPE_TARGA:
++      case R_IMF_IMTYPE_RAWTGA:
++      case R_IMF_IMTYPE_TIFF:
++      case R_IMF_IMTYPE_IRIS:
++                      chan_flag |= IMA_CHAN_FLAG_BW;
++      }
++
++      return chan_flag;
++}
++
+ char BKE_imtype_valid_depths(const char imtype)
+ {
+       switch (imtype) {
+       case R_IMF_IMTYPE_RADHDR:
+               return R_IMF_CHAN_DEPTH_32;
+       case R_IMF_IMTYPE_TIFF:
+               return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_16;
+       case R_IMF_IMTYPE_OPENEXR:
+               return R_IMF_CHAN_DEPTH_16 | R_IMF_CHAN_DEPTH_32;
+       case R_IMF_IMTYPE_MULTILAYER:
+               return R_IMF_CHAN_DEPTH_32;
+       /* eeh, cineone does some strange 10bits per channel */
+       case R_IMF_IMTYPE_DPX:
+       case R_IMF_IMTYPE_CINEON:
+               return R_IMF_CHAN_DEPTH_12;
+       case R_IMF_IMTYPE_JP2:
+               return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16;
+       /* most formats are 8bit only */
+       default:
+               return R_IMF_CHAN_DEPTH_8;
+       }
+ }
+ /* string is from command line --render-format arg, keep in sync with
+  * creator.c help info */
+ char BKE_imtype_from_arg(const char *imtype_arg)
+ {
+       if      (!strcmp(imtype_arg,"TGA")) return R_IMF_IMTYPE_TARGA;
+       else if (!strcmp(imtype_arg,"IRIS")) return R_IMF_IMTYPE_IRIS;
+ #ifdef WITH_DDS
+       else if (!strcmp(imtype_arg,"DDS")) return R_IMF_IMTYPE_DDS;
+ #endif
+       else if (!strcmp(imtype_arg,"JPEG")) return R_IMF_IMTYPE_JPEG90;
+       else if (!strcmp(imtype_arg,"IRIZ")) return R_IMF_IMTYPE_IRIZ;
+       else if (!strcmp(imtype_arg,"RAWTGA")) return R_IMF_IMTYPE_RAWTGA;
+       else if (!strcmp(imtype_arg,"AVIRAW")) return R_IMF_IMTYPE_AVIRAW;
+       else if (!strcmp(imtype_arg,"AVIJPEG")) return R_IMF_IMTYPE_AVIJPEG;
+       else if (!strcmp(imtype_arg,"PNG")) return R_IMF_IMTYPE_PNG;
+       else if (!strcmp(imtype_arg,"AVICODEC")) return R_IMF_IMTYPE_AVICODEC;
+       else if (!strcmp(imtype_arg,"QUICKTIME")) return R_IMF_IMTYPE_QUICKTIME;
+       else if (!strcmp(imtype_arg,"BMP")) return R_IMF_IMTYPE_BMP;
+ #ifdef WITH_HDR
+       else if (!strcmp(imtype_arg,"HDR")) return R_IMF_IMTYPE_RADHDR;
+ #endif
+ #ifdef WITH_TIFF
+       else if (!strcmp(imtype_arg,"TIFF")) return R_IMF_IMTYPE_TIFF;
+ #endif
+ #ifdef WITH_OPENEXR
+       else if (!strcmp(imtype_arg,"EXR")) return R_IMF_IMTYPE_OPENEXR;
+       else if (!strcmp(imtype_arg,"MULTILAYER")) return R_IMF_IMTYPE_MULTILAYER;
+ #endif
+       else if (!strcmp(imtype_arg,"MPEG")) return R_IMF_IMTYPE_FFMPEG;
+       else if (!strcmp(imtype_arg,"FRAMESERVER")) return R_IMF_IMTYPE_FRAMESERVER;
+ #ifdef WITH_CINEON
+       else if (!strcmp(imtype_arg,"CINEON")) return R_IMF_IMTYPE_CINEON;
+       else if (!strcmp(imtype_arg,"DPX")) return R_IMF_IMTYPE_DPX;
+ #endif
+ #ifdef WITH_OPENJPEG
+       else if (!strcmp(imtype_arg,"JP2")) return R_IMF_IMTYPE_JP2;
+ #endif
+       else return R_IMF_IMTYPE_INVALID;
+ }
+ int BKE_add_image_extension(char *string, const char imtype)
  {
        const char *extension= NULL;
        
-       if(imtype== R_IRIS) {
+       if(imtype== R_IMF_IMTYPE_IRIS) {
                if(!BLI_testextensie(string, ".rgb"))
                        extension= ".rgb";
        }
-       else if(imtype==R_IRIZ) {
+       else if(imtype==R_IMF_IMTYPE_IRIZ) {
                if(!BLI_testextensie(string, ".rgb"))
                        extension= ".rgb";
        }
  #ifdef WITH_HDR
-       else if(imtype==R_RADHDR) {
+       else if(imtype==R_IMF_IMTYPE_RADHDR) {
                if(!BLI_testextensie(string, ".hdr"))
                        extension= ".hdr";
        }
  #endif
-       else if (ELEM5(imtype, R_PNG, R_FFMPEG, R_H264, R_THEORA, R_XVID)) {
+       else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
                if(!BLI_testextensie(string, ".png"))
                        extension= ".png";
        }
  #ifdef WITH_DDS
-       else if(imtype==R_DDS) {
+       else if(imtype==R_IMF_IMTYPE_DDS) {
                if(!BLI_testextensie(string, ".dds"))
                        extension= ".dds";
        }
  #endif
-       else if(imtype==R_RAWTGA) {
+       else if(imtype==R_IMF_IMTYPE_RAWTGA) {
                if(!BLI_testextensie(string, ".tga"))
                        extension= ".tga";
        }
-       else if(imtype==R_BMP) {
+       else if(imtype==R_IMF_IMTYPE_BMP) {
                if(!BLI_testextensie(string, ".bmp"))
                        extension= ".bmp";
        }
  #ifdef WITH_TIFF
-       else if(imtype==R_TIFF) {
+       else if(imtype==R_IMF_IMTYPE_TIFF) {
                if(!BLI_testextensie(string, ".tif") && 
                        !BLI_testextensie(string, ".tiff")) extension= ".tif";
        }
  #endif
  #ifdef WITH_OPENEXR
-       else if( ELEM(imtype, R_OPENEXR, R_MULTILAYER)) {
+       else if( ELEM(imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER)) {
                if(!BLI_testextensie(string, ".exr"))
                        extension= ".exr";
        }
  #endif
  #ifdef WITH_CINEON
-       else if(imtype==R_CINEON){
+       else if(imtype==R_IMF_IMTYPE_CINEON){
                if (!BLI_testextensie(string, ".cin"))
                        extension= ".cin";
        }
-       else if(imtype==R_DPX){
+       else if(imtype==R_IMF_IMTYPE_DPX){
                if (!BLI_testextensie(string, ".dpx"))
                        extension= ".dpx";
        }
  #endif
-       else if(imtype==R_TARGA) {
+       else if(imtype==R_IMF_IMTYPE_TARGA) {
                if(!BLI_testextensie(string, ".tga"))
                        extension= ".tga";
        }
  #ifdef WITH_OPENJPEG
-       else if(imtype==R_JP2) {
+       else if(imtype==R_IMF_IMTYPE_JP2) {
                if(!BLI_testextensie(string, ".jp2"))
                        extension= ".jp2";
        }
  #endif
-       else { //   R_AVICODEC, R_AVIRAW, R_AVIJPEG, R_JPEG90, R_QUICKTIME etc
+       else { //   R_IMF_IMTYPE_AVICODEC, R_IMF_IMTYPE_AVIRAW, R_IMF_IMTYPE_AVIJPEG, R_IMF_IMTYPE_JPEG90, R_IMF_IMTYPE_QUICKTIME etc
                if(!( BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
                        extension= ".jpg";
        }
@@@ -1371,98 -1483,101 +1498,102 @@@ int BKE_alphatest_ibuf(ImBuf *ibuf
        return FALSE;
  }
  
- int BKE_write_ibuf(ImBuf *ibuf, const char *name, int imtype, int subimtype, int quality)
++/* note: imf->planes is ignored here, its assumed the image channels
++ * are already set */
+ int BKE_write_ibuf(ImBuf *ibuf, const char *name, ImageFormatData *imf)
  {
+       char imtype= imf->imtype;
+       char compress= imf->compress;
+       char quality= imf->quality;
        int ok;
-       (void)subimtype; /* quies unused warnings */
  
        if(imtype == -1) {
                /* use whatever existing image type is set by 'ibuf' */
        }
-       else if(imtype== R_IRIS) {
+       else if(imtype== R_IMF_IMTYPE_IRIS) {
                ibuf->ftype= IMAGIC;
        }
  #ifdef WITH_HDR
-       else if (imtype==R_RADHDR) {
+       else if (imtype==R_IMF_IMTYPE_RADHDR) {
                ibuf->ftype= RADHDR;
        }
  #endif
-       else if (ELEM5(imtype, R_PNG, R_FFMPEG, R_H264, R_THEORA, R_XVID)) {
+       else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
                ibuf->ftype= PNG;
  
-               if(imtype==R_PNG)
-                       ibuf->ftype |= quality;  /* quality is actually compression 0-100 --> 0-9 */
+               if(imtype==R_IMF_IMTYPE_PNG)
+                       ibuf->ftype |= compress;
  
        }
  #ifdef WITH_DDS
-       else if (imtype==R_DDS) {
+       else if (imtype==R_IMF_IMTYPE_DDS) {
                ibuf->ftype= DDS;
        }
  #endif
-       else if (imtype==R_BMP) {
+       else if (imtype==R_IMF_IMTYPE_BMP) {
                ibuf->ftype= BMP;
        }
  #ifdef WITH_TIFF
-       else if (imtype==R_TIFF) {
+       else if (imtype==R_IMF_IMTYPE_TIFF) {
                ibuf->ftype= TIF;
  
-               if(subimtype & R_TIFF_16BIT)
+               if(imf->depth == R_IMF_CHAN_DEPTH_16)
                        ibuf->ftype |= TIF_16BIT;
        }
  #endif
  #ifdef WITH_OPENEXR
-       else if (imtype==R_OPENEXR || imtype==R_MULTILAYER) {
+       else if (imtype==R_IMF_IMTYPE_OPENEXR || imtype==R_IMF_IMTYPE_MULTILAYER) {
                ibuf->ftype= OPENEXR;
-               if(subimtype & R_OPENEXR_HALF)
+               if(imf->depth == R_IMF_CHAN_DEPTH_16)
                        ibuf->ftype |= OPENEXR_HALF;
                ibuf->ftype |= (quality & OPENEXR_COMPRESS);
                
-               if(!(subimtype & R_OPENEXR_ZBUF))
+               if(!(imf->flag & R_IMF_FLAG_ZBUF))
                        ibuf->zbuf_float = NULL;        /* signal for exr saving */
                
        }
  #endif
  #ifdef WITH_CINEON
-       else if (imtype==R_CINEON) {
+       else if (imtype==R_IMF_IMTYPE_CINEON) {
                ibuf->ftype = CINEON;
        }
-       else if (imtype==R_DPX) {
+       else if (imtype==R_IMF_IMTYPE_DPX) {
                ibuf->ftype = DPX;
        }
  #endif
-       else if (imtype==R_TARGA) {
+       else if (imtype==R_IMF_IMTYPE_TARGA) {
                ibuf->ftype= TGA;
        }
-       else if(imtype==R_RAWTGA) {
+       else if(imtype==R_IMF_IMTYPE_RAWTGA) {
                ibuf->ftype= RAWTGA;
        }
  #ifdef WITH_OPENJPEG
-       else if(imtype==R_JP2) {
+       else if(imtype==R_IMF_IMTYPE_JP2) {
                if(quality < 10) quality= 90;
                ibuf->ftype= JP2|quality;
                
-               if (subimtype & R_JPEG2K_16BIT) {
+               if (imf->depth == R_IMF_CHAN_DEPTH_16) {
                        ibuf->ftype |= JP2_16BIT;
-               } else if (subimtype & R_JPEG2K_12BIT) {
+               } else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
                        ibuf->ftype |= JP2_12BIT;
                }
                
-               if (subimtype & R_JPEG2K_YCC) {
+               if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
                        ibuf->ftype |= JP2_YCC;
                }
-               
-               if (subimtype & R_JPEG2K_CINE_PRESET) {
+               if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
                        ibuf->ftype |= JP2_CINE;
-                       if (subimtype & R_JPEG2K_CINE_48FPS)
+                       if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48)
                                ibuf->ftype |= JP2_CINE_48FPS;
                }
        }
  #endif
        else {
-               /* R_JPEG90, etc. default we save jpegs */
+               /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
                if(quality < 10) quality= 90;
                ibuf->ftype= JPG|quality;
-               if(ibuf->depth==32) ibuf->depth= 24;    /* unsupported feature only confuses other s/w */
 -              if(ibuf->planes==32) ibuf->planes= 24;  /* unsupported feature only confuses other s/w */
        }
        
        BLI_make_existing_file(name);
        return(ok);
  }
  
- int BKE_write_ibuf_stamp(Scene *scene, struct Object *camera, ImBuf *ibuf, const char *name, int imtype, int subimtype, int quality)
++/* same as BKE_write_ibuf_as but crappy workaround not to perminantly modify
++ * _some_, values in the imbuf */
++int BKE_write_ibuf_as(ImBuf *ibuf, const char *name, ImageFormatData *imf,
++                      const short save_copy)
++{
++      ImBuf ibuf_back= *ibuf;
++      int ok;
++
++      /* all data is rgba anyway,
++       * this just controls how to save for some formats */
++      ibuf->planes= imf->planes;
++
++      ok= BKE_write_ibuf(ibuf, name, imf);
++
++      if (save_copy) {
++              /* note that we are not restoring _all_ settings */
++              ibuf->planes= ibuf_back.planes;
++              ibuf->ftype=  ibuf_back.ftype;
++      }
++
++      return ok;
++}
++
+ int BKE_write_ibuf_stamp(Scene *scene, struct Object *camera, ImBuf *ibuf, const char *name, struct ImageFormatData *imf)
  {
        if(scene && scene->r.stamp & R_STAMP_ALL)
                BKE_stamp_info(scene, camera, ibuf);
  
-       return BKE_write_ibuf(ibuf, name, imtype, subimtype, quality);
+       return BKE_write_ibuf(ibuf, name, imf);
  }
  
  
- void BKE_makepicstring(char *string, const char *base, const char *relbase, int frame, int imtype, const short use_ext, const short use_frames)
+ void BKE_makepicstring(char *string, const char *base, const char *relbase, int frame, const char imtype, const short use_ext, const short use_frames)
  {
        if (string==NULL) return;
        BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
@@@ -2414,13 -2529,13 +2568,13 @@@ int BKE_image_has_alpha(struct Image *i
  {
        ImBuf *ibuf;
        void *lock;
-       int depth;
+       int planes;
        
        ibuf= BKE_image_acquire_ibuf(image, NULL, &lock);
-       depth = (ibuf?ibuf->depth:0);
+       planes = (ibuf?ibuf->planes:0);
        BKE_image_release_ibuf(image, lock);
  
-       if (depth == 32)
+       if (planes == 32)
                return 1;
        else
                return 0;
index 6c8a72825c794f2585dcb24137fde95a2f48b33f,48c6d6b2a19313efa95a663d77382fe6ffe40866..9d196a1104bc756cc93aee66f012f9586957e64c
@@@ -145,7 -145,6 +145,7 @@@ void init_material(Material *ma
        ma->tx_limit= 0.0;
        ma->tx_falloff= 1.0;
        ma->shad_alpha= 1.0f;
 +      ma->vcol_alpha= 0;
        
        ma->gloss_mir = ma->gloss_tra= 1.0;
        ma->samp_gloss_mir = ma->samp_gloss_tra= 18;
@@@ -1181,129 -1180,129 +1181,129 @@@ int object_remove_material_slot(Object 
  
  /* r g b = current value, col = new value, fac==0 is no change */
  /* if g==NULL, it only does r channel */
--void ramp_blend(int type, float *r, float *g, float *b, float fac, const float col[3])
++void ramp_blend(int type, float r_col[3], const float fac, const float col[3])
  {
        float tmp, facm= 1.0f-fac;
        
        switch (type) {
                case MA_RAMP_BLEND:
--                      *r = facm*(*r) + fac*col[0];
--                      if(g) {
--                              *g = facm*(*g) + fac*col[1];
--                              *b = facm*(*b) + fac*col[2];
++                      r_col[0] = facm*(r_col[0]) + fac*col[0];
++                      if(r_col[1]) {
++                              r_col[1] = facm*(r_col[1]) + fac*col[1];
++                              r_col[2] = facm*(r_col[2]) + fac*col[2];
                        }
                                break;
                case MA_RAMP_ADD:
--                      *r += fac*col[0];
--                      if(g) {
--                              *g += fac*col[1];
--                              *b += fac*col[2];
++                      r_col[0] += fac*col[0];
++                      if(r_col[1]) {
++                              r_col[1] += fac*col[1];
++                              r_col[2] += fac*col[2];
                        }
                                break;
                case MA_RAMP_MULT:
--                      *r *= (facm + fac*col[0]);
--                      if(g) {
--                              *g *= (facm + fac*col[1]);
--                              *b *= (facm + fac*col[2]);
++                      r_col[0] *= (facm + fac*col[0]);
++                      if(r_col[1]) {
++                              r_col[1] *= (facm + fac*col[1]);
++                              r_col[2] *= (facm + fac*col[2]);
                        }
                                break;
                case MA_RAMP_SCREEN:
--                      *r = 1.0f - (facm + fac*(1.0f - col[0])) * (1.0f - *r);
--                      if(g) {
--                              *g = 1.0f - (facm + fac*(1.0f - col[1])) * (1.0f - *g);
--                              *b = 1.0f - (facm + fac*(1.0f - col[2])) * (1.0f - *b);
++                      r_col[0] = 1.0f - (facm + fac*(1.0f - col[0])) * (1.0f - r_col[0]);
++                      if(r_col[1]) {
++                              r_col[1] = 1.0f - (facm + fac*(1.0f - col[1])) * (1.0f - r_col[1]);
++                              r_col[2] = 1.0f - (facm + fac*(1.0f - col[2])) * (1.0f - r_col[2]);
                        }
                                break;
                case MA_RAMP_OVERLAY:
--                      if(*r < 0.5f)
--                              *r *= (facm + 2.0f*fac*col[0]);
++                      if(r_col[0] < 0.5f)
++                              r_col[0] *= (facm + 2.0f*fac*col[0]);
                        else
--                              *r = 1.0f - (facm + 2.0f*fac*(1.0f - col[0])) * (1.0f - *r);
--                      if(g) {
--                              if(*g < 0.5f)
--                                      *g *= (facm + 2.0f*fac*col[1]);
++                              r_col[0] = 1.0f - (facm + 2.0f*fac*(1.0f - col[0])) * (1.0f - r_col[0]);
++                      if(r_col[1]) {
++                              if(r_col[1] < 0.5f)
++                                      r_col[1] *= (facm + 2.0f*fac*col[1]);
                                else
--                                      *g = 1.0f - (facm + 2.0f*fac*(1.0f - col[1])) * (1.0f - *g);
--                              if(*b < 0.5f)
--                                      *b *= (facm + 2.0f*fac*col[2]);
++                                      r_col[1] = 1.0f - (facm + 2.0f*fac*(1.0f - col[1])) * (1.0f - r_col[1]);
++                              if(r_col[2] < 0.5f)
++                                      r_col[2] *= (facm + 2.0f*fac*col[2]);
                                else
--                                      *b = 1.0f - (facm + 2.0f*fac*(1.0f - col[2])) * (1.0f - *b);
++                                      r_col[2] = 1.0f - (facm + 2.0f*fac*(1.0f - col[2])) * (1.0f - r_col[2]);
                        }
                                break;
                case MA_RAMP_SUB:
--                      *r -= fac*col[0];
--                      if(g) {
--                              *g -= fac*col[1];
--                              *b -= fac*col[2];
++                      r_col[0] -= fac*col[0];
++                      if(r_col[1]) {
++                              r_col[1] -= fac*col[1];
++                              r_col[2] -= fac*col[2];
                        }
                                break;
                case MA_RAMP_DIV:
                        if(col[0]!=0.0f)
--                              *r = facm*(*r) + fac*(*r)/col[0];
--                      if(g) {
++                              r_col[0] = facm*(r_col[0]) + fac*(r_col[0])/col[0];
++                      if(r_col[1]) {
                                if(col[1]!=0.0f)
--                                      *g = facm*(*g) + fac*(*g)/col[1];
++                                      r_col[1] = facm*(r_col[1]) + fac*(r_col[1])/col[1];
                                if(col[2]!=0.0f)
--                                      *b = facm*(*b) + fac*(*b)/col[2];
++                                      r_col[2] = facm*(r_col[2]) + fac*(r_col[2])/col[2];
                        }
                                break;
                case MA_RAMP_DIFF:
--                      *r = facm*(*r) + fac*fabsf(*r-col[0]);
--                      if(g) {
--                              *g = facm*(*g) + fac*fabsf(*g-col[1]);
--                              *b = facm*(*b) + fac*fabsf(*b-col[2]);
++                      r_col[0] = facm*(r_col[0]) + fac*fabsf(r_col[0]-col[0]);
++                      if(r_col[1]) {
++                              r_col[1] = facm*(r_col[1]) + fac*fabsf(r_col[1]-col[1]);
++                              r_col[2] = facm*(r_col[2]) + fac*fabsf(r_col[2]-col[2]);
                        }
                                break;
                case MA_RAMP_DARK:
                        tmp=col[0]+((1-col[0])*facm); 
--                      if(tmp < *r) *r= tmp; 
--                      if(g) { 
++                      if(tmp < r_col[0]) r_col[0]= tmp;
++                      if(r_col[1]) {
                                tmp=col[1]+((1-col[1])*facm); 
--                              if(tmp < *g) *g= tmp; 
++                              if(tmp < r_col[1]) r_col[1]= tmp;
                                tmp=col[2]+((1-col[2])*facm); 
--                              if(tmp < *b) *b= tmp; 
++                              if(tmp < r_col[2]) r_col[2]= tmp;
                        } 
                                break; 
                case MA_RAMP_LIGHT:
                        tmp= fac*col[0];
--                      if(tmp > *r) *r= tmp; 
--                              if(g) {
++                      if(tmp > r_col[0]) r_col[0]= tmp;
++                              if(r_col[1]) {
                                        tmp= fac*col[1];
--                                      if(tmp > *g) *g= tmp; 
++                                      if(tmp > r_col[1]) r_col[1]= tmp;
                                        tmp= fac*col[2];
--                                      if(tmp > *b) *b= tmp; 
++                                      if(tmp > r_col[2]) r_col[2]= tmp;
                                }
                                        break;  
                case MA_RAMP_DODGE:                     
                        
                                
--                      if(*r !=0.0f){
++                      if(r_col[0] !=0.0f){
                                tmp = 1.0f - fac*col[0];
                                if(tmp <= 0.0f)
--                                      *r = 1.0f;
--                              else if ((tmp = (*r) / tmp)> 1.0f)
--                                      *r = 1.0f;
++                                      r_col[0] = 1.0f;
++                              else if ((tmp = (r_col[0]) / tmp)> 1.0f)
++                                      r_col[0] = 1.0f;
                                else 
--                                      *r = tmp;
++                                      r_col[0] = tmp;
                        }
--                      if(g) {
--                              if(*g !=0.0f){
++                      if(r_col[1]) {
++                              if(r_col[1] !=0.0f){
                                        tmp = 1.0f - fac*col[1];
                                        if(tmp <= 0.0f )
--                                              *g = 1.0f;
--                                      else if ((tmp = (*g) / tmp) > 1.0f )
--                                              *g = 1.0f;
++                                              r_col[1] = 1.0f;
++                                      else if ((tmp = (r_col[1]) / tmp) > 1.0f )
++                                              r_col[1] = 1.0f;
                                        else
--                                              *g = tmp;
++                                              r_col[1] = tmp;
                                }
--                              if(*b !=0.0f){
++                              if(r_col[2] !=0.0f){
                                        tmp = 1.0f - fac*col[2];
                                        if(tmp <= 0.0f)
--                                              *b = 1.0f;
--                                      else if ((tmp = (*b) / tmp) > 1.0f )
--                                              *b = 1.0f;
++                                              r_col[2] = 1.0f;
++                                      else if ((tmp = (r_col[2]) / tmp) > 1.0f )
++                                              r_col[2] = 1.0f;
                                        else
--                                              *b = tmp;
++                                              r_col[2] = tmp;
                                }
  
                        }
                        tmp = facm + fac*col[0];
                        
                        if(tmp <= 0.0f)
--                              *r = 0.0f;
--                      else if (( tmp = (1.0f - (1.0f - (*r)) / tmp )) < 0.0f)
--                                      *r = 0.0f;
++                              r_col[0] = 0.0f;
++                      else if (( tmp = (1.0f - (1.0f - (r_col[0])) / tmp )) < 0.0f)
++                                      r_col[0] = 0.0f;
                        else if (tmp > 1.0f)
--                              *r=1.0f;
++                              r_col[0]=1.0f;
                        else 
--                              *r = tmp; 
++                              r_col[0] = tmp;
  
--                      if(g) {
++                      if(r_col[1]) {
                                tmp = facm + fac*col[1];
                                if(tmp <= 0.0f)
--                                      *g = 0.0f;
--                              else if (( tmp = (1.0f - (1.0f - (*g)) / tmp )) < 0.0f )
--                                              *g = 0.0f;
++                                      r_col[1] = 0.0f;
++                              else if (( tmp = (1.0f - (1.0f - (r_col[1])) / tmp )) < 0.0f )
++                                              r_col[1] = 0.0f;
                                else if(tmp >1.0f)
--                                      *g=1.0f;
++                                      r_col[1]=1.0f;
                                else
--                                      *g = tmp;
++                                      r_col[1] = tmp;
  
                                        tmp = facm + fac*col[2];
                                        if(tmp <= 0.0f)
--                                      *b = 0.0f;
--                              else if (( tmp = (1.0f - (1.0f - (*b)) / tmp )) < 0.0f  )
--                                              *b = 0.0f;
++                                      r_col[2] = 0.0f;
++                              else if (( tmp = (1.0f - (1.0f - (r_col[2])) / tmp )) < 0.0f  )
++                                              r_col[2] = 0.0f;
                                else if(tmp >1.0f)
--                                      *b= 1.0f;
++                                      r_col[2]= 1.0f;
                                else
--                                      *b = tmp;
++                                      r_col[2] = tmp;
                        }
                                break;
                case MA_RAMP_HUE:               
--                      if(g){
++                      if(r_col[1]){
                                float rH,rS,rV;
                                float colH,colS,colV; 
                                float tmpr,tmpg,tmpb;
                                rgb_to_hsv(col[0],col[1],col[2],&colH,&colS,&colV);
                                if(colS!=0 ){
--                                      rgb_to_hsv(*r,*g,*b,&rH,&rS,&rV);
++                                      rgb_to_hsv(r_col[0],r_col[1],r_col[2],&rH,&rS,&rV);
                                        hsv_to_rgb( colH , rS, rV, &tmpr, &tmpg, &tmpb);
--                                      *r = facm*(*r) + fac*tmpr;  
--                                      *g = facm*(*g) + fac*tmpg; 
--                                      *b = facm*(*b) + fac*tmpb;
++                                      r_col[0] = facm*(r_col[0]) + fac*tmpr;
++                                      r_col[1] = facm*(r_col[1]) + fac*tmpg;
++                                      r_col[2] = facm*(r_col[2]) + fac*tmpb;
                                }
                        }
                                break;
                case MA_RAMP_SAT:               
--                      if(g){
++                      if(r_col[1]){
                                float rH,rS,rV;
                                float colH,colS,colV;
--                              rgb_to_hsv(*r,*g,*b,&rH,&rS,&rV);
++                              rgb_to_hsv(r_col[0],r_col[1],r_col[2],&rH,&rS,&rV);
                                if(rS!=0){
                                        rgb_to_hsv(col[0],col[1],col[2],&colH,&colS,&colV);
--                                      hsv_to_rgb( rH, (facm*rS +fac*colS), rV, r, g, b);
++                                      hsv_to_rgb( rH, (facm*rS +fac*colS), rV, r_col+0, r_col+1, r_col+2);
                                }
                        }
                                break;
                case MA_RAMP_VAL:               
--                      if(g){
++                      if(r_col[1]){
                                float rH,rS,rV;
                                float colH,colS,colV;
--                              rgb_to_hsv(*r,*g,*b,&rH,&rS,&rV);
++                              rgb_to_hsv(r_col[0],r_col[1],r_col[2],&rH,&rS,&rV);
                                rgb_to_hsv(col[0],col[1],col[2],&colH,&colS,&colV);
--                              hsv_to_rgb( rH, rS, (facm*rV +fac*colV), r, g, b);
++                              hsv_to_rgb( rH, rS, (facm*rV +fac*colV), r_col+0, r_col+1, r_col+2);
                        }
                                break;
                case MA_RAMP_COLOR:             
--                      if(g){
++                      if(r_col[1]){
                                float rH,rS,rV;
                                float colH,colS,colV;
                                float tmpr,tmpg,tmpb;
                                rgb_to_hsv(col[0],col[1],col[2],&colH,&colS,&colV);
                                if(colS!=0){
--                                      rgb_to_hsv(*r,*g,*b,&rH,&rS,&rV);
++                                      rgb_to_hsv(r_col[0],r_col[1],r_col[2],&rH,&rS,&rV);
                                        hsv_to_rgb( colH, colS, rV, &tmpr, &tmpg, &tmpb);
--                                      *r = facm*(*r) + fac*tmpr;
--                                      *g = facm*(*g) + fac*tmpg;
--                                      *b = facm*(*b) + fac*tmpb;
++                                      r_col[0] = facm*(r_col[0]) + fac*tmpr;
++                                      r_col[1] = facm*(r_col[1]) + fac*tmpg;
++                                      r_col[2] = facm*(r_col[2]) + fac*tmpb;
                                }
                        }
                                break;
                case MA_RAMP_SOFT: 
--                      if (g){ 
++                      if (r_col[1]){
                                float scr, scg, scb; 
  
                                /* first calculate non-fac based Screen mix */ 
--                              scr = 1.0f - (1.0f - col[0]) * (1.0f - *r); 
--                              scg = 1.0f - (1.0f - col[1]) * (1.0f - *g); 
--                              scb = 1.0f - (1.0f - col[2]) * (1.0f - *b); 
++                              scr = 1.0f - (1.0f - col[0]) * (1.0f - r_col[0]);
++                              scg = 1.0f - (1.0f - col[1]) * (1.0f - r_col[1]);
++                              scb = 1.0f - (1.0f - col[2]) * (1.0f - r_col[2]);
  
--                              *r = facm*(*r) + fac*(((1.0f - *r) * col[0] * (*r)) + (*r * scr)); 
--                              *g = facm*(*g) + fac*(((1.0f - *g) * col[1] * (*g)) + (*g * scg)); 
--                              *b = facm*(*b) + fac*(((1.0f - *b) * col[2] * (*b)) + (*b * scb)); 
++                              r_col[0] = facm*(r_col[0]) + fac*(((1.0f - r_col[0]) * col[0] * (r_col[0])) + (r_col[0] * scr));
++                              r_col[1] = facm*(r_col[1]) + fac*(((1.0f - r_col[1]) * col[1] * (r_col[1])) + (r_col[1] * scg));
++                              r_col[2] = facm*(r_col[2]) + fac*(((1.0f - r_col[2]) * col[2] * (r_col[2])) + (r_col[2] * scb));
                        } 
                                break; 
                case MA_RAMP_LINEAR: 
                        if (col[0] > 0.5f)  
--                              *r = *r + fac*(2.0f*(col[0]-0.5f)); 
++                              r_col[0] = r_col[0] + fac*(2.0f*(col[0]-0.5f));
                        else  
--                              *r = *r + fac*(2.0f*(col[0]) - 1.0f); 
--                      if (g){ 
++                              r_col[0] = r_col[0] + fac*(2.0f*(col[0]) - 1.0f);
++                      if (r_col[1]){
                                if (col[1] > 0.5f)  
--                                      *g = *g + fac*(2.0f*(col[1]-0.5f)); 
++                                      r_col[1] = r_col[1] + fac*(2.0f*(col[1]-0.5f));
                                else  
--                                      *g = *g + fac*(2.0f*(col[1]) -1.0f); 
++                                      r_col[1] = r_col[1] + fac*(2.0f*(col[1]) -1.0f);
                                if (col[2] > 0.5f)  
--                                      *b = *b + fac*(2.0f*(col[2]-0.5f)); 
++                                      r_col[2] = r_col[2] + fac*(2.0f*(col[2]-0.5f));
                                else  
--                                      *b = *b + fac*(2.0f*(col[2]) - 1.0f); 
++                                      r_col[2] = r_col[2] + fac*(2.0f*(col[2]) - 1.0f);
                        } 
                                break; 
        }       
index 540d757f0c9d037d1bd3c5175dd12ddd5150bef1,12a2fe28bc8b123ed6531613969fe96aa37aaa15..382e1d7038723cb2ebb75fb485aa2b6462fe115f
@@@ -895,7 -895,7 +895,7 @@@ void BKE_movieclip_update_scopes(MovieC
  
  static void movieclip_build_proxy_ibuf(MovieClip *clip, ImBuf *ibuf, int cfra, int proxy_render_size, int undistorted)
  {
--      char name[FILE_MAXFILE+FILE_MAXDIR];
++      char name[FILE_MAX];
        int quality, rectx, recty;
        int size= size= rendersize_to_number(proxy_render_size);
        ImBuf *scaleibuf;
        scaleibuf->ftype= JPG | quality;
  
        /* unsupported feature only confuses other s/w */
-       if(scaleibuf->depth==32)
-               scaleibuf->depth= 24;
+       if(scaleibuf->planes==32)
+               scaleibuf->planes= 24;
  
        BLI_lock_thread(LOCK_MOVIECLIP);
  
index b25c130590e3391ce01db03fb727c0ecabb3ae11,0b0a0039501f6dc7f0f936103dd3845e2c608bfa..d0858ea032a304c90244a49f21872ae9772a5864
  
  #include "GPU_material.h"
  
 +#include "FRS_freestyle.h"
 +
  /* Local function protos */
  static void solve_parenting (Scene *scene, Object *ob, Object *par, float obmat[][4], float slowmat[][4], int simul);
  
@@@ -604,14 -602,6 +604,14 @@@ void unlink_object(Object *ob
                                        }
                                SEQ_END
                        }
 +
 +                      {
 +                              SceneRenderLayer *srl;
 +
 +                              for (srl= sce->r.layers.first; srl; srl= srl->next) {
 +                                      FRS_unlink_target_object(&srl->freestyleConfig, ob);
 +                              }
 +                      }
                }
  
                sce= sce->id.next;
@@@ -1795,6 -1785,7 +1795,7 @@@ static void give_parvert(Object *par, i
                                dm->getVertCo(dm, 0, vec);
                        }
                }
+               else fprintf(stderr, "%s: DerivedMesh is needed to solve parenting, object position can be wrong now\n", __func__);
  
                if(em)
                        BKE_mesh_end_editmesh(me, em);
index ea1dbec8a275d3a528a9057c1fd9921db47cb47f,ea1dbec8a275d3a528a9057c1fd9921db47cb47f..7be8aefc883a2600ed25d8254b8104bbbc026006
@@@ -168,7 -168,7 +168,7 @@@ PackedFile *newPackedFile(ReportList *r
  {
        PackedFile *pf = NULL;
        int file, filelen;
--      char name[FILE_MAXDIR+FILE_MAXFILE];
++      char name[FILE_MAX];
        void *data;
        
        /* render result has no filename and can be ignored
@@@ -245,7 -245,7 +245,7 @@@ void packAll(Main *bmain, ReportList *r
  
  static char *find_new_name(char *name)
  {
--      char tempname[FILE_MAXDIR + FILE_MAXFILE];
++      char tempname[FILE_MAX];
        char *newname;
        size_t len;
        
@@@ -268,8 -268,8 +268,8 @@@ int writePackedFile(ReportList *reports
  {
        int file, number, remove_tmp = FALSE;
        int ret_value = RET_OK;
--      char name[FILE_MAXDIR + FILE_MAXFILE];
--      char tempname[FILE_MAXDIR + FILE_MAXFILE];
++      char name[FILE_MAX];
++      char tempname[FILE_MAX];
  /*    void *data; */
        
        if (guimode) {} //XXX  waitcursor(1);
@@@ -337,7 -337,7 +337,7 @@@ int checkPackedFile(const char *filenam
        struct stat st;
        int ret_val, i, len, file;
        char buf[4096];
--      char name[FILE_MAXDIR + FILE_MAXFILE];
++      char name[FILE_MAX];
        
        BLI_strncpy(name, filename, sizeof(name));
        BLI_path_abs(name, G.main->name);
@@@ -394,8 -394,8 +394,8 @@@ char *unpackFile(ReportList *reports, c
        char *newname = NULL;
        const char *temp = NULL;
        
--      // char newabs[FILE_MAXDIR + FILE_MAXFILE];
--      // char newlocal[FILE_MAXDIR + FILE_MAXFILE];
++      // char newabs[FILE_MAX];
++      // char newlocal[FILE_MAX];
        
        if (pf != NULL) {
                switch (how) {
  
  int unpackVFont(ReportList *reports, VFont *vfont, int how)
  {
--      char localname[FILE_MAXDIR + FILE_MAXFILE], fi[FILE_MAXFILE];
++      char localname[FILE_MAX], fi[FILE_MAXFILE];
        char *newname;
        int ret_value = RET_ERROR;
        
index 220068780a7782536e297bb334b4b74e8ff6b850,220068780a7782536e297bb334b4b74e8ff6b850..7c71df9fece0ee65e5d7aeed01e81ac87795067a
@@@ -3170,13 -3170,13 +3170,13 @@@ void psys_cache_edit_paths(Scene *scene
                                float t2;
  
                                if(k==0) {
--                                      weight_to_rgb(pind.hkey[1]->weight, ca->col, ca->col+1, ca->col+2);
++                                      weight_to_rgb(ca->col, pind.hkey[1]->weight);
                                } else {
                                        float w1[3], w2[3];
                                        keytime = (t - (*pind.ekey[0]->time))/((*pind.ekey[1]->time) - (*pind.ekey[0]->time));
  
--                                      weight_to_rgb(pind.hkey[0]->weight, w1, w1+1, w1+2);
--                                      weight_to_rgb(pind.hkey[1]->weight, w2, w2+1, w2+2);
++                                      weight_to_rgb(w1, pind.hkey[0]->weight);
++                                      weight_to_rgb(w2, pind.hkey[1]->weight);
  
                                        interp_v3_v3v3(ca->col, w1, w2, keytime);
                                }
index dbfda18942a61b557ea3d6978c933f6526741617,dbfda18942a61b557ea3d6978c933f6526741617..5445c990a9bdfeb021eddf2c14c120e149760831
@@@ -770,6 -770,6 +770,9 @@@ void BKE_ptcache_id_from_softbody(PTCac
        pid->info_types= 0;
  
        pid->stack_index = pid->cache->index;
++
++      pid->default_step = 10;
++      pid->max_step = 20;
  }
  void BKE_ptcache_id_from_particles(PTCacheID *pid, Object *ob, ParticleSystem *psys)
  {
                pid->data_types|= (1<<BPHYS_DATA_ROTATION);
  
        pid->info_types= (1<<BPHYS_DATA_TIMES);
++
++      pid->default_step = 10;
++      pid->max_step = 20;
  }
  void BKE_ptcache_id_from_cloth(PTCacheID *pid, Object *ob, ClothModifierData *clmd)
  {
  
        pid->data_types= (1<<BPHYS_DATA_LOCATION) | (1<<BPHYS_DATA_VELOCITY) | (1<<BPHYS_DATA_XCONST);
        pid->info_types= 0;
++
++      pid->default_step = 1;
++      pid->max_step = 1;
  }
  void BKE_ptcache_id_from_smoke(PTCacheID *pid, struct Object *ob, struct SmokeModifierData *smd)
  {
                pid->data_types |= (1<<BPHYS_DATA_SMOKE_LOW);
        if(sds->wt)
                pid->data_types |= (1<<BPHYS_DATA_SMOKE_HIGH);
++
++      pid->default_step = 1;
++      pid->max_step = 1;
  }
  
  void BKE_ptcache_id_from_dynamicpaint(PTCacheID *pid, Object *ob, DynamicPaintSurface *surface)
        pid->info_types= 0;
  
        pid->stack_index = pid->cache->index;
++
++      pid->default_step = 1;
++      pid->max_step = 1;
  }
  
  void BKE_ptcache_ids_from_object(ListBase *lb, Object *ob, Scene *scene, int duplis)
  */
  
  #define MAX_PTCACHE_PATH FILE_MAX
--#define MAX_PTCACHE_FILE ((FILE_MAXDIR+FILE_MAXFILE)*2)
++#define MAX_PTCACHE_FILE ((FILE_MAX)*2)
  
  static int ptcache_path(PTCacheID *pid, char *filename)
  {
@@@ -1112,7 -1112,7 +1127,7 @@@ static PTCacheFile *ptcache_file_open(P
  {
        PTCacheFile *pf;
        FILE *fp = NULL;
--      char filename[(FILE_MAXDIR+FILE_MAXFILE)*2];
++      char filename[(FILE_MAX)*2];
  
  #ifndef DURIAN_POINTCACHE_LIB_OK
        /* don't allow writing for linked objects */
index ae958db3d4a97bac6422012fd8a363aad24225a8,b7aa02b2f7bce02567fff0a6752a64f4c096895a..33fb15faa56c1bda15e5505519284745e0abbadc
@@@ -78,8 -78,6 +78,8 @@@
  //XXX #include "BIF_previewrender.h"
  //XXX #include "BIF_editseq.h"
  
 +#include "FRS_freestyle_config.h"
 +
  //XXX #include "nla.h"
  
  #ifdef WIN32
@@@ -244,8 -242,7 +244,8 @@@ Scene *copy_scene(Scene *sce, int type
  void free_scene(Scene *sce)
  {
        Base *base;
 -
 +      SceneRenderLayer *srl;
 +      
        base= sce->base.first;
        while(base) {
                base->object->id.us--;
                sce->r.ffcodecdata.properties = NULL;
        }
        
 +      for(srl= sce->r.layers.first; srl; srl= srl->next) {
 +              FRS_free_freestyle_config(srl);
 +      }
 +      
        BLI_freelistN(&sce->markers);
        BLI_freelistN(&sce->transform_spaces);
        BLI_freelistN(&sce->r.layers);
@@@ -354,9 -347,11 +354,11 @@@ Scene *add_scene(const char *name
        sce->r.mblur_samples= 1;
        sce->r.filtertype= R_FILTER_MITCH;
        sce->r.size= 50;
-       sce->r.planes= 24;
-       sce->r.imtype= R_PNG;
-       sce->r.quality= 90;
+       sce->r.im_format.planes= R_IMF_PLANES_RGB;
+       sce->r.im_format.imtype= R_IMF_IMTYPE_PNG;
+       sce->r.im_format.quality= 90;
        sce->r.displaymode= R_OUTPUT_AREA;
        sce->r.framapto= 100;
        sce->r.images= 100;
@@@ -1110,7 -1105,6 +1112,7 @@@ SceneRenderLayer *scene_add_render_laye
        srl->lay= (1<<20) -1;
        srl->layflag= 0x7FFF;   /* solid ztra halo edge strand */
        srl->passflag= SCE_PASS_COMBINED|SCE_PASS_Z;
 +      FRS_add_freestyle_config( srl );
  
        return srl;
  }
index 5d35867d9c32fc06279a5325dd34a687510e0507,880bdbfaa962e80643c9df611a2fb193b9c9acb0..249555578f0b896b5843a4e2ab7100ea93d3c8a7
@@@ -652,7 -652,7 +652,7 @@@ void calc_sequence(Scene *scene, Sequen
  /* note: caller should run calc_sequence(scene, seq) after */
  void reload_sequence_new_file(Scene *scene, Sequence * seq, int lock_range)
  {
--      char str[FILE_MAXDIR+FILE_MAXFILE];
++      char str[FILE_MAX];
        int prev_startdisp=0, prev_enddisp=0;
        /* note: dont rename the strip, will break animation curves */
  
@@@ -1156,7 -1156,7 +1156,7 @@@ static IMB_Proxy_Size seq_rendersize_to
  
  static void seq_open_anim_file(Sequence * seq)
  {
--      char name[FILE_MAXDIR+FILE_MAXFILE];
++      char name[FILE_MAX];
        StripProxy * proxy;
  
        if(seq->anim != NULL) {
@@@ -1327,8 -1327,8 +1327,8 @@@ static void seq_proxy_build_frame(SeqRe
        ibuf->ftype= JPG | quality;
  
        /* unsupported feature only confuses other s/w */
-       if(ibuf->depth==32)
-               ibuf->depth= 24;
+       if(ibuf->planes==32)
+               ibuf->planes= 24;
  
        BLI_make_existing_file(name);
        
@@@ -1729,7 -1729,7 +1729,7 @@@ static ImBuf * input_preprocess
        }
  
        if(seq->flag & SEQ_MAKE_PREMUL) {
-               if(ibuf->depth == 32 && ibuf->zbuf == NULL) {
+               if(ibuf->planes == 32 && ibuf->zbuf == NULL) {
                        IMB_premultiply_alpha(ibuf);
                }
        }
@@@ -2057,7 -2057,7 +2057,7 @@@ static ImBuf * seq_render_scene_strip_i
  static ImBuf * seq_render_strip(SeqRenderData context, Sequence * seq, float cfra)
  {
        ImBuf * ibuf = NULL;
--      char name[FILE_MAXDIR+FILE_MAXFILE];
++      char name[FILE_MAX];
        int use_preprocess = input_have_to_preprocess(context, seq, cfra);
        float nr = give_stripelem_index(seq, cfra);
        /* all effects are handled similarly with the exception of speed effect */
index 001d2abab01108e7fca993d0e55ba9915e8580b7,050aaee92e4060dc98ec60043c7b2bbeb3639275..1ad811c6580af60a006543742747bf8816e22104
@@@ -749,7 -749,7 +749,7 @@@ static void ccgDM_getFinalEdge(DerivedM
  
                edgeFlag = (ccgdm->edgeFlags)? &ccgdm->edgeFlags[i]: NULL;
                if(edgeFlag)
 -                      flags |= (*edgeFlag & (ME_SEAM | ME_SHARP))
 +                      flags |= (*edgeFlag & (ME_SEAM | ME_SHARP | ME_FREESTYLE_EDGE))
                                         | ME_EDGEDRAW | ME_EDGERENDER;
                else
                        flags |= ME_EDGEDRAW | ME_EDGERENDER;
@@@ -934,7 -934,7 +934,7 @@@ static void ccgDM_copyFinalEdgeArray(De
  
                if(edgeFlags) {
                        if(edgeIdx != -1) {
 -                              flags |= (edgeFlags[index] & (ME_SEAM | ME_SHARP))
 +                              flags |= (edgeFlags[index] & (ME_SEAM | ME_SHARP | ME_FREESTYLE_EDGE))
                                                 | ME_EDGEDRAW | ME_EDGERENDER;
                        }
                } else {
@@@ -1173,8 -1173,6 +1173,6 @@@ static void ccgdm_pbvh_update(CCGDerive
  static void ccgDM_drawEdges(DerivedMesh *dm, int drawLooseEdges, int UNUSED(drawAllEdges)) {
        CCGDerivedMesh *ccgdm = (CCGDerivedMesh*) dm;
        CCGSubSurf *ss = ccgdm->ss;
-       CCGEdgeIterator *ei = ccgSubSurf_getEdgeIterator(ss);
-       CCGFaceIterator *fi = ccgSubSurf_getFaceIterator(ss);
        int i, j, edgeSize = ccgSubSurf_getEdgeSize(ss);
        int totedge = ccgSubSurf_getNumEdges(ss);
        int gridSize = ccgSubSurf_getGridSize(ss);
        }
  
        if (ccgdm->drawInteriorEdges) {
-               for (; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
-                       CCGFace *f = ccgFaceIterator_getCurrent(fi);
+               int totface = ccgSubSurf_getNumFaces(ss);
+               for(j = 0; j < totface; j++) {
+                       CCGFace *f = ccgdm->faceMap[j].face;
                        int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
  
                        for (S=0; S<numVerts; S++) {
                        }
                }
        }
-       ccgFaceIterator_free(fi);
-       ccgEdgeIterator_free(ei);
  }
  static void ccgDM_drawLooseEdges(DerivedMesh *dm) {
        CCGDerivedMesh *ccgdm = (CCGDerivedMesh*) dm;
        CCGSubSurf *ss = ccgdm->ss;
-       CCGEdgeIterator *ei = ccgSubSurf_getEdgeIterator(ss);
-       int i, edgeSize = ccgSubSurf_getEdgeSize(ss);
+       int totedge = ccgSubSurf_getNumEdges(ss);
+       int i, j, edgeSize = ccgSubSurf_getEdgeSize(ss);
  
-       for (; !ccgEdgeIterator_isStopped(ei); ccgEdgeIterator_next(ei)) {
-               CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
+       for (j=0; j< totedge; j++) {
+               CCGEdge *e = ccgdm->edgeMap[j].edge;
                DMGridData *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
  
                if (!ccgSubSurf_getEdgeNumFaces(e)) {
                        glEnd();
                }
        }
-       ccgEdgeIterator_free(ei);
  }
  
  static void ccgDM_glNormalFast(float *a, float *b, float *c, float *d)
  static void ccgDM_drawFacesSolid(DerivedMesh *dm, float (*partial_redraw_planes)[4], int fast, int (*setMaterial)(int, void *attribs)) {
        CCGDerivedMesh *ccgdm = (CCGDerivedMesh*) dm;
        CCGSubSurf *ss = ccgdm->ss;
-       CCGFaceIterator *fi;
        int gridSize = ccgSubSurf_getGridSize(ss);
        char *faceFlags = ccgdm->faceFlags;
        int step = (fast)? gridSize-1: 1;
+       int i, totface = ccgSubSurf_getNumFaces(ss);
+       int drawcurrent = 0, matnr = -1, shademodel = -1;
  
        ccgdm_pbvh_update(ccgdm);
  
                return;
        }
  
-       fi = ccgSubSurf_getFaceIterator(ss);
-       for (; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
-               CCGFace *f = ccgFaceIterator_getCurrent(fi);
+       for(i = 0; i < totface; i++) {
+               CCGFace *f = ccgdm->faceMap[i].face;
                int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
                int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(ss, f));
-               int drawSmooth, mat_nr;
+               int new_matnr, new_shademodel;
  
                if(faceFlags) {
-                       drawSmooth = (faceFlags[index*2] & ME_SMOOTH);
-                       mat_nr= faceFlags[index*2 + 1];
+                       new_shademodel = (faceFlags[index*2] & ME_SMOOTH)? GL_SMOOTH: GL_FLAT;
+                       new_matnr= faceFlags[index*2 + 1];
                }
                else {
-                       drawSmooth = 1;
-                       mat_nr= 0;
+                       new_shademodel = GL_SMOOTH;
+                       new_matnr= 0;
                }
                
-               if (!setMaterial(mat_nr+1, NULL))
+               if(shademodel != new_shademodel || matnr != new_matnr) {
+                       matnr= new_matnr;
+                       shademodel= new_shademodel;
+                       drawcurrent= setMaterial(matnr+1, NULL);
+                       glShadeModel(shademodel);
+               }
+               if(!drawcurrent)
                        continue;
  
-               glShadeModel(drawSmooth? GL_SMOOTH: GL_FLAT);
                for (S=0; S<numVerts; S++) {
                        DMGridData *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
  
-                       if (drawSmooth) {
+                       if (shademodel == GL_SMOOTH) {
                                for (y=0; y<gridSize-1; y+=step) {
                                        glBegin(GL_QUAD_STRIP);
                                        for (x=0; x<gridSize; x+=step) {
                        }
                }
        }
-       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= {{{NULL}}};
        /* MTFace *tf = dm->getFaceDataArray(dm, CD_MTFACE); */ /* UNUSED */
        }
  
  #undef PASSATTRIB
-       ccgFaceIterator_free(fi);
  }
  
  static void ccgDM_drawFacesGLSL(DerivedMesh *dm, int (*setMaterial)(int, void *attribs)) {
  static void ccgDM_drawMappedFacesMat(DerivedMesh *dm, void (*setMaterial)(void *userData, int, void *attribs), int (*setFace)(void *userData, int index), void *userData) {
        CCGDerivedMesh *ccgdm = (CCGDerivedMesh*) dm;
        CCGSubSurf *ss = ccgdm->ss;
-       CCGFaceIterator *fi = ccgSubSurf_getFaceIterator(ss);
        GPUVertexAttribs gattribs;
        DMVertexAttribs attribs= {{{NULL}}};
        int gridSize = ccgSubSurf_getGridSize(ss);
        }
  
  #undef PASSATTRIB
-       ccgFaceIterator_free(fi);
  }
  
  
  static void ccgDM_drawFacesColored(DerivedMesh *dm, int UNUSED(useTwoSided), unsigned char *col1, unsigned char *col2) {
        CCGDerivedMesh *ccgdm = (CCGDerivedMesh*) dm;
        CCGSubSurf *ss = ccgdm->ss;
-       CCGFaceIterator *fi = ccgSubSurf_getFaceIterator(ss);
        int gridSize = ccgSubSurf_getGridSize(ss);
        unsigned char *cp1, *cp2;
-       int useTwoSide=1;
+       int useTwoSide=1, i, totface;
  
        ccgdm_pbvh_update(ccgdm);
  
        }
  
        glBegin(GL_QUADS);
-       for (; !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
-               CCGFace *f = ccgFaceIterator_getCurrent(fi);
+       totface = ccgSubSurf_getNumFaces(ss);
+       for(i = 0; i < totface; i++) {
+               CCGFace *f = ccgdm->faceMap[i].face;
                int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
  
                for (S=0; S<numVerts; S++) {
                }
        }
        glEnd();
-       ccgFaceIterator_free(fi);
  }
  
  static void ccgDM_drawFacesTex_common(DerivedMesh *dm,
index 5735a95764bf6a5ca044cb2e80fe9234e066b6b6,5735a95764bf6a5ca044cb2e80fe9234e066b6b6..28d68892a2acb349af35da726c23f9e3d9b99770
@@@ -237,12 -237,12 +237,12 @@@ int reopen_text(Text *text
        int i, llen, len;
        unsigned char *buffer;
        TextLine *tmp;
--      char str[FILE_MAXDIR+FILE_MAXFILE];
++      char str[FILE_MAX];
        struct stat st;
  
        if (!text || !text->name) return 0;
        
--      BLI_strncpy(str, text->name, FILE_MAXDIR+FILE_MAXFILE);
++      BLI_strncpy(str, text->name, FILE_MAX);
        BLI_path_abs(str, G.main->name);
        
        fp= fopen(str, "r");
@@@ -334,10 -334,10 +334,10 @@@ Text *add_text(const char *file, const 
        unsigned char *buffer;
        TextLine *tmp;
        Text *ta;
--      char str[FILE_MAXDIR+FILE_MAXFILE];
++      char str[FILE_MAX];
        struct stat st;
  
--      BLI_strncpy(str, file, FILE_MAXDIR+FILE_MAXFILE);
++      BLI_strncpy(str, file, FILE_MAX);
        if (relpath) /* can be NULL (bg mode) */
                BLI_path_abs(str, relpath);
        
index 4507d70e3394facdf68fc2740d08a652db1e84c6,4507d70e3394facdf68fc2740d08a652db1e84c6..b7df06bbf24442a44b51c2c3065e319457a0daa4
@@@ -287,20 -287,20 +287,28 @@@ static DLRBT_Node *get_grandparent (DLR
                return NULL;
  }
  
--/* get the 'uncle' - the sibling of the parent - of the given node */
--static DLRBT_Node *get_uncle (DLRBT_Node *node)
++/* get the sibling node (e.g. if node is left child of parent, return right child of parent) */
++static DLRBT_Node *get_sibling(DLRBT_Node *node)
  {
--      DLRBT_Node *gpn= get_grandparent(node);
--      
--      /* return the child of the grandparent which isn't the node's parent */
--      if (gpn) {
--              if (gpn->left == node->parent)
--                      return gpn->right;
++      if (node && node->parent) {
++              if (node == node->parent->left)
++                      return node->parent->right;
                else
--                      return gpn->left;
++                      return node->parent->left;
        }
++
++      /* sibling not found */
++      return NULL;
++}
++
++/* get the 'uncle' - the sibling of the parent - of the given node */
++static DLRBT_Node *get_uncle (DLRBT_Node *node)
++{
++      if (node)
++              /* return the child of the grandparent which isn't the node's parent */
++              return get_sibling(node->parent);
        
--      /* not found */
++      /* uncle not found */
        return NULL;
  }
  
index 08d9dfaeb9ea8a32eb5dc09845b7bcb3c7fe27cd,8261a018a09a844c9b3363bdd21d3a96ebaf5d34..e79d850caa582ef0b119496c29c297f32d3d3750
@@@ -44,6 -44,7 +44,7 @@@
  #include "BLI_fileops.h"
  #include "BLI_path_util.h"
  #include "BLI_string.h"
+ #include "BLI_string_utf8.h"
  #include "BLI_utildefines.h"
  
  #include "BKE_utildefines.h"
@@@ -220,16 -221,25 +221,25 @@@ int BLI_uniquename_cb(int (*unique_chec
        }
  
        if(unique_check(arg, name)) {
+               char    numstr[16];
                char    tempname[UNIQUE_NAME_MAX];
                char    left[UNIQUE_NAME_MAX];
                int             number;
                int             len= BLI_split_name_num(left, &number, name, delim);
                do {
-                       int newlen= BLI_snprintf(tempname, name_len, "%s%c%03d", left, delim, ++number);
-                       if(newlen >= name_len) {
-                               len -= ((newlen + 1) - name_len);
-                               if(len < 0) len= number= 0;
-                               left[len]= '\0';
+                       int numlen= BLI_snprintf(numstr, sizeof(numstr), "%c%03d", delim, ++number);
+                       /* highly unlikely the string only has enough room for the number
+                        * but support anyway */
+                       if ((len == 0) || (numlen >= name_len)) {
+                               /* number is know not to be utf-8 */
+                               BLI_strncpy(tempname, numstr, name_len);
+                       }
+                       else {
+                               char *tempname_buf;
+                               tempname[0]= '\0';
+                               tempname_buf =BLI_strncat_utf8(tempname, left, name_len - numlen);
+                               memcpy(tempname_buf, numstr, numlen + 1);
                        }
                } while(unique_check(arg, tempname));
  
@@@ -416,8 -426,8 +426,8 @@@ void BLI_cleanup_file(const char *relab
  void BLI_path_rel(char *file, const char *relfile)
  {
        char * lslash;
--      char temp[FILE_MAXDIR+FILE_MAXFILE];
--      char res[FILE_MAXDIR+FILE_MAXFILE];
++      char temp[FILE_MAX];
++      char res[FILE_MAX];
        
        /* if file is already relative, bail out */
        if(file[0]=='/' && file[1]=='/') return;
                if (relfile[0] != '\\' && relfile[0] != '/') {
                        ptemp++;
                }
--              BLI_strncpy(ptemp, relfile, FILE_MAXDIR + FILE_MAXFILE-3);
++              BLI_strncpy(ptemp, relfile, FILE_MAX-3);
        } else {
--              BLI_strncpy(temp, relfile, FILE_MAXDIR + FILE_MAXFILE);
++              BLI_strncpy(temp, relfile, FILE_MAX);
        }
  
        if (BLI_strnlen(file, 3) > 2) {
@@@ -529,7 -539,7 +539,7 @@@ int BLI_has_parent(char *path
  int BLI_parent_dir(char *path)
  {
        static char parent_dir[]= {'.', '.', SEP, '\0'}; /* "../" or "..\\" */
--      char tmp[FILE_MAXDIR+FILE_MAXFILE+4];
++      char tmp[FILE_MAX+4];
        BLI_strncpy(tmp, path, sizeof(tmp)-4);
        BLI_add_slash(tmp);
        strcat(tmp, parent_dir);
@@@ -734,7 -744,7 +744,7 @@@ int BLI_path_cwd(char *path
  #endif
        
        if (wasrelative==1) {
--              char cwd[FILE_MAXDIR + FILE_MAXFILE]= "";
++              char cwd[FILE_MAX]= "";
                BLI_current_working_dir(cwd, sizeof(cwd)); /* incase the full path to the blend isnt used */
                
                if (cwd[0] == '\0') {
                        * blend file which isnt a feature we want to use in this case since were dealing
                        * with a path from the command line, rather than from inside Blender */
                        
--                      char origpath[FILE_MAXDIR + FILE_MAXFILE];
--                      BLI_strncpy(origpath, path, FILE_MAXDIR + FILE_MAXFILE);
++                      char origpath[FILE_MAX];
++                      BLI_strncpy(origpath, path, FILE_MAX);
                        
                        BLI_make_file_string(NULL, path, cwd, origpath); 
                }
@@@ -1246,7 -1256,7 +1256,7 @@@ void BLI_make_exist(char *dir
  
  void BLI_make_existing_file(const char *name)
  {
--      char di[FILE_MAXDIR+FILE_MAXFILE], fi[FILE_MAXFILE];
++      char di[FILE_MAX], fi[FILE_MAXFILE];
  
        BLI_strncpy(di, name, sizeof(di));
        BLI_splitdirstring(di, fi);
@@@ -1695,8 -1705,8 +1705,8 @@@ static int add_win32_extension(char *na
        type = BLI_exists(name);
        if ((type == 0) || S_ISDIR(type)) {
  #ifdef _WIN32
--              char filename[FILE_MAXDIR+FILE_MAXFILE];
--              char ext[FILE_MAXDIR+FILE_MAXFILE];
++              char filename[FILE_MAX];
++              char ext[FILE_MAX];
                const char *extensions = getenv("PATHEXT");
                if (extensions) {
                        char *temp;
  */
  static void bli_where_am_i(char *fullname, const size_t maxlen, const char *name)
  {
--      char filename[FILE_MAXDIR+FILE_MAXFILE];
++      char filename[FILE_MAX];
        const char *path = NULL, *temp;
  
  #ifdef _WIN32
index 0ac6e0ba4dfc6d0decba5c201d17af43cac9090a,0ac6e0ba4dfc6d0decba5c201d17af43cac9090a..5c7a29c6277b62e91837a71b1877b959a5c1563f
@@@ -656,12 -656,12 +656,17 @@@ void BLI_pbvh_free(PBVH *bvh
                        /* if pbvh was deformed, new memory was allocated for verts/faces -- free it */
  
                        MEM_freeN(bvh->verts);
--                      MEM_freeN(bvh->faces);
++                      if(bvh->faces)
++                              MEM_freeN(bvh->faces);
                }
        }
  
--      MEM_freeN(bvh->nodes);
--      MEM_freeN(bvh->prim_indices);
++      if(bvh->nodes)
++              MEM_freeN(bvh->nodes);
++
++      if(bvh->prim_indices)
++              MEM_freeN(bvh->prim_indices);
++
        MEM_freeN(bvh);
  }
  
@@@ -1127,6 -1127,6 +1132,9 @@@ void BLI_pbvh_update(PBVH *bvh, int fla
        PBVHNode **nodes;
        int totnode;
  
++      if(!bvh->nodes)
++              return;
++
        BLI_pbvh_search_gather(bvh, update_search_cb, SET_INT_IN_POINTER(flag),
                &nodes, &totnode);
  
index 86095e6b90907f3a340bd77b3d37211b04103aaa,86095e6b90907f3a340bd77b3d37211b04103aaa..1ef254d355f4bf7e7c344d19bbd604451109d65a
@@@ -442,18 -442,18 +442,18 @@@ int BLI_exists(const char *name
        /*  in Windows stat doesn't recognize dir ending on a slash 
                To not break code where the ending slash is expected we
                don't mess with the argument name directly here - elubie */
--      char tmp[FILE_MAXDIR+FILE_MAXFILE];
++      char tmp[FILE_MAX];
        int len, res;
--      BLI_strncpy(tmp, name, FILE_MAXDIR+FILE_MAXFILE);
++      BLI_strncpy(tmp, name, FILE_MAX);
        len = strlen(tmp);
        if (len > 3 && ( tmp[len-1]=='\\' || tmp[len-1]=='/') ) tmp[len-1] = '\0';
        res = _stat(tmp, &st);
        if (res == -1) return(0);
  #elif defined(__MINGW32__)
        struct _stati64 st;
--      char tmp[FILE_MAXDIR+FILE_MAXFILE];
++      char tmp[FILE_MAX];
        int len, res;
--      BLI_strncpy(tmp, name, FILE_MAXDIR+FILE_MAXFILE);
++      BLI_strncpy(tmp, name, FILE_MAX);
        len = strlen(tmp);
        if (len > 3 && ( tmp[len-1]=='\\' || tmp[len-1]=='/') ) tmp[len-1] = '\0';
        res = _stati64(tmp, &st);
index d3e989c28ae4b64b48656fc9696b2a205951db41,d3e989c28ae4b64b48656fc9696b2a205951db41..1b5bb60738623c07285b94b99e29dea173025156
  #define WIN32_SKIP_HKEY_PROTECTION            // need to use HKEY
  #include "BLI_winstuff.h"
  
-- /* FILE_MAXDIR + FILE_MAXFILE */
++ /* FILE_MAX */
  
  int BLI_getInstallationDir( char * str ) {
        char dir[FILE_MAXDIR];
        int a;
        
--      GetModuleFileName(NULL,str,FILE_MAXDIR+FILE_MAXFILE);
++      GetModuleFileName(NULL,str,FILE_MAX);
        BLI_split_dir_part(str, dir, sizeof(dir)); /* shouldn't be relative */
        a = strlen(dir);
        if(dir[a-1] == '\\') dir[a-1]=0;
index c96d7f7ffa1e8d3a6e331adcbd1d1c303c905767,61f0989a6f2a6bc7e666423e2579f499c0b99504..9246773bdc1825a8e0f339b98f5653733627b048
@@@ -66,7 -66,6 +66,7 @@@
  #include "DNA_key_types.h"
  #include "DNA_lattice_types.h"
  #include "DNA_lamp_types.h"
 +#include "DNA_linestyle_types.h"
  #include "DNA_meta_types.h"
  #include "DNA_material_types.h"
  #include "DNA_mesh_types.h"
@@@ -501,7 -500,7 +501,7 @@@ static Main *blo_find_main(FileData *fd
  {
        Main *m;
        Library *lib;
--      char name1[FILE_MAXDIR+FILE_MAXFILE];
++      char name1[FILE_MAX];
        
        BLI_strncpy(name1, filepath, sizeof(name1));
        cleanup_path(relabase, name1);
@@@ -4638,7 -4637,6 +4638,7 @@@ static void lib_link_scene(FileData *fd
        Base *base, *next;
        Sequence *seq;
        SceneRenderLayer *srl;
 +      FreestyleLineSet *fls;
        TimeMarker *marker;
        
        sce= main->scene.first;
                        for(srl= sce->r.layers.first; srl; srl= srl->next) {
                                srl->mat_override= newlibadr_us(fd, sce->id.lib, srl->mat_override);
                                srl->light_override= newlibadr_us(fd, sce->id.lib, srl->light_override);
 +                              for(fls=srl->freestyleConfig.linesets.first; fls; fls= fls->next) {
 +                                      fls->linestyle= newlibadr_us(fd, sce->id.lib, fls->linestyle);
 +                                      fls->group= newlibadr_us(fd, sce->id.lib, fls->group);
 +                              }
                        }
                        /*Game Settings: Dome Warp Text*/
                        sce->gm.dome.warptext= newlibadr(fd, sce->id.lib, sce->gm.dome.warptext);
@@@ -4764,7 -4758,6 +4764,7 @@@ static void direct_link_scene(FileData 
        Editing *ed;
        Sequence *seq;
        MetaStack *ms;
 +      SceneRenderLayer *srl;
  
        sce->theDag = NULL;
        sce->dagisvalid = 0;
        link_list(fd, &(sce->transform_spaces));
        link_list(fd, &(sce->r.layers));
  
 +      for(srl= sce->r.layers.first; srl; srl= srl->next) {
 +              link_list(fd, &(srl->freestyleConfig.modules));
 +      }
 +      for(srl= sce->r.layers.first; srl; srl= srl->next) {
 +              link_list(fd, &(srl->freestyleConfig.linesets));
 +      }
 +      
        sce->nodetree= newdataadr(fd, sce->nodetree);
        if(sce->nodetree)
                direct_link_nodetree(fd, sce->nodetree);
@@@ -6001,177 -5987,6 +6001,177 @@@ static void lib_link_movieclip(FileDat
        }
  }
  
 +/* ************ READ LINE STYLE ***************** */
 +
 +static void lib_link_linestyle(FileData *fd, Main *main)
 +{
 +      FreestyleLineStyle *linestyle;
 +      LineStyleModifier *m;
 +
 +      linestyle = main->linestyle.first;
 +      while (linestyle) {
 +              if (linestyle->id.flag & LIB_NEEDLINK) {
 +                      linestyle->id.flag -= LIB_NEEDLINK;
 +
 +                      if (linestyle->id.properties) IDP_LibLinkProperty(linestyle->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
 +                      if (linestyle->adt) lib_link_animdata(fd, &linestyle->id, linestyle->adt);
 +                      for (m = linestyle->color_modifiers.first; m; m = m->next) {
 +                              switch (m->type) {
 +                              case LS_MODIFIER_DISTANCE_FROM_OBJECT:
 +                                      {
 +                                              LineStyleColorModifier_DistanceFromObject *cm = (LineStyleColorModifier_DistanceFromObject *)m;
 +                                              cm->target = newlibadr(fd, linestyle->id.lib, cm->target);
 +                                      }
 +                                      break;
 +                              }
 +                      }
 +                      for (m = linestyle->alpha_modifiers.first; m; m = m->next){
 +                              switch (m->type) {
 +                              case LS_MODIFIER_DISTANCE_FROM_OBJECT:
 +                                      {
 +                                              LineStyleAlphaModifier_DistanceFromObject *am = (LineStyleAlphaModifier_DistanceFromObject *)m;
 +                                              am->target = newlibadr(fd, linestyle->id.lib, am->target);
 +                                      }
 +                                      break;
 +                              }
 +                      }
 +                      for (m = linestyle->thickness_modifiers.first; m; m = m->next){
 +                              switch (m->type) {
 +                              case LS_MODIFIER_DISTANCE_FROM_OBJECT:
 +                                      {
 +                                              LineStyleThicknessModifier_DistanceFromObject *tm = (LineStyleThicknessModifier_DistanceFromObject *)m;
 +                                              tm->target = newlibadr(fd, linestyle->id.lib, tm->target);
 +                                      }
 +                                      break;
 +                              }
 +                      }
 +              }
 +              linestyle = linestyle->id.next;
 +      }
 +}
 +
 +static void direct_link_linestyle_color_modifier(FileData *fd, LineStyleModifier *modifier)
 +{
 +      switch (modifier->type) {
 +      case LS_MODIFIER_ALONG_STROKE:
 +              {
 +                      LineStyleColorModifier_AlongStroke *m = (LineStyleColorModifier_AlongStroke *)modifier;
 +                      m->color_ramp = newdataadr(fd, m->color_ramp);
 +              }
 +              break;
 +      case LS_MODIFIER_DISTANCE_FROM_CAMERA:
 +              {
 +                      LineStyleColorModifier_DistanceFromCamera *m = (LineStyleColorModifier_DistanceFromCamera *)modifier;
 +                      m->color_ramp = newdataadr(fd, m->color_ramp);
 +              }
 +              break;
 +      case LS_MODIFIER_DISTANCE_FROM_OBJECT:
 +              {
 +                      LineStyleColorModifier_DistanceFromObject *m = (LineStyleColorModifier_DistanceFromObject *)modifier;
 +                      m->color_ramp = newdataadr(fd, m->color_ramp);
 +              }
 +              break;
 +      case LS_MODIFIER_MATERIAL:
 +              {
 +                      LineStyleColorModifier_Material *m = (LineStyleColorModifier_Material *)modifier;
 +                      m->color_ramp = newdataadr(fd, m->color_ramp);
 +              }
 +              break;
 +      }
 +}
 +
 +static void direct_link_linestyle_alpha_modifier(FileData *fd, LineStyleModifier *modifier)
 +{
 +      switch (modifier->type) {
 +      case LS_MODIFIER_ALONG_STROKE:
 +              {
 +                      LineStyleAlphaModifier_AlongStroke *m = (LineStyleAlphaModifier_AlongStroke *)modifier;
 +                      m->curve = newdataadr(fd, m->curve);
 +                      direct_link_curvemapping(fd, m->curve);
 +              }
 +              break;
 +      case LS_MODIFIER_DISTANCE_FROM_CAMERA:
 +              {
 +                      LineStyleAlphaModifier_DistanceFromCamera *m = (LineStyleAlphaModifier_DistanceFromCamera *)modifier;
 +                      m->curve = newdataadr(fd, m->curve);
 +                      direct_link_curvemapping(fd, m->curve);
 +              }
 +              break;
 +      case LS_MODIFIER_DISTANCE_FROM_OBJECT:
 +              {
 +                      LineStyleAlphaModifier_DistanceFromObject *m = (LineStyleAlphaModifier_DistanceFromObject *)modifier;
 +                      m->curve = newdataadr(fd, m->curve);
 +                      direct_link_curvemapping(fd, m->curve);
 +              }
 +              break;
 +      case LS_MODIFIER_MATERIAL:
 +              {
 +                      LineStyleAlphaModifier_Material *m = (LineStyleAlphaModifier_Material *)modifier;
 +                      m->curve = newdataadr(fd, m->curve);
 +                      direct_link_curvemapping(fd, m->curve);
 +              }
 +              break;
 +      }
 +}
 +
 +static void direct_link_linestyle_thickness_modifier(FileData *fd, LineStyleModifier *modifier)
 +{
 +      switch (modifier->type) {
 +      case LS_MODIFIER_ALONG_STROKE:
 +              {
 +                      LineStyleThicknessModifier_AlongStroke *m = (LineStyleThicknessModifier_AlongStroke *)modifier;
 +                      m->curve = newdataadr(fd, m->curve);
 +                      direct_link_curvemapping(fd, m->curve);
 +              }
 +              break;
 +      case LS_MODIFIER_DISTANCE_FROM_CAMERA:
 +              {
 +                      LineStyleThicknessModifier_DistanceFromCamera *m = (LineStyleThicknessModifier_DistanceFromCamera *)modifier;
 +                      m->curve = newdataadr(fd, m->curve);
 +                      direct_link_curvemapping(fd, m->curve);
 +              }
 +              break;
 +      case LS_MODIFIER_DISTANCE_FROM_OBJECT:
 +              {
 +                      LineStyleThicknessModifier_DistanceFromObject *m = (LineStyleThicknessModifier_DistanceFromObject *)modifier;
 +                      m->curve = newdataadr(fd, m->curve);
 +                      direct_link_curvemapping(fd, m->curve);
 +              }
 +              break;
 +      case LS_MODIFIER_MATERIAL:
 +              {
 +                      LineStyleThicknessModifier_Material *m = (LineStyleThicknessModifier_Material *)modifier;
 +                      m->curve = newdataadr(fd, m->curve);
 +                      direct_link_curvemapping(fd, m->curve);
 +              }
 +              break;
 +      }
 +}
 +
 +static void direct_link_linestyle_geometry_modifier(FileData *fd, LineStyleModifier *modifier)
 +{
 +}
 +
 +static void direct_link_linestyle(FileData *fd, FreestyleLineStyle *linestyle)
 +{
 +      LineStyleModifier *modifier;
 +
 +      linestyle->adt= newdataadr(fd, linestyle->adt);
 +      direct_link_animdata(fd, linestyle->adt);
 +      link_list(fd, &linestyle->color_modifiers);
 +      for(modifier=linestyle->color_modifiers.first; modifier; modifier= modifier->next)
 +              direct_link_linestyle_color_modifier(fd, modifier);
 +      link_list(fd, &linestyle->alpha_modifiers);
 +      for(modifier=linestyle->alpha_modifiers.first; modifier; modifier= modifier->next)
 +              direct_link_linestyle_alpha_modifier(fd, modifier);
 +      link_list(fd, &linestyle->thickness_modifiers);
 +      for(modifier=linestyle->thickness_modifiers.first; modifier; modifier= modifier->next)
 +              direct_link_linestyle_thickness_modifier(fd, modifier);
 +      link_list(fd, &linestyle->geometry_modifiers);
 +      for(modifier=linestyle->geometry_modifiers.first; modifier; modifier= modifier->next)
 +              direct_link_linestyle_geometry_modifier(fd, modifier);
 +}
 +
  /* ************** GENERAL & MAIN ******************** */
  
  
@@@ -6207,7 -6022,6 +6207,7 @@@ static const char *dataname(short id_co
                case ID_PA: return "Data from PA";
                case ID_GD: return "Data from GD";
                case ID_MC: return "Data from MC";
 +              case ID_LS: return "Data from LS";
        }
        return "Data from Lib Block";
        
@@@ -6380,9 -6194,6 +6380,9 @@@ static BHead *read_libblock(FileData *f
                case ID_MC:
                        direct_link_movieclip(fd, (MovieClip *)id);
                        break;
 +              case ID_LS:
 +                      direct_link_linestyle(fd, (FreestyleLineStyle *)id);
 +                      break;
        }
        
        /*link direct data of ID properties*/
@@@ -6668,8 -6479,8 +6668,8 @@@ static void customdata_version_242(Mes
  
                if (layer->type == CD_MTFACE) {
                        if (layer->name[0] == 0) {
-                               if (mtfacen == 0) strcpy(layer->name, "UVTex");
-                               else sprintf(layer->name, "UVTex.%.3d", mtfacen);
+                               if (mtfacen == 0) strcpy(layer->name, "UVMap");
+                               else sprintf(layer->name, "UVMap.%.3d", mtfacen);
                        }
                        mtfacen++;
                }
@@@ -7537,6 -7348,67 +7537,67 @@@ static void do_versions_nodetree_conver
        }
  }
  
+ void do_versions_image_settings_2_60(Scene *sce)
+ {
+       /* note: rd->subimtype is moved into indervidual settings now and no longer
+        * exists */
+       RenderData *rd= &sce->r;
+       ImageFormatData *imf= &sce->r.im_format;
+       imf->imtype= rd->imtype;
+       imf->planes= rd->planes;
+       imf->compress= rd->quality;
+       imf->quality= rd->quality;
+       /* default, was stored in multiple places, may override later */
+       imf->depth= R_IMF_CHAN_DEPTH_8;
+       /* openexr */
+       imf->exr_codec = rd->quality & 7; /* strange but true! 0-4 are valid values, OPENEXR_COMPRESS */
+       switch (imf->imtype) {
+       case R_IMF_IMTYPE_OPENEXR:
+               imf->depth=  (rd->subimtype & R_OPENEXR_HALF) ? R_IMF_CHAN_DEPTH_16 : R_IMF_CHAN_DEPTH_32;
+               if (rd->subimtype & R_PREVIEW_JPG) {
+                       imf->flag |= R_IMF_FLAG_PREVIEW_JPG;
+               }
+               if (rd->subimtype & R_OPENEXR_ZBUF) {
+                       imf->flag |= R_IMF_FLAG_ZBUF;
+               }
+               break;
+       case R_IMF_IMTYPE_TIFF:
+               if (rd->subimtype & R_TIFF_16BIT) {
+                       imf->depth= R_IMF_CHAN_DEPTH_16;
+               }
+               break;
+       case R_IMF_IMTYPE_JP2:
+               if (rd->subimtype & R_JPEG2K_16BIT) {
+                       imf->depth= R_IMF_CHAN_DEPTH_16;
+               }
+               else if (rd->subimtype & R_JPEG2K_12BIT) {
+                       imf->depth= R_IMF_CHAN_DEPTH_12;
+               }
+               if (rd->subimtype & R_JPEG2K_YCC) {
+                       imf->jp2_flag |= R_IMF_JP2_FLAG_YCC;
+               }
+               if (rd->subimtype & R_JPEG2K_CINE_PRESET) {
+                       imf->jp2_flag |= R_IMF_JP2_FLAG_CINE_PRESET;
+               }
+               if (rd->subimtype & R_JPEG2K_CINE_48FPS) {
+                       imf->jp2_flag |= R_IMF_JP2_FLAG_CINE_48;
+               }
+               break;
+       case R_IMF_IMTYPE_CINEON:
+       case R_IMF_IMTYPE_DPX:
+               if (rd->subimtype & R_CINEON_LOG) {
+                       imf->cineon_flag |= R_IMF_CINEON_FLAG_LOG;
+               }
+               break;
+       }
+ }
  static void do_versions(FileData *fd, Library *lib, Main *main)
  {
        /* WATCH IT!!!: pointers from libdata have not been converted */
  
        /* put compatibility code here until next subversion bump */
        {
+               Scene *sce;
+               for(sce = main->scene.first; sce; sce = sce->id.next) {
+                       if (sce->r.im_format.depth == 0) {
+                               do_versions_image_settings_2_60(sce);
+                       }
+               }
        }
  
 +      /* default values in Freestyle settings */
 +      {
 +              Scene *sce;
 +              SceneRenderLayer *srl;
 +              FreestyleLineStyle *linestyle;
 +
 +              for(sce = main->scene.first; sce; sce = sce->id.next) {
 +                      for(srl= sce->r.layers.first; srl; srl= srl->next) {
 +                              if (srl->freestyleConfig.mode == 0)
 +                                      srl->freestyleConfig.mode= FREESTYLE_CONTROL_EDITOR_MODE;
 +                              if (srl->freestyleConfig.raycasting_algorithm == 0)
 +                                      srl->freestyleConfig.raycasting_algorithm= FREESTYLE_ALGO_CULLED_ADAPTIVE_CUMULATIVE;
 +                      }
 +              }
 +              for(linestyle = main->linestyle.first; linestyle; linestyle = linestyle->id.next) {
 +                      if (linestyle->chaining == 0)
 +                              linestyle->chaining= LS_CHAINING_PLAIN;
 +                      if (linestyle->rounds == 0)
 +                              linestyle->rounds= 3;
 +              }
 +      }
 +      
        /* WATCH IT!!!: pointers from libdata have not been converted yet here! */
        /* WATCH IT 2!: Userdef struct init has to be in editors/interface/resources.c! */
  
@@@ -12802,7 -12658,6 +12869,7 @@@ static void lib_link_all(FileData *fd, 
        lib_link_brush(fd, main);
        lib_link_particlesettings(fd, main);
        lib_link_movieclip(fd, main);
 +      lib_link_linestyle(fd, main);
  
        lib_link_mesh(fd, main);                /* as last: tpage images with users at zero */
  
@@@ -13686,7 -13541,6 +13753,7 @@@ static void expand_scene(FileData *fd, 
  {
        Base *base;
        SceneRenderLayer *srl;
 +      FreestyleLineSet *lineset;
  
        for(base= sce->base.first; base; base= base->next) {
                expand_doit(fd, mainvar, base->object);
        for(srl= sce->r.layers.first; srl; srl= srl->next) {
                expand_doit(fd, mainvar, srl->mat_override);
                expand_doit(fd, mainvar, srl->light_override);
 +
 +              for (lineset= srl->freestyleConfig.linesets.first; lineset; lineset= lineset->next) {
 +                      if (lineset->group)
 +                              expand_doit(fd, mainvar, lineset->group);
 +                      expand_doit(fd, mainvar, lineset->linestyle);
 +              }
        }
  
        if(sce->r.dometext)
@@@ -13766,25 -13614,6 +13833,25 @@@ static void expand_sound(FileData *fd, 
        expand_doit(fd, mainvar, snd->ipo); // XXX depreceated - old animation system
  }
  
 +static void expand_linestyle(FileData *fd, Main *mainvar, FreestyleLineStyle *linestyle)
 +{
 +      LineStyleModifier *m;
 +
 +      if (linestyle->adt)
 +              expand_animdata(fd, mainvar, linestyle->adt);
 +      for (m = linestyle->color_modifiers.first; m; m = m->next) {
 +              if (m->type == LS_MODIFIER_DISTANCE_FROM_OBJECT)
 +                      expand_doit(fd, mainvar, ((LineStyleColorModifier_DistanceFromObject *)m)->target);
 +      }
 +      for (m = linestyle->alpha_modifiers.first; m; m = m->next){
 +              if (m->type == LS_MODIFIER_DISTANCE_FROM_OBJECT)
 +                      expand_doit(fd, mainvar, ((LineStyleAlphaModifier_DistanceFromObject *)m)->target);
 +      }
 +      for (m = linestyle->thickness_modifiers.first; m; m = m->next){
 +              if (m->type == LS_MODIFIER_DISTANCE_FROM_OBJECT)
 +                      expand_doit(fd, mainvar, ((LineStyleThicknessModifier_DistanceFromObject *)m)->target);
 +      }
 +}
  
  static void expand_main(FileData *fd, Main *mainvar)
  {
                                                break;
                                        case ID_PA:
                                                expand_particlesettings(fd, mainvar, (ParticleSettings *)id);
 +                                              break;
 +                                      case ID_LS:
 +                                              expand_linestyle(fd, mainvar, (FreestyleLineStyle *)id);
 +                                              break;
                                        }
  
                                        doit= 1;
index 358a7659d5155e2d0b10e7829ff15984d769401d,358a7659d5155e2d0b10e7829ff15984d769401d..c7a53555415615b550510be628a61ee4282cdfca
@@@ -59,7 -59,7 +59,7 @@@ typedef struct FileData 
        gzFile gzfiledes;
  
        // now only in use for library appending
--      char relabase[FILE_MAXDIR+FILE_MAXFILE];
++      char relabase[FILE_MAX];
        
        // variables needed for reading from stream
        char headerdone;
index 5e985e64288af63c2263fdedd9c276a11b408e5f,2bb70ce20b517e8cccaaa7fd0a74f4f117beb2fd..74aa502d982733dee156815bef89c1ac49406f59
@@@ -105,7 -105,6 +105,7 @@@ Any case: direct data is ALWAYS after t
  #include "DNA_key_types.h"
  #include "DNA_lattice_types.h"
  #include "DNA_lamp_types.h"
 +#include "DNA_linestyle_types.h"
  #include "DNA_meta_types.h"
  #include "DNA_mesh_types.h"
  #include "DNA_meshdata_types.h"
@@@ -1667,7 -1666,7 +1667,8 @@@ static void write_customdata(WriteData 
                                writestruct(wd, DATA, structname, datasize, layer->data);
                        }
                        else
--                              printf("error: this CustomDataLayer must not be written to file\n");
++                              printf("%s error: layer '%s':%d - can't be written to file\n",
++                                     __func__, structname, layer->type);
                }
        }
  
@@@ -1948,8 -1947,6 +1949,8 @@@ static void write_scenes(WriteData *wd
        TimeMarker *marker;
        TransformOrientation *ts;
        SceneRenderLayer *srl;
 +      FreestyleModuleConfig *fmc;
 +      FreestyleLineSet *fls;
        ToolSettings *tos;
        
        sce= scebase->first;
                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)
 +              for(srl= sce->r.layers.first; srl; srl= srl->next) {
                        writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
 +                      
 +                      for(fmc= srl->freestyleConfig.modules.first; fmc; fmc = fmc->next) {
 +                              writestruct(wd, DATA, "FreestyleModuleConfig", 1, fmc);
 +                      }
 +                      
 +                      for(fls= srl->freestyleConfig.linesets.first; fls; fls = fls->next) {
 +                              writestruct(wd, DATA, "FreestyleLineSet", 1, fls);
 +                      }
 +
 +              }
                
                if(sce->nodetree) {
                        writestruct(wd, DATA, "bNodeTree", 1, sce->nodetree);
@@@ -2584,199 -2571,6 +2585,199 @@@ static void write_movieclips(WriteData 
        mywrite(wd, MYWRITE_FLUSH, 0);
  }
  
 +static void write_linestyle_color_modifiers(WriteData *wd, ListBase *modifiers)
 +{
 +      LineStyleModifier *m;
 +      char *struct_name;
 +
 +      for (m = modifiers->first; m; m = m->next) {
 +              switch (m->type) {
 +              case LS_MODIFIER_ALONG_STROKE:
 +                      struct_name = "LineStyleColorModifier_AlongStroke";
 +                      break;
 +              case LS_MODIFIER_DISTANCE_FROM_CAMERA:
 +                      struct_name = "LineStyleColorModifier_DistanceFromCamera";
 +                      break;
 +              case LS_MODIFIER_DISTANCE_FROM_OBJECT:
 +                      struct_name = "LineStyleColorModifier_DistanceFromObject";
 +                      break;
 +              case LS_MODIFIER_MATERIAL:
 +                      struct_name = "LineStyleColorModifier_Material";
 +                      break;
 +              default:
 +                      struct_name = "LineStyleColorModifier"; // this should not happen
 +              }
 +              writestruct(wd, DATA, struct_name, 1, m);
 +      }
 +      for (m = modifiers->first; m; m = m->next) {
 +              switch (m->type) {
 +              case LS_MODIFIER_ALONG_STROKE:
 +                      writestruct(wd, DATA, "ColorBand", 1, ((LineStyleColorModifier_AlongStroke *)m)->color_ramp);
 +                      break;
 +              case LS_MODIFIER_DISTANCE_FROM_CAMERA:
 +                      writestruct(wd, DATA, "ColorBand", 1, ((LineStyleColorModifier_DistanceFromCamera *)m)->color_ramp);
 +                      break;
 +              case LS_MODIFIER_DISTANCE_FROM_OBJECT:
 +                      writestruct(wd, DATA, "ColorBand", 1, ((LineStyleColorModifier_DistanceFromObject *)m)->color_ramp);
 +                      break;
 +              case LS_MODIFIER_MATERIAL:
 +                      writestruct(wd, DATA, "ColorBand", 1, ((LineStyleColorModifier_Material *)m)->color_ramp);
 +                      break;
 +              }
 +      }
 +}
 +
 +static void write_linestyle_alpha_modifiers(WriteData *wd, ListBase *modifiers)
 +{
 +      LineStyleModifier *m;
 +      char *struct_name;
 +
 +      for (m = modifiers->first; m; m = m->next) {
 +              switch (m->type) {
 +              case LS_MODIFIER_ALONG_STROKE:
 +                      struct_name = "LineStyleAlphaModifier_AlongStroke";
 +                      break;
 +              case LS_MODIFIER_DISTANCE_FROM_CAMERA:
 +                      struct_name = "LineStyleAlphaModifier_DistanceFromCamera";
 +                      break;
 +              case LS_MODIFIER_DISTANCE_FROM_OBJECT:
 +                      struct_name = "LineStyleAlphaModifier_DistanceFromObject";
 +                      break;
 +              case LS_MODIFIER_MATERIAL:
 +                      struct_name = "LineStyleAlphaModifier_Material";
 +                      break;
 +              default:
 +                      struct_name = "LineStyleAlphaModifier"; // this should not happen
 +              }
 +              writestruct(wd, DATA, struct_name, 1, m);
 +      }
 +      for (m = modifiers->first; m; m = m->next) {
 +              switch (m->type) {
 +              case LS_MODIFIER_ALONG_STROKE:
 +                      write_curvemapping(wd, ((LineStyleAlphaModifier_AlongStroke *)m)->curve);
 +                      break;
 +              case LS_MODIFIER_DISTANCE_FROM_CAMERA:
 +                      write_curvemapping(wd, ((LineStyleAlphaModifier_DistanceFromCamera *)m)->curve);
 +                      break;
 +              case LS_MODIFIER_DISTANCE_FROM_OBJECT:
 +                      write_curvemapping(wd, ((LineStyleAlphaModifier_DistanceFromObject *)m)->curve);
 +                      break;
 +              case LS_MODIFIER_MATERIAL:
 +                      write_curvemapping(wd, ((LineStyleAlphaModifier_Material *)m)->curve);
 +                      break;
 +              }
 +      }
 +}
 +
 +static void write_linestyle_thickness_modifiers(WriteData *wd, ListBase *modifiers)
 +{
 +      LineStyleModifier *m;
 +      char *struct_name;
 +
 +      for (m = modifiers->first; m; m = m->next) {
 +              switch (m->type) {
 +              case LS_MODIFIER_ALONG_STROKE:
 +                      struct_name = "LineStyleThicknessModifier_AlongStroke";
 +                      break;
 +              case LS_MODIFIER_DISTANCE_FROM_CAMERA:
 +                      struct_name = "LineStyleThicknessModifier_DistanceFromCamera";
 +                      break;
 +              case LS_MODIFIER_DISTANCE_FROM_OBJECT:
 +                      struct_name = "LineStyleThicknessModifier_DistanceFromObject";
 +                      break;
 +              case LS_MODIFIER_MATERIAL:
 +                      struct_name = "LineStyleThicknessModifier_Material";
 +                      break;
 +              case LS_MODIFIER_CALLIGRAPHY:
 +                      struct_name = "LineStyleThicknessModifier_Calligraphy";
 +                      break;
 +              default:
 +                      struct_name = "LineStyleThicknessModifier"; // this should not happen
 +              }
 +              writestruct(wd, DATA, struct_name, 1, m);
 +      }
 +      for (m = modifiers->first; m; m = m->next) {
 +              switch (m->type) {
 +              case LS_MODIFIER_ALONG_STROKE:
 +                      write_curvemapping(wd, ((LineStyleThicknessModifier_AlongStroke *)m)->curve);
 +                      break;
 +              case LS_MODIFIER_DISTANCE_FROM_CAMERA:
 +                      write_curvemapping(wd, ((LineStyleThicknessModifier_DistanceFromCamera *)m)->curve);
 +                      break;
 +              case LS_MODIFIER_DISTANCE_FROM_OBJECT:
 +                      write_curvemapping(wd, ((LineStyleThicknessModifier_DistanceFromObject *)m)->curve);
 +                      break;
 +              case LS_MODIFIER_MATERIAL:
 +                      write_curvemapping(wd, ((LineStyleThicknessModifier_Material *)m)->curve);
 +                      break;
 +              }
 +      }
 +}
 +
 +static void write_linestyle_geometry_modifiers(WriteData *wd, ListBase *modifiers)
 +{
 +      LineStyleModifier *m;
 +      char *struct_name;
 +
 +      for (m = modifiers->first; m; m = m->next) {
 +              switch (m->type) {
 +              case LS_MODIFIER_SAMPLING:
 +                      struct_name = "LineStyleGeometryModifier_Sampling";
 +                      break;
 +              case LS_MODIFIER_BEZIER_CURVE:
 +                      struct_name = "LineStyleGeometryModifier_BezierCurve";
 +                      break;
 +              case LS_MODIFIER_SINUS_DISPLACEMENT:
 +                      struct_name = "LineStyleGeometryModifier_SinusDisplacement";
 +                      break;
 +              case LS_MODIFIER_SPATIAL_NOISE:
 +                      struct_name = "LineStyleGeometryModifier_SpatialNoise";
 +                      break;
 +              case LS_MODIFIER_PERLIN_NOISE_1D:
 +                      struct_name = "LineStyleGeometryModifier_PerlinNoise1D";
 +                      break;
 +              case LS_MODIFIER_PERLIN_NOISE_2D:
 +                      struct_name = "LineStyleGeometryModifier_PerlinNoise2D";
 +                      break;
 +              case LS_MODIFIER_BACKBONE_STRETCHER:
 +                      struct_name = "LineStyleGeometryModifier_BackboneStretcher";
 +                      break;
 +              case LS_MODIFIER_TIP_REMOVER:
 +                      struct_name = "LineStyleGeometryModifier_TipRemover";
 +                      break;
 +              case LS_MODIFIER_POLYGONIZATION:
 +                      struct_name = "LineStyleGeometryModifier_Polygonalization";
 +                      break;
 +              case LS_MODIFIER_GUIDING_LINES:
 +                      struct_name = "LineStyleGeometryModifier_GuidingLines";
 +                      break;
 +              case LS_MODIFIER_BLUEPRINT:
 +                      struct_name = "LineStyleGeometryModifier_Blueprint";
 +                      break;
 +              default:
 +                      struct_name = "LineStyleGeometryModifier"; // this should not happen
 +              }
 +              writestruct(wd, DATA, struct_name, 1, m);
 +      }
 +}
 +
 +static void write_linestyles(WriteData *wd, ListBase *idbase)
 +{
 +      FreestyleLineStyle *linestyle;
 +
 +      for(linestyle=idbase->first; linestyle; linestyle= linestyle->id.next) {
 +              if(linestyle->id.us>0 || wd->current) {
 +                      writestruct(wd, ID_LS, "FreestyleLineStyle", 1, linestyle);
 +                      if (linestyle->id.properties) IDP_WriteProperty(linestyle->id.properties, wd);
 +                      if (linestyle->adt) write_animdata(wd, linestyle->adt);
 +                      write_linestyle_color_modifiers(wd, &linestyle->color_modifiers);
 +                      write_linestyle_alpha_modifiers(wd, &linestyle->alpha_modifiers);
 +                      write_linestyle_thickness_modifiers(wd, &linestyle->thickness_modifiers);
 +                      write_linestyle_geometry_modifiers(wd, &linestyle->geometry_modifiers);
 +              }
 +      }
 +}
 +
  /* 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 */
@@@ -2879,7 -2673,6 +2880,7 @@@ static int write_file_handle(Main *main
        write_brushes  (wd, &mainvar->brush);
        write_scripts  (wd, &mainvar->script);
        write_gpencils (wd, &mainvar->gpencil);
 +      write_linestyles(wd, &mainvar->linestyle);
        write_libraries(wd,  mainvar->next);
  
        if (write_user_block) {
  /* return: success(0), failure(1) */
  static int do_history(const char *name, ReportList *reports)
  {
--      char tempname1[FILE_MAXDIR+FILE_MAXFILE], tempname2[FILE_MAXDIR+FILE_MAXFILE];
++      char tempname1[FILE_MAX], tempname2[FILE_MAX];
        int hisnr= U.versions;
        
        if(U.versions==0) return 0;
  /* return: success (1) */
  int BLO_write_file(Main *mainvar, const char *filepath, int write_flags, ReportList *reports, int *thumb)
  {
--      char userfilename[FILE_MAXDIR+FILE_MAXFILE];
--      char tempname[FILE_MAXDIR+FILE_MAXFILE+1];
++      char userfilename[FILE_MAX];
++      char tempname[FILE_MAX+1];
        int file, err, write_user_block;
  
        /* open temporary file, so we preserve the original in case we crash */
  
        /* remapping of relative paths to new file location */
        if(write_flags & G_FILE_RELATIVE_REMAP) {
--              char dir1[FILE_MAXDIR+FILE_MAXFILE];
--              char dir2[FILE_MAXDIR+FILE_MAXFILE];
++              char dir1[FILE_MAX];
++              char dir2[FILE_MAX];
                BLI_split_dir_part(filepath, dir1, sizeof(dir1));
                BLI_split_dir_part(mainvar->name, dir2, sizeof(dir2));
  
  
        if(write_flags & G_FILE_COMPRESS) {
                /* compressed files have the same ending as regular files... only from 2.4!!! */
--              char gzname[FILE_MAXDIR+FILE_MAXFILE+4];
++              char gzname[FILE_MAX+4];
                int ret;
  
                /* first write compressed to separate @.gz */
index def6cd61370482d28133a189a515b6a5160b9770,def6cd61370482d28133a189a515b6a5160b9770..d40831f9e8776bd70a2f3bd9966e4d6a84fe6272
@@@ -107,7 -107,7 +107,7 @@@ static void gp_draw_stroke_buffer (tGPs
        if (totpoints == 1) {           
                /* draw point */
                glBegin(GL_POINTS);
--                      glVertex2f(points->x, points->y);
++                      glVertex2iv(&points->x);
                glEnd();
        }
        else if (sflag & GP_STROKE_ERASER) {
                                glBegin(GL_LINE_STRIP);
                                
                                /* need to roll-back one point to ensure that there are no gaps in the stroke */
--                              if (i != 0) {
--                                      pt--;
--                                      glVertex2f(pt->x, pt->y);
--                                      pt++;
--                              }
++                              if (i != 0) glVertex2iv(&(pt - 1)->x);
++
                                /* now the point we want... */
--                              glVertex2f(pt->x, pt->y);
++                              glVertex2iv(&pt->x);
                                
                                oldpressure = pt->pressure;
                        }
                        else
--                              glVertex2f(pt->x, pt->y);
++                              glVertex2iv(&pt->x);
                }
                glEnd();
  
@@@ -162,7 -162,7 +159,7 @@@ static void gp_draw_stroke_point (bGPDs
        /* draw point */
        if (sflag & GP_STROKE_3DSPACE) {
                glBegin(GL_POINTS);
--                      glVertex3f(points->x, points->y, points->z);
++                      glVertex3fv(&points->x);
                glEnd();
        }
        else {
@@@ -228,18 -228,18 +225,16 @@@ static void gp_draw_stroke_3d (bGPDspoi
                        glBegin(GL_LINE_STRIP);
                        
                        /* need to roll-back one point to ensure that there are no gaps in the stroke */
--                      if (i != 0) {
--                              pt--;
--                              glVertex3f(pt->x, pt->y, pt->z);
--                              pt++;
--                      }
++                      if (i != 0) glVertex3fv(&(pt - 1)->x);
++
                        /* now the point we want... */
--                      glVertex3f(pt->x, pt->y, pt->z);
++                      glVertex3fv(&pt->x);
                        
                        oldpressure = pt->pressure;
                }
--              else
--                      glVertex3f(pt->x, pt->y, pt->z);
++              else {
++                      glVertex3fv(&pt->x);
++              }
        }
        glEnd();
        
        if (debug) {
                glBegin(GL_POINTS);
                for (i=0, pt=points; i < totpoints && pt; i++, pt++)
--                      glVertex3f(pt->x, pt->y, pt->z);
++                      glVertex3fv(&pt->x);
                glEnd();
        }
  }
@@@ -461,7 -461,7 +456,7 @@@ static void gp_draw_stroke (bGPDspoint 
                glBegin(GL_POINTS);
                for (i=0, pt=points; i < totpoints && pt; i++, pt++) {
                        if (sflag & GP_STROKE_2DSPACE) {
--                              glVertex2f(pt->x, pt->y);
++                              glVertex2fv(&pt->x);
                        }
                        else if (sflag & GP_STROKE_2DIMAGE) {
                                const float x= (float)((pt->x * winx) + offsx);
index f09797bf6f1bcb6cd81d2280ea58bb50408e23b9,f09797bf6f1bcb6cd81d2280ea58bb50408e23b9..6c93727bf55394d19c43d70b2ab4460fa9397239
@@@ -331,8 -331,8 +331,7 @@@ static short gp_stroke_addpoint (tGPsda
                        pt= (tGPspoint *)(gpd->sbuffer);
                        
                        /* store settings */
--                      pt->x= mval[0];
--                      pt->y= mval[1];
++                      copy_v2_v2_int(&pt->x, mval);
                        pt->pressure= pressure;
                        
                        /* increment buffer size */
                        pt= ((tGPspoint *)(gpd->sbuffer) + 1);
                        
                        /* store settings */
--                      pt->x= mval[0];
--                      pt->y= mval[1];
++                      copy_v2_v2_int(&pt->x, mval);
                        pt->pressure= pressure;
                        
                        /* if this is just the second point we've added, increment the buffer size
                pt= ((tGPspoint *)(gpd->sbuffer) + gpd->sbuffer_size);
                
                /* store settings */
--              pt->x= mval[0];
--              pt->y= mval[1];
++              copy_v2_v2_int(&pt->x, mval);
                pt->pressure= pressure;
                
                /* increment counters */
                pt= (tGPspoint *)(gpd->sbuffer);
  
                /* store settings */
--              pt->x= mval[0];
--              pt->y= mval[1];
++              copy_v2_v2_int(&pt->x, mval);
                pt->pressure= pressure;
  
                /* if there's stroke for this poly line session add (or replace last) point
@@@ -475,9 -475,9 +471,8 @@@ static void gp_stroke_smooth (tGPsdata 
        /* second pass: apply smoothed coordinates */
        for (i=0, spc=smoothArray; i < gpd->sbuffer_size; i++, spc++) {
                tGPspoint *pc= (((tGPspoint *)gpd->sbuffer) + i);
--              
--              pc->x = spc->x;
--              pc->y = spc->y;
++
++              copy_v2_v2_int(&pc->x, &spc->x);
        }
        
        /* free temp array */
@@@ -653,7 -653,7 +648,7 @@@ static void gp_stroke_newfrombuffer (tG
                        depth_arr= MEM_mallocN(sizeof(float) * gpd->sbuffer_size, "depth_points");
  
                        for (i=0, ptc=gpd->sbuffer; i < gpd->sbuffer_size; i++, ptc++, pt++) {
--                              mval[0]= ptc->x; mval[1]= ptc->y;
++                              copy_v2_v2_int(mval, &ptc->x);
  
                                if ((ED_view3d_autodist_depth(p->ar, mval, depth_margin, depth_arr+i) == 0) &&
                                        (i && (ED_view3d_autodist_depth_seg(p->ar, mval, mval_prev, depth_margin + 1, depth_arr+i) == 0))
index a0b477413e48cba55867f0c37d39d51c5230d2ad,ec6958c841512875534d8b6efbe24d632d922238..d1f11d60999f2df3159e09428c46d362c0f9d60a
@@@ -115,12 -115,13 +115,14 @@@ typedef struct uiLayout uiLayout
  #define UI_BLOCK_OUT_1                        1024
  #define UI_BLOCK_NO_FLIP              2048
  #define UI_BLOCK_POPUP_MEMORY 4096
+ #define UI_BLOCK_CLIP_EVENTS  8192    /* stop handling mouse events */
  
  /* uiPopupBlockHandle->menuretval */
  #define UI_RETURN_CANCEL      1       /* cancel all menus cascading */
  #define UI_RETURN_OK        2       /* choice made */
  #define UI_RETURN_OUT       4       /* left the menu */
  #define UI_RETURN_UPDATE    8       /* update the button that opened */
++#define UI_RETURN_POPUP_OK  16      /* popup is ok to be handled */
  
        /* block->flag bits 12-15 are identical to but->flag bits */
  
@@@ -277,6 -278,6 +279,30 @@@ void uiDrawBoxVerticalShade(int mode, f
  #define UI_SCROLL_NO_OUTLINE  4
  void uiWidgetScrollDraw(struct uiWidgetColors *wcol, struct rcti *rect, struct rcti *slider, int state);
  
++/* Callbacks
++ *
++ * uiBlockSetHandleFunc/ButmFunc are for handling events through a callback.
++ * HandleFunc gets the retval passed on, and ButmFunc gets a2. The latter is
++ * mostly for compatibility with older code.
++ *
++ * uiButSetCompleteFunc is for tab completion.
++ *
++ * uiButSearchFunc is for name buttons, showing a popup with matches
++ *
++ * uiBlockSetFunc and uiButSetFunc are callbacks run when a button is used,
++ * in case events, operators or RNA are not sufficient to handle the button.
++ *
++ * uiButSetNFunc will free the argument with MEM_freeN. */
++
++typedef struct uiSearchItems uiSearchItems;
++
++typedef void (*uiButHandleFunc)(struct bContext *C, void *arg1, void *arg2);
++typedef void (*uiButHandleRenameFunc)(struct bContext *C, void *arg, char *origstr);
++typedef void (*uiButHandleNFunc)(struct bContext *C, void *argN, void *arg2);
++typedef void (*uiButCompleteFunc)(struct bContext *C, char *str, void *arg);
++typedef void (*uiButSearchFunc)(const struct bContext *C, void *arg, const char *str, uiSearchItems *items);
++typedef void (*uiBlockHandleFunc)(struct bContext *C, void *arg, int event);
++
  /* Menu Callbacks */
  
  typedef void (*uiMenuCreateFunc)(struct bContext *C, struct uiLayout *layout, void *arg1);
@@@ -312,7 -313,7 +338,7 @@@ typedef void (*uiBlockCancelFunc)(void 
  
  void uiPupBlock(struct bContext *C, uiBlockCreateFunc func, void *arg);
  void uiPupBlockO(struct bContext *C, uiBlockCreateFunc func, void *arg, const char *opname, int opcontext);
--void uiPupBlockEx(struct bContext *C, uiBlockCreateFunc func, uiBlockCancelFunc cancel_func, void *arg);
++void uiPupBlockEx(struct bContext *C, uiBlockCreateFunc func, uiBlockHandleFunc popup_func, uiBlockCancelFunc cancel_func, void *arg);
  /* void uiPupBlockOperator(struct bContext *C, uiBlockCreateFunc func, struct wmOperator *op, int opcontext); */ /* UNUSED */
  
  void uiPupBlockClose(struct bContext *C, uiBlock *block);
@@@ -364,6 -365,7 +390,7 @@@ void uiTextBoundsBlock(uiBlock *block, 
  void uiPopupBoundsBlock(uiBlock *block, int addval, int mx, int my);
  void uiMenuPopupBoundsBl